Trent Trent - 22 days ago 13
Javascript Question

Pass object to PHP through AJAX

I was wondering if it is possible to pass an array to a php function using the jQuery AJAX function. I have the following as my javascript

arr_data = {
field01: "data 01",
field02: "data 02",
field03: "data 03",
field04: "data 04"
}

$.ajax({
url: "scripts/php/phpfunc.php",
type: "GET",
dataType: "json",
data: {
'action': "exec_find",
'field01': arr_data["field01"],
'field02': arr_data["field02"],
'field03': arr_data["field03"],
'field04': arr_data["field04"]
},
success: function(result) {
// continue program
},
error: function(log) {
// handle error
}
});


When I try to do the following though

arr_data = {
field01: "data 01",
field02: "data 02",
field03: "data 03",
field04: "data 04"
}

$.ajax({
url: "scripts/php/phpfunc.php",
type: "GET",
dataType: "json",
data: {
'action': "exec_find",
'data': arr_data
},
success: function(result) {
// continue program
},
error: function(log) {
// handle error
}
});


I receive it in the PHP as "Array". How can I correctly send the object so that it is usable by the PHP function?

Answer

from the second ajax you can access the data based on the property names like: $_GET['data']['field01']

$_GET['data'] is the js object converted in php in a associative array

Comments