Php ajax вернуть массив

Ajax return array shows [object Object],[object Object] in PHP

I am then putting this though Ajax and extracting the variable via PHP on the other side. The results of a print_r($arrayTwo) are as follows.

Array([foo] => blah [arrayOne] => [object Object],[object Object]) 

I can see no way of extracting the contents of arrayOne, which is a pity because I really need them! Can anyone tell me what I am doing wrong in Jquery or what I need to do in PHP to make the embedded array accessible. Many thanks as always Edit to add my Ajax code.

Seems like you are not serializing your data properly before you send it. [object Object] is the default string representation of a JavaScript object: console.log(<>.toString()) . Post the code you use to send the data.

1 Answer 1

The issue is that jQuery’s $.ajax (or rather $.param ) method treats an array of objects in a special way. jQuery will use name as the parameter name and the string representation of value as value:

But the string representation of arrayOne is the useless stuff you are seeing on the server:

> [, ].toString() "[object Object],[object Object]" 

The documentation actually points out the caveats when passing an array / object:

If the object passed is in an Array, it must be an array of objects in the format returned by .serializeArray()

Note: Because some frameworks have limited ability to parse serialized arrays, developers should exercise caution when passing an obj argument that contains objects or arrays nested within another array.

Читайте также:  Функция вычисления среднего питон

Note: Because there is no universally agreed-upon specification for param strings, it is not possible to encode complex data structures using this method in a manner that works ideally across all languages supporting such input. Use JSON format as an alternative for encoding complex data instead.

Since you have a complex data structure, you should probably use JSON to encode your data:

and on the server you simply decode it with

$data = json_decode($_POST['data'], true); 

$data will have the exact same structure as arrayTwo .

But in case you want to actually have parameters with names foo and arrayOne , then you only need to serialize the the value of arrayOne :

$arrayOne = json_decode($_POST['arrayOne'], true); 

Источник

Как вернуть массив из вызова AJAX?

Я ищу лучшее решение для создания AJAX-вызова с помощью jQuery, когда PHP файл возвращает массив, и выйдет он на стороне клиента как массив Javascript. Вот что я делаю: Файл PHP (Example.php):

id_numbers = new Array(); $.ajax( < url:"Example.php", type:"POST", success:function(msg)< id_numbers = msg.split('|'); >>); 

на стороне PHP и непосредственно перевести его в массив Javascript после вызова AJAX. Идеи, кто-нибудь?

5 ответов

echo json_encode($id_numbers); 

Как упоминал Вольфганг, вы можете дать четвертый параметр jQuery для автоматического декодирования JSON для вас.

id_numbers = new Array(); $.ajax(< url:"Example.php", type:"POST", success:function(msg)< id_numbers = msg; >, dataType:"json" >); 

@k_sel это в значительной степени промышленный стандарт. Все используют это для AJAX. Вы заметите, что JSON также является допустимым JavaScript.

Посмотрите json_encode() в PHP. Вы можете получить $.ajax, чтобы распознать это с помощью параметра dataType: «json».

@Xeon06, приятно, но точно так же, как fyi для тех, кто читал эту тему и пробовал, как я. при возврате массива из php = > json_encode($theArray) . преобразует в строку, которая мне нелегко манипулировать esp для таких мягких пользователей, как я.

Внутри js вы пытаетесь получить значения массива и/или ключи массива u r лучше, используя JSON.parse, как в var jsArray = JSON.parse(data) , где data — это возвращаемый массив из php. строка, закодированная json, преобразуется в объект js, который теперь можно легко манипулировать.

например. foo = — получил после JSON.parse

Как это ни странно, если вы работаете с многомерными массивами, попробуйте и json_encode внутренние массивы, таким образом, $parent_array = array (json_encode($child_array)); , Это сработало в моем случае.

Php имеет супер-сексуальную функцию для этого, просто передайте ему массив:

$json = json_encode($var); $.ajax( < url:"Example.php", type:"POST", dataType : "json", success:function(msg)< console.info(msg); >>); 

Источник

Как вернуть массив из вызова AJAX?

Я ищу лучшее решение для создания AJAX-вызова с помощью jQuery, если PHP-файл возвращает массив и выйдет на стороне клиента как массив Javascript. Вот что я делаю:

Мой текущий метод просто слишком запутан для моего вкуса.

Я бы хотел, чтобы вы могли просто

на стороне PHP и непосредственно перевести его в массив Javascript после вызова AJAX.

Используйте JSON для передачи типов данных (массивов и объектов) между клиентом и сервером.

echo json_encode($id_numbers); 

Как упоминал Вольфганг, вы можете дать четвертый параметр jQuery для автоматического декодирования JSON для вас.

id_numbers = new Array(); $.ajax(< url:"Example.php", type:"POST", success:function(msg)< id_numbers = msg; >, dataType:"json" >); 

Посмотрите на json_encode () в PHP. Вы можете получить $ .ajax, чтобы распознать это с помощью параметра dataType: «json».

@ Xeon06, приятно, но точно так же, как fyi для тех, кто читал этот поток и пробовал, как я … при возврате массива из php => json_encode($theArray) . конвертирует в строку, которая мне нелегко манипулировать esp для таких мягких js-пользователей, как я.

Внутри js вы пытаетесь получить значения массива и / или ключи массива ur лучше, используя JSON.parse, как в var jsArray = JSON.parse(data) где data – это возвращаемый массив из php. строка, закодированная json, преобразуется в объект js, который теперь можно легко манипулировать.

например foo = – получил после JSON.parse

for (key in foo) < console.log("foo["+ key +"]="+ fooPhp ajax вернуть массив) >– печатает на консоли firebug. вуаля!

Посмотрите на json_encode (http://php.net/manual/en/function.json-encode.php). Он доступен с PHP 5.2. Используйте параметр dataType: ‘json’ чтобы он разбирался для вас. Тогда у вас будет объект как первый аргумент. Для получения дополнительной информации смотрите jQuery-документацию: http://api.jquery.com/jQuery.ajax/

Php имеет супер-сексуальную функцию для этого, просто передайте массив:

$json = json_encode($var); $.ajax( < url:"Example.php", type:"POST", dataType : "json", success:function(msg)< console.info(msg); >>); 

Источник

How return array in function() to javascript on wordpress ajax.php with following code:

If you want to use your getHomeSliderSeries function through AJAX then you have to tell the PHP script. You can do this by sending an action key where the value is the name of the function, for example: < action: 'getHomeSliderSeries' >or ‘action=getHomeSliderSeries’ . Without it the server won’t know what function the call.

And you have JavaScript in your PHP function. Instead use an associative array and turn it into JSON with json_encode() . Then return the JSON.

but if i want keep and send data on .php its possible to use post like this? $id = isset($_POST[‘id’]) ? $_POST[‘id’] : null

Check the answer below. If you have any questions, feel free to leave them below the answer and I’ll get to them as soon as I can.

2 Answers 2

Try ajax callback function in functions.php

function swt_ajax_data() < $id = isset($_POST['id']) ? $_POST['id'] : ''; // Create an associative array for the response. $responsedata = array( 'id' =>$id, ); $result = array(); // if need featch the data from the template un comment the bellow five lines and commented the sixth line //ob_start(); //include('templatepatj'); //$opr_html .= ob_get_contents(); //ob_get_clean(); // $result['data'] = $opr_html; $result['data'] = $responsedata;// POST array data. > return wp_send_json_success($result); > > add_action('wp_ajax_swt_ajax_data', 'swt_ajax_data'); add_action('wp_ajax_nopriv_swt_ajax_data', 'swt_ajax_data'); 

Localize your script and pass the admin ajax url

// Register the script wp_register_script( 'ajax-script', 'path/to/myscript.js' ); // Localize the script with new data $js_array = array( 'ajaxurl' => admin_url('admin-ajax.php'), ); wp_localize_script( 'ajax-script', 'swtobj', $js_array ); // Enqueued script with localized data. wp_enqueue_script( 'ajax-script' ); 
$(document).on("click", "[data-show-home-list-series]", function () < var $("[data-show-home-list-series]").removeClass("active"); $(this).addClass("active"); var $list = $("#homeSliderSerieList"); var data = < 'action': 'swt_ajax_data', 'id': id >; $.ajax( < url: swtobj.ajaxurl, type: 'POST', data: data, cache: false, dataType: 'json', success: function (response, textStatus, jqXHR) < var response_data = response.data.data; if (response_data != "" || response_data.length != 0) < console.log(response_data); // write your code here >else < // write your code here >>, >); >); 

The data you send in $.post is missing an action property. This property is responsible for telling the admin-ajax.php which function that is registered with a wp_ajax_ hook should be called.

The value in the action property should match the function_name in wp_ajax_ and wp_ajax_nopriv_ to be called properly.

Combine the action property with other properties that you want to send to the backend to pass the data that you need to send.

// Set the action and get the id. var action = 'getHomeSliderSeries'; var Create object to send data to backend. // This must include an action property with // the name of the function on the backend. var postData = < action: action, id: id, example: 'Send any data as a property. You can also nest objects and arrays.' >; $.post("wp-admin/admin-ajax.php", postData, function(response) < if (response.status == "success") < console.log(response); >>, 'json'); // Expect JSON from the backend. Now you don't need to parse. 

Now on the server side your getHomeSliderSeries should be called. All the other properties (action included) can now be accessed through the global $_POST variable with their corresponding keys.

For a response, create an associative array with the data you want to return. This is the equivalent of an object in JavaScript. Encode the array to JSON and send it back. Now the frontend should see an object as a response.

function getHomeSliderSeries() < // Get the id from the post request. $id = isset($_POST['id']) ? $_POST['id'] : null; $example_string = isset($_POST['example_string']) ? $_POST['example_string'] : null; // Create an associative array for the response. $response = array( 'status' =>'success', 'id' => $id, 'example' => $example_string ); // Return the array as a JSON string. return json_encode($response); // Cuts connection by stopping the function. die(); > add_action( 'wp_ajax_getHomeSliderSeries', 'getHomeSliderSeries' ); add_action( 'wp_ajax_nopriv_getHomeSliderSeries', 'getHomeSliderSeries' ); 

Источник

Оцените статью