Reputation: 433
I am sending a JSON array with this data to my server:
[{"name":"Dinner","value":"3"},
{"name":"Happy_Hour","value":"3"},
{"name":"client_id","value":"55"}]
using AJAX:
$.ajax({
async: false,
url: 'http://****',
data: MyJsonArray,
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'submitCallback',
success: function(){
alert("success");
},
error: function(xhr, status, errorThrown){
alert("submit interests error" + status);
},
complete: function(){
}
}); //ajax
I would then like to update a table for the column names ("Dinner" and "Happy_Hour") with the values for each respective name using PHP. Normally, I would use $_GET['Happy_Hour']
, and UPDATE table_name SET Happy_Hour=?, etc_etc=? WHERE id=?
, but now I should somehow iterate through an array in order get the keys/value. How can I transition from having to use $_GET['hardcoded_name']
to getting an array of those keys/values?
EDIT
The JSON object I referred to was actually an array, so I changed it (top). I got it by calling MyHTMLForm.serializeArray();
Upvotes: 1
Views: 392
Reputation: 41873
If you do not want use a hardcoded indices you can put it inside to another parent:
$.ajax({
data: {data: MyJsonObject},
// ... others
});
Then on the PHP script, call that parent holder:
<?php
if(isset($_GET['data'])) {
$data = $_GET['data'];
foreach($data as $val) {
$val['name'] // the particular key Dinner, ,Happy_Hour
$val['value'] // the corresponding value 3, 3, 55
// rest of insert code
}
}
?>
Upvotes: 1