- выводить массив через Ajax на PHP
- How to work with jQuery AJAX and PHP array return [duplicate]
- 5 Answers 5
- PHP Code:
- jQuery script
- Как передать массив данных из ajax в php
- How to Send JavaScript Array to the AJAX using jQuery and PHP
- Contents
- 1. Create a Table
- 2. Create a file for Database connection
- 3. HTML Layout
- 4. AJAX – Receiving the JavaScript Array in PHP
- 5. jQuery – Sending the JavaScript Array to Server-side using AJAX
- 6. Demo
- 7. Conclusion
выводить массив через Ajax на PHP
Сделал рабочий пример использования ajax-запроса для отправки со страницы данных на сервер(PHP), получения от него новых данных и вывода их на странице.
Это должно помочь разобраться в вашем вопросе.
- На странице пользователь вводит через запятую значения и нажимает кнопку.
- Клик-событие вызывает ajax-запрос (post + json) к php-скрипту на сервере, который передает в параметре data массив значений, полученных с помощью преобразования значений введеной на странице строки в массив(разделитель — символ запятой).
- PHP-скрипт проверяет факт того, что совершен POST-запрос — значение параметра data супер-массива $_POST определено и если это так, то извлекает значения переданного массива data , добавляет в него два значения three и four , возвращает его в виде json-ответа и завершает свою работу.
- Когда ответ от php-скрипта сервера получен, то полученные данные из массива преобразовываются в строку и отображаются на странице.
else < $data = $_POST['data']; >$data[] = "three!"; $data[] = "four!"; echo json_encode($data); exit; > ?> Входные данные на сервер:
Выходные данные от сервера:
спасибо болшое! многие вещи прояснились. А если нужно сделать так, чтобы массив вводился на одной странице — index.php , а передавался на другую, например, show.php. То есть мне нужно получить этот массив для последующей записи в файл.
я сделала, как вы сказали. но при этом у меня не получается вывести массив на другой странице. выводится null
Когда вы отправляете ajax запрос на ту же страницу, она уже отрисована и php отработал. Что бы пыха подобрала данные из массива $_post ей (пыхе, которая на сервере) нужно послать запрос на новую отрисовку страницы с данными из массива $_post . В вашем примере нет необходимости во вставке фрагмента php кода, достаточно результат подставить динамически тем же js
Что бы пыхой ловить $_POST, надо перезагружать страницу. Это не ajax кейс . Именно в вашем случае нужна форма. Если вам надо отправить данные на файл-обработчик, что-то сделать с данными и вернуть некий результат обратно и всё это без перезагрузки страницы — тогда ajax
How to work with jQuery AJAX and PHP array return [duplicate]
I want to do action in client side based on this. Say if array[0] is ‘b’, I want to alert «hi». Again if array[2] is ‘x’, I want to alert «hello», and so on. How can I filter array elements in order to grab their data?
5 Answers 5
You will have to return the array encoded in the json form like following
$array = array("a","b","c","d"); echo json_encode($array);
then you can access it in javascript converting it back to an array/object like
var result = eval(retuned_value);
You can also navigate through all array elements using a for loop
in your code it should look something like:
PHP Code:
$array = array("a","b","c","d"); echo json_encode( $array );
jQuery script
i got it worked with eval but not worked without eval. also my php script didnt set to any specific header like HMR says on below answer.
and in javascript create an object from the json string, you can do this with using getJSON instead of ajax http://api.jquery.com/jQuery.getJSON/
Make sure your php sets the right response header:
header ("content-type: application/json; charset=utf-8");
I find the best way to return an array from php to Ajax (jscript):
on the php side: echo json_encode($myArray); on the javascript side (e.g. myAjax.responseText ) replyVal = JSON.parse(myAjax.responseText);
To send arrays TO php from javascript, use the matching JSON.stringify() to send and php json_decode() to receive
In your PHP code encode the array as JSON object
Then you need to convert the JSON object into a Javascript/jQuery-compatible object. Afterwards you can convert back to an array
$.ajax( < success: function(result) < jq_json_obj = $.parseJSON(result); //Convert the JSON object to jQuery-compatible if(typeof jq_json_obj == 'object')< //Test if variable is a [JSON] object jq_obj = eval (jq_json_obj); //Convert back to an array jq_array = []; for(elem in jq_obj)< jq_array.push(jq_obj[elem]); >console.log(jq_array); >else < console.log("Error occurred!"); >> >);
Как передать массив данных из ajax в php
Для передачи информации с помощью Ajax в PHP необходимо использовать параметр data в методе ajax . В данный параметр можно передать массив данных в формате JSON.
$.ajax( url: 'example.php', type: 'POST', data: array: JSON.stringify(data) >, success: function(response) // Обработка ответа > >);
В PHP можно получить массив данных с помощью функции json_decode:
$data = json_decode($_POST['array']);
How to Send JavaScript Array to the AJAX using jQuery and PHP
The process of sending JavaScript arrays to the server-side using AJAX is a frequent requirement in web development. JavaScript arrays allow us to store and manage data in a structured format.
This can be used to pass the group of related values as data to the $.ajax for processing and get the response.
E.g. pass all checked checkboxes values, selected values from the list.
In this tutorial, you will learn how to send a JavaScript array to the server-side using AJAX, jQuery, and PHP with a live example.
Contents
1. Create a Table
I am using userinfo table in the example.
CREATE TABLE `userinfo` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `name` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, `lang` varchar(100) NOT NULL, `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP );
2. Create a file for Database connection
Create a config.php file for the database connection.
3. HTML Layout
Create a basic form layout that includes two input elements, multiple checkboxes, and a button.
To ensure that the data is sent correctly, make sure to use the same name attribute for the checkboxes, such as name=»prolang» .
Once the AJAX request is successful, the data received from the server can be displayed in the element.
Enter DetailsLanguages you now?JavaScript
jQuery
AngularJS
NodeJS
TypeScript
4. AJAX – Receiving the JavaScript Array in PHP
To handle AJAX requests, create a file named getData.php . In this file, retrieve the values from the $_POST .
Check if the $_POST[‘lang’] variable contains the string “jQuery”. If it does, convert the array into a string using the implode() function. This is required as MySQL does not support storing arrays. You can also store it in serialized form using serialize() function.
After that, store the retrieved values into the userinfo table. Initialize a new array called $return_arr with the stored values, and return it in the JSON format. This will enable you to send the data back to the client-side.
// Converting the array to comma separated string $lang = implode(",",$lang); // check entry $sql = "SELECT COUNT(*) AS cntuser from userinfo WHERE email='".$email."'"; $result = mysqli_query($con,$sql); $row = mysqli_fetch_array($result); $count = $row['cntuser']; if($count > 0)< // update $updatequery = "UPDATE userinfo SET name='".$name."',lang='".$lang."' WHERE email='".$email."'"; mysqli_query($con,$updatequery); >else < // insert $insertquery = "INSERT INTO userinfo(name,email,lang) VALUES('".$name."','".$email."','".$lang."')"; mysqli_query($con,$insertquery); >$return_arr = array('name'=>$name,'email'=>$email,'lang'=>$lang,"foundjquery"=>$foundjquery); echo json_encode($return_arr);
5. jQuery – Sending the JavaScript Array to Server-side using AJAX
When the submit button is clicked, retrieve the input values and initialize an array called lang by looping through the checked checkboxes using the $(«input[name=’prolang’]:checked») selector and the .each() function.
Passing the initialized variables as data in AJAX request.
Here, name and email are string type variables and lang is an Array variable.
Note – You can pass JavaScript Array variable as same as any other variable in AJAX request.
$(document).ready(function()< // submit button click $("#submit").click(function()< var name = $("#txt_name").val(); var email = $("#txt_email").val(); var lang = []; // Initializing array with Checkbox checked values $("input[name='prolang']:checked").each(function()< lang.push(this.value); >); if(email != '')< $.ajax(< url: 'getData.php', type: 'post', data: , dataType: 'JSON', success: function(response) < $('.details').show(); // selecting values from response Object var name = response.name; var email = response.email; var lang = response.lang; var foundjquery = response.foundjquery; // setting values $('#name').text(name); $('#email').text(email); $('#lang').text(lang); $('#foundjquery').text(foundjquery); >>); > >); >);
6. Demo
7. Conclusion
Passing a JavaScript array variable in the $.ajax() method is as simple as passing any other variable.
You can use it as a typical PHP array variable in the PHP script. The data is sent and received accurately with this method, and it can be stored in the database or altered as necessary.
If you found this tutorial helpful then don’t forget to share.