Reputation: 2077
im trying to figure out how to properly insert key=>value
pair to an array using array_unshift
this is my code.
Javascript/AJAX
var array= {};
array['name'] = name;
array['lname'] = lname;
$.ajax ({
type:"POST",
url:"some.php",
data: {array:array},
success: function(html) {}
});
PHP will then receive the array via POST
$array = $_post['array'];
//add additional key=>value pair in the array
array_unshift($array, "['middle']=>test");
return $array;
Im not getting any errors from it, i just dont see the value being printed from the function.
Printed Result:
Object {name: "John", lname: "Smith"}
edit:typo
Upvotes: 0
Views: 198
Reputation: 13843
I don't think you're doing it right...
You can't alter a JavaScript array (it's an object actually) via PHP. However, you can fetch new data and replace the JavaScript object.
Because I'm expecting an object, I might as well use the JSON format - thus use $.getJSON()
instead. Note that this is a GET request on default.
var url = 'file.php';
var obj = {
name: name,
lname: lname
};
$.getJSON(url, { data:obj }, function(data) {
// replace object with new content
obj = data;
console.log(obj);
});
As for your PHP code:
// get data (remember we're using a GET request)
$data = $_GET['data'];
// add an index
$data['middle'] = 'test';
// echo data in JSON format
echo json_encode($data);
Upvotes: 1
Reputation: 28753
Rename the person
to array
like
var array= {};
array['name'] = name;
array['lname'] = lname;
$.ajax ({
type:"POST",
url:"some.php",
data: {array:array},
success: function(html) {}
});
Or send the person
array as array
data: {array:person},
EDIT :.Simple try like
$array['middle'] = 'test';
Upvotes: 0
Reputation: 2375
// not var array= {};
var person = {}
person['name'] = name;
person['lname'] = lname;
Upvotes: 0