I'm trying to return data as an array to my .ajax function on success so I can do do multiple things, but I can't get to work for anything except a single value. Like return $foo. But when I return $array, the page never loads up.
JavaScript's use & utilizing of array is different as compared to PHP's processing. So, either you need to send the data to your AJAX function as a JSON (JavaScript Object Notation), otherwise you need to send the data as a string with a common separator to your AJAX function.
In the latter case, you will need to split up the Response Text in your AJAX function, with that common separator, to make up a JS Array. Then it will be very much easy to use that array instead.
Hope it helps.
You would have to serialize your data into a string. My preference is JSON, so if your PHP version is >= 5.2.0, you'll most likely have access to a json_encode function. This will turn the PHP object into a JSON string. If you don't have access to json_encode, you can use the PECL JSON package.
Looking at the way you reference your ".ajax" function, I am assuming jQuery. So as long as you set the content type to 'json', the JSON response will result in a native JavaScript object. For example,
PHP,
return json_encode(array(1, 2, 3));
JavaScript,
$.ajax({
...
contentType: 'json',
success: function(response) {
for (var i = 0; i < response.length; i++) {
alert(response[i]);
}
});
This code should proceed to alert 1, 2, and then 3.
I haven't verified the code, but the essential parts are all there. A note to have though, a normal indexed array is turned into a JavaScript list while an associative array will be turned into a JavaScript object.
JSON is a good option to send your data array from PHP to Javascript. In PHP side just encode and return your data array as JSON string and in the Javascript side decode that JSON string and use as normal array.
Suppose your data array is like $array, in your PHP code just encode that array using json_encode($array) and return the resulted JSON string.
In your javascript code decode that JSON string using 'eval' function in the success callback function like:
$.ajax({
type: "GET",
url: "test.php",
success: function(data) {
var dataArray = eval('(' + data + ')');
}
});
I think this will help you ...
Siva
Related
An Ajax call is computing me a multidimensional PHP array '$tree', after this call is made I would like to retrieve this array as a JSON.
My PHP page is only printing the Array:
print_r(json_encode($tree));
Here the success part of my ajax call:
success: function(data, textStatus, jqXHR) {
var myObject = JSON.parse(data);
alert(myObject);
}
Unfortunately the alert box is not triggered.
Also, I noticed that when I'm reaching my PHP page through a web browser:
print_r(json_encode($tree));
isn't displaying anything, while:
print_r($tree);
Is printing my multidimensional Array
echo json_encode($tree);
exit;
This is the ideal way to send JSON back to browser.
Also check that you do not have any special characters in your array otherwise you will have to use BITMASKs in json_encode function.
Also, All string data must be UTF-8 encoded, so you may want to correct the encoding of your data.
Further reading: http://php.net/manual/en/function.json-encode.php
As others already said, the correct method to output a JSON from PHP is via the json_encode function.
echo json_encode($tree);
You should probably check the encode of the Array data; if you have any string they must be encoded in UTF-8. I suggest you to loop through the $tree Array and to force the encode via the utf8_encode function (you can find PHP docs here).
If your Array has a depth of 2 levels you can try something like this, or some kind of array walk loop.
for (i = 0; i < count($tree); i++)
{
for (j = 0; j < count($tree[$i]; j++)
{
utf8_encode($tree[$i][$j]);
}
}
You probably just need to encode strings, so you should reduce the amount of data to encode if you can (i.e. you know that only 2 indexes in the whole array could be strings, or maybe could contain characters that need to be encoded).
Never forget the header!
<?php
header("Content-Type: application/json");
echo json_encode($tree);
First of all you need to test if the function json_encode exists.
if (function_exists('json_encode')) print 'json_encode working';
else print 'json_encode not working';
If it doesn't, you need to enable it, see here https://stackoverflow.com/a/26166916/5043552
Last, use print json_encode($tree) instead of print_r(json_encode($tree)).
I want to POST 3 parameters to my PHP web service. One of which is an array, so I used JSON.stringify() first and then added it as the parameter. The problem is, PHP isn't receiving the stringify'ed parameter.
My array is created by fetching IDs of each element in an object.
Converting it into a string:
var cid = JSON.stringify(cids);
Output as in the console for cid:
["1","2","3"]
And my $http.post call:
var dataObj = {
wid: wid,
type: type,
cid: cid
};
$http.post("my.php", dataObj);
From what I understand, the array gets converted into a string, which must get POSTed alike other strings, but when I echo back $_POST['cid'], it turns out to be blank; while the wid & type are proper.
From my understanding all post data is converted to JSON anyway. Manually changing your array to JSON and including is just the same as:
$http.post("my.php", {
wid: wid,
type: type,
cid: [1, 2, 3]
}
At the other side of the connection the JSON is converted back to objects(arrays) if possible. PHP doesn't print anything because arrays aren't converted to strings that well. Although you should expect the string 'array'. Try echo'ing $_POST['cid'][0]
EDIT:
As stated in the comments and this post the following code is required to get PHP and AngularJS to play together:
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
I have a php file wich searches in a DB, then builds and array with results and it ends and shows the result like this:
{"1":"1","2":"2","15":"15","25":"25"}
That means in position 0 there is no result, position 1 has value 1, and so on. (as far as I /know this result is a valid json output)
In jquery side I have this
$.ajax({
type: 'POST',
url: 'diahoracierre.php',
dataType: 'json',
cache: false,
success: function(result) {
alert(result);
},
});
What I need is to "parse" result to an array and be able to play which the content using index of array, like
alert(result[X]);
on result[1] it shows 1, any other attempt shows undefined and there are at least 4 results.
You have two options either you loop through result and create an array by yourself(a tedious task) or you access elements like below, please note quotes around index is required as here though we are saying index but in reality we are looking for key name.
result["index"]
e.g.
result["5"]
Also I tried your jsFiddle and it worked:
var json = '{"0":"-1","1":"1","2":"2","15":"15","3":"-1","25":"25","4":"-1","5":"-1","6":"-1","7":"-1","8":"-","9":"-1","10":"-1","11":"-1","12":"-1","13":"-1","14":"-1","16":"-1","17":"-1","18":"-1","19":"-1","20":"-1","21":"-1","22":"-1","23":"-1","24":"-1","26":"-1"}';
json = JSON.parse(json);
alert(json["25"]);
Since you've used dataType: 'json'. Then it's no longer require you to parse the json result.
Also note that your parameter is named result in success function.So you can use:
alert(result[1]);
instead of:
alert(myArray[1]);
I've been trying to send a JSON string to PHP server like this:
$.ajax({
type: "POST",
url: "themes.php?page=themeoptions",
data: {structure : JSON.stringify(structure)},
});
However, every quotation mark from the string I send is escaped automatically, so I can't decode it in PHP with json_decode(). I could remove all the escape characters, but I really doubt that this way of sending JSON data to server is safe.
So, I was wondering if you have any ideas on how to do that in a simple and safe (not necessarily bulletfroof) way?
Thank you!
You can just do '{"structure":' + JSON.stringify(structure) + '}' or {structure: structure}
The first one is a JSON String so jQuery doesn't need to parse it. The second is a javascript object, so jQuery knows exactly how to parse it.
But you are mixing the two, so jQuery is confused and re-encodes your object, because you encoded only half your object.
So another alternative would be JSON.stringify({structure: structure })
Try this
$.ajax({
type: "POST",
url: "themes.php?page=themeoptions",
data: {structure: structure},
});
$.ajax({
type: "POST",
url: "themes.php?page=themeoptions",
data: structure,
});
Quoting from the documentation:
dataObject String Data to be sent to the server. It is
converted to a query string, if not already a string. It's appended to
the url for GET-requests. See processData option to prevent this
automatic processing. Object must be Key/Value pairs. If value is an
Array, jQuery serializes multiple values with same key based on the
value of the traditional setting (described below).
I have a $.get() call to a PHP page that takes 4 GET parameters. For some reason, despite giving the $.get() call all 4, it only passes the first two. When I look at the dev console in chrome, it shows the URL that gets called, and it only passes action and dbname. Heres the code:
$.get('util/util.php', { action: 'start', dbname: db, url: starturl, crawldepth: depth }, function(data) {
if (data == 'true') {
status = 1;
$('#0').append(starturl + "<ul></ul>");
$('#gobutton').hide();
$('#loading').show("slow");
while(status == 1) {
setTimeout("update()",10000);
}
} else {
show_error("Form data incomplete!");
}
});
and heres the URL that I see in the developer console:
http://localhost/pci/util/util.php?action=start&dbname=1hkxorr9ve1kuap2.db
** EDIT **
I have been informed that I need to encode the URL that I am trying to pass through the header. How would I go about encoding it in javascript, and decoding it in php?
Are you sure that the starturl and depth variables are defined? A simple alert() before the $.get() will be enough to check.
In regards to your edit, you can encode strings in JavaScript with the encodeURIComponent function. And decode it back again in the PHP with urldecode. They both take one string argument.
Probably you will need to check whether your input strings are properly quoted. Internally jQuery will build the paramter string out of the parameter map you specified using its param() method. This method will construct an object of the keys and values, which will likely not be parseable if you quoted your keys and values incorrectly.
# Felix Kling: jQuery automatically encodes keys and values of the parameter string with encodeURIComponent.