I am trying to edit a data query using php by passing it through javascript,
my ajax request looks like
var totalSearchResult=10;
$.ajax({
url:"php/queryManipulation.php",
type: 'POST',
data: { totalQuery : totalSearchResult, query : '{"data":{"match_all":{}}}'},
success: function(finalList)
{
alert(finalList);
}
});
my php code looks like
<?php
$from=$_POST["totalQuery"];
$qry=json_decode($_POST["query"]);
$qry->from=$from; }?>
I am trying to get it in the form,
{"data": {"match_all": {}} , "from": 10}
I get the error Object of class stdClass could not be converted to string
Edit: Changed json_decode return value from array to object
You need to encode the json again just after finishing the edits.
So what you can do is something like:
<?php
$from = $_POST["totalQuery"];
$qry = json_decode($_POST["query"]);
$qry->data->from = $from;
//you will get the new json string
//as the finalList variable in your post callback
echo json_encode($qry);
?>
You should use json_decode($string, true) - so it will be an array.
Details here: http://php.net/manual/en/function.json-decode.php
You can decode to an array (not sure about objects) and re-encode:
$qry = json_decode($_POST['query'], TRUE);
$qry['from'] = 10;
$new_qry = json_encode($qry);
Related
I've been experiencing a lot of trouble with my issue all afternoon. Endless searches on Google and SO haven't helped me unfortunately.
The issue
I need to send an array to a PHP script using jQuery AJAX every 30 seconds. After constructing the array and sending it to the PHP file I seemingly get stuck. I can't seem to properly decode the array, it gives me null when I look at my console.
The scripts
This is what I have so far. I am running jQuery 1.11.1 and PHP version 5.3.28 by the way.
The jQuery/Ajax part
$(document).ready(function(){
$.ajaxSetup({cache: false});
var interval = 30000;
// var ids = ['1','2','3'];
var ids = []; // This creates an array like this: ['1','2','3']
$(".player").each(function() {
ids.push(this.id);
});
setInterval(function() {
$.ajax({
type: "POST",
url: "includes/fetchstatus.php",
data: {"players" : ids},
dataType: "json",
success: function(data) {
console.log(data);
}
});
}, interval);
});
The PHP part (fetchstatus.php)
if (isset($_POST["players"])) {
$data = json_decode($_POST["players"], true);
header('Content-Type: application/json');
echo json_encode($data);
}
What I'd like
After decoding the JSON array I'd like to foreach loop it in order to get specific information from the rows in the database belonging to a certain id. In my case the rows 1, 2 and 3.
But I don't know if the decoded array is actually ready for looping. My experience with the console is minimal and I have no idea how to check if it's okay.
All the information belonging to the rows with those id's are then bundled into a new array, json encoded and then sent back in a success callback. Elements in the DOM are then altered using the information sent in this array.
Could someone tell me what exactly I am doing wrong/missing?
Perhaps the answer is easier than I think but I can't seem to find out myself.
Best regards,
Peter
The jQuery.ajax option dataType is just for the servers answer. What type of anser are you expexting from 'fetchstatus.php'. And it's right, it's json. But what you send to this file via post method is not json.
You don't have to json_decode the $_POST data. Try outputting the POST data with var_dump($_POST).
And what happens if 'players' is not given as parameter? Then no JSON is returning. Change your 'fetchstatus.php' like this:
$returningData = array(); // or 'false'
$data = #$_POST['players']; // # supresses PHP notices if key 'players' is not defined
if (!empty($data) && is_array($data))
{
var_dump($data); // dump the whole 'players' array
foreach($data as $key => $value)
{
var_dump($value); // dump only one player id per iteration
// do something with your database
}
$returningData = $data;
}
header('Content-Type: application/json');
echo json_encode($returningData);
Using JSON:
You can simply use your returning JSON data in jQuery, e.g. like this:
// replace ["1", "2", "3"] with the 'data' variable
jQuery.each(["1", "2", "3"], function( index, value ) {
console.log( index + ": " + value );
});
And if you fill your $data variable on PHP side, use your player id as array key and an array with additional data as value e.g. this following structure:
$data = array(
1 => array(
// data from DB for player with ID 1
),
2 => array(
// data from DB for player with ID 2
),
...
);
// [...]
echo json_decode($data);
What I suspect is that the data posted is not in the proper JSON format. You need to use JSON.stringify() to encode an array in javascript. Here is an example of building JSON.
In JS you can use console.log('something'); to see the output in browser console window. To see posted data in php you can do echo '<pre>'; print_r($someArrayOrObjectOrAnything); die();.
print_r prints human-readable information about a variable
So in your case use echo '<pre>'; print_r($_POST); to see if something is actually posted or not.
I have a JSON encoded array, to which i am returning to an AJAX request.
I need to place the JSON array into a JS Array so i can cycle through each array of data to perform an action.
Q. How do i place the JSON array contents into a JS array efficiently?
The PHP/JSON Returned to the AJAX
$sql = 'SELECT *
FROM btn_color_presets
';
$result = mysqli_query($sql);
$array = array(); //
while($row = mysql_fetch_assoc($result)) //
{
$array[] = $row;
$index++;
}
header("Content-type: application/json");
echo json_encode($array);
You can use JSON.parse function to do so:
var myObject = JSON.parse(response_from_php);
// loop over each item
for (var i in myObject) {
if (myObject.hasOwnProperty(i)) {
console.log(myObject[i]);
}
}
You can also use jQuery.parseJSON() if you are using jQuery, however jQuery also uses same function under the hood as priority if available.
Adding to Safraz answer:
If you're using jQuery, there's another way to do that. Simply add json as last parameter to your ajax calls. It tells jQuery that some json content will be returned, so success function get already parsed json.
Below example shows you simple way to achieve this. There's simple json property accessing (result.message), as well as each loop that iterates through whole array/object. If you will return more structurized json, containing list of object, you can access it inside each loop calling value.objectfield.
Example:
//Assuming, that your `json` looks like this:
{
message: 'Hello!',
result: 1
}
$.post(
'example.com',
{data1: 1, data2: 2},
function(response){
console.log(response.message) //prints 'hello'
console.log(response.result) //prints '1'
//iterate throught every field in json:
$(response).each(function(index, value){
console.log("key: " + index + " value: " + value);
});
},
'json'
)
I am new to JSON.
In JS, I create an array of values like so:
var arrFields = $("td>.frmInput").map(function(){
return {
id: this.id,
value: $(this).val()
};
}).get();
I then AJAX them to the server like so:
$.ajax({
type: "POST",
url: "ajax/ax_all_ajax_fns.php",
data: "Fields=" +JSON.stringify(arrFields),
success: function(recd) {
alert(recd);
}
});
Note that there is a mixture of strings, plus the JSON.stringified (?) array. (There are additional string values sent, so data must remain as string.)
On the PHP side, I need to turn the received Fields string into an associative array.
Doing this:
$jsonAsStr_Fields = $_POST['Fields'];
die($jsonAsStr_Fields);
Returns this text string in the alert():
[{"id":"rateDriver","value":"Jacques Villeneuve"},{"id":"rateCar","value":"Chev"}]
Doing this:
$arrFields = json_decode($jsonAsStr_Fields, TRUE);
$driver = $arrFields['rateDriver'];
$car = $arrFields['rateCar'];
$tire = $arrFields['rateTire'];
die('Driver: [' .$driver. '] Car: [' .$car. '] Tire: [' .$tire. ']');
Returns this:
Driver: [ ] Car: [ ] Tire: [ ]
How can I turn the $jsonAsStr_Fields string into an assoc array, and thereby output the correct values to my alert?
Do this instead for your creation of values:
var arrFields = {};
$("td>.frmInput").each(function(){
arrFields[this.id] = $(this).val();
});
This will create an object, when JSON-stringified, that looks like this:
{"rateDriver":"Jacques Villeneuve", "rateCar":"Chev"}
Which seems to be the format you want to use in your PHP code.
You have an array of associative arrays and your arrays don't have the specified props, rateDriver for example is the value of the first array's element's id:
$driver = $arrFields[0]['id'];
$car = $arrFields[1]['id'];
For seeing the array's contents you use the famous var_dump function.
From the Author:
For those who haven't fully understood what solved this problem.
The underlying problem was that the stringified JSON was being modified en route (immed after hit Submit button en route to the PHP side) by the AJAX. All quote marks were being escaped, which made it impossible for that string to work with json_encode.
This was discovered by grabbing the value of the received data once it hit the PHP side:
$jsonAsStr_Fields = $_POST['Fields'];
die($jsonAsStr_Fields);
And alerting the received data in the AJAX success function:
success: function(recd) {
alert(recd);
}
Both of the above were described in the OP.
However, because I assumed this was an unrelated problem, I "fixed" the string displayed in the alert() box when I posted the question. Lesson to be learned: don't help - just post what you actually see.
It really displayed like this:
{\"id\":\"rateDriver\",\"value\":\"Jacques Villeneuve\"}
but I wrote that it displayed like this:
{"id":"rateDriver","value":"Jacques Villeneuve"}
Of course, the json_decode() PHP function had no idea what to do with the backslashes, so the string did not convert.
Solution was to use str_replace() on the received JSON string over on the PHP side, to resolve the problem, like this:
str_replace("\\", "", $_POST['Fields']);
Hey guys i really need help with this. i pass this json object to php..
var x = {};
x.xt = {};
x.xt.id = id;
x.xt.to = foo;
somearray.push(x);
convert object to json:
$.toJSON(x);
json string:
[{"x":{"xt":"9","to":"2"}}]
them i post this:
$.post(
"temp/sop.php",
{ xa: somearray},
function(data){
console.log("response - "+ data);
});
server side:
$xtj = $_POST["xa"];
$encodedArray = array_map(utf8_encode, $xtj);
$asnk = json_decode($encodedArray);
This returns:
string(4) "null"
and this:
$asnk = json_encode($xtj);
returns:
null
the data base it is set to:
UTF8
also when i test if it is an array, comes back true..
any idea how to solve this? thanks
also server side:
$xtj = $_POST["xa"];
$asnk = json_decode($xtj);
this returns:
NULL
$.toJSON(x) does not do the conversion in-place; it returns the JSON, and you're just discarding it. You need this instead:
$.post(
"temp/sop.php",
{ xa: $.toJSON(somearray) },
// ...
});
Then, on the PHP side, you won't want array_map as it's not going to be an array until you decode the JSON:
$xtj = $_POST["xa"];
$encodedArray = utf8_encode($xtj); // I'm not sure you need this, by the way.
$asnk = json_decode($encodedArray);
try using
if(get_magic_quotes_gpc()) $xtj = stripslashes($xtj);
to lose the excessive escaping before trying to decode.
What you are doing is you are converting to json string in JS ($.toJSON()).
And then in PHP you are again trying to convert to json string (json_encode()).
And you are using array_map() on something that is not an array but a string. (Try echo $_POST["xa"]; to see the contents of it.)
Here is my code:
var var_ids = new Array();
var i = 0;
jQuery("select").each(function() {
var_ids[i] = jQuery("option:selected",this).val();
i++;
}
var $data = {
action: "do_something",
var_ids: var_ids,
};
jQuery.post(doajax.ajaxurl, $data, function(response) {
alert(response);
});
And in my php:
$ids = mysql_real_escape_string(trim($_POST['var_ids']));
exit(print_r($ids));
And it just returns garbage...So my question is how to pass an array via AJAX to post php?
Thank you.
Most likely you get unexpected results because you apply string-related functions trim and mysql_real_escape_string to array $_POST['var_ids']
As long as it is just an array of integers - the only mysql sanitize you need is casting to int:
$ids = array_map('intval', $_POST['var_ids']);
print_r($ids);
$_POST['var_ids'] is an array in your example on the PHP side. You can only call trim and mysql_real_escape_string on strings not arrays. Try this in php:
$postData = isset($_POST['var_ids'])?$_POST['var_ids']):null;
if(is_array($postData)){
foreach($postData as $key=>$value){
$postData[$key] = mysql_real_escape_string(trim($value));
}
}
Viola, $postData is now a PHP array with trimmed and escaped values.
It's in the docs about 1/4 of a way down titled pass arrays of data to the server
var var_ids = new Array('10','12','13');
var $data = {
action: "do_something",
'var_ids[]': var_ids,
};
jQuery.post(doajax.ajaxurl, $data, function(response) {
alert(response);
});
Make it json_encoded array ... And then You can json_decode() the array properly.
You'll have better luck converting the array to a JSON object (Javascript Object Notation) and sending it that way.
Javascript JSON Instructions
JSON PHP Reference
You can either post each of the items with the key items[], then you could access the array as $_POST['items'] or you can serialize the array, send it and unserialize in PHP (JSON.stringify and PHP json_decode).