I'm using this code
$.post("assets/scripts/chat/load_convos.php",{}, function(data) {
$.each(data, function(index, value) {
alert(value);
});
,and the return of the data is [57,49] but it just doesn't do anything... If I replace the data just after the $.each( with [57,49] it works but not with the data in its place.
I'm not the best with Javascript so all help is much appreciated.
What do you mean with "the data is [57,49]" ?
My guess is, that you expect a (JSON)-object but you just receive a string. My second guess is that jQuery interpretates the result the wrong way and does not identify the return as JSON-String and hence, does not implicit JSON.parse it.
Check the content-types of the request. Try to call data = JSON.parse(data); manually before calling the each loop. Actually jQuery should be able to identiy that string as a JSON result itself, so I'm also wondering which jQuery version you use.
Another shot you might have is to call .getJSON() instead of .post() directly.
You can use JSON.parse or eval('('+response+')'); but probably the solution is to specify to jQuery or the library you are using that the response is JSON.
By the way, no all browsers have the JSON object, so if your library don't provide it you'll have to use the eval solution.
Specify json as your datatype.
Taken from jquery.post documentation
Example: Posts to the test.php page and gets contents which has been
returned in json format
(<;?php echo json_encode(array("name"=>"John","time"=>"2pm")); ?>).
$.post("test.php", { "func": "getNameAndTime" },
function(data){
console.log(data.name); // John
console.log(data.time); // 2pm
}, "json");
Related
I am writing a JS where I want to make some Ajax calls to get a JSON file from my DB in CouchDB. My code is based on examples I found online, but my lack of experience and knowledge is making it difficult to fix it completely.
My code:
function myFunction(){
var request = $.ajax({
url:'http://admin:pass#localhost:5984/db/_design/view/_view/view',
type:'get',
dataType:'json'
});
request.done (function (data)){
var result;
for (var i in data){
if( data[i] == key){
result.push(data[i]);
}
}
console.log(result);
};}
Problem: It seems like it is not even doing the requested call since when I try to print my array it isn`t doing anything.
The way see it, in the first part where I defined request it should get the JSON file from CouchDB. And, if correct, in the second part where the request is done request.done I give the function how I want the JSON file to be taken care of. To make it clear, my idea is to iterate through the data and to save the values of the "key" in every row in my result-array.
I'm trying to fetch a JS array created by a PHP file and re-use the JS array in a JS script in the page. I have tried many different solutions found on this site but none seems to work but I don't know what the issue is with my script.
I have a PHP file that echoes the following:
[["content11", "content12", "content13", "content14","content15"],
["content21", "content22", "content23", "content24","content25"]]
I'm using a simple Ajax get to retrieve the data:
$.ajax({
type: "GET",
url: myUrlToPhpFile,
dataType: "html",
success : function(data)
{
result = data;
alert (result);
}
});
The alert displays the expected output from the PHP file but if I now try to access the array like result[0], it outputs "[" which is the first character. It looks like JS sees the output as a string rather than an array.
Is there something I should do to make JS understand it's a JS array?
I have seen many solution with JSON arrays but before going into this direction, I'd like to check if there are simple solutions with JS arrays (this would prevent me from rewriting too much code)
Thanks
Laurent
In you php file you need check that your arrays echos with json_encode.
echo json_encode($arr);
And in your javascript file:
$.ajax({
type: "GET",
url: myUrlToPhpFile,
dataType: "html", // json
success : function(data)
{
var res = JSON.parse(html);
alert(html); // show raw data
alert(res); // show parsed JSON
}
});
You can use JSON.parse to format the string back into an array.
JSON.parse(result)[0]
or
var result = JSON.parse(result);
result[0];
#Rho's answer should work fine, but it appears that you're using jQuery for your AJAX call, which gives you a shortcut; you can use $.getJSON instead of $.ajax, and it will read the data as JSON and provide you with the array immediately.
$.getJSON(myUrlToPhpFile, function(result) { ... });
This is really just a short way of writing what you already have, but with a dataType of json instead of html, so you could even do it that way if you prefer. This is all assuming that you're using jQuery of course, but your code was following their API so it seems a good bet that you're either using jQuery or something compatible.
If I run a get request like this:
$.ajax({
url: 'http://localhost:8000/api/points/',
contentType:"application/json",
dataType: "json",
data: JSON.stringify({"content_type":content_type,"object_id":object_id}),
type: 'GET',
}).error(function(r){ $(output).text('error') })
.success(function(r){
$(output).text(r.count);
})
Its request goes to:
http://localhost:8000/api/points/?{%22content_type%22:8,%22object_id%22:40}
Obviously that's bad. It works okay if I don't do JSON.stringify(), but why is that?
Curiously if I do a POST request it's the opposite! I have to stringify the data or it won't work. So why the difference?
First of all let's fix your request:
var req = $.ajax({
method: "GET",
url: "http://localhost:8000/api/points/",
dataType: "json", // is you telling jQuery what kind of response to expect.
data : {id : '12345'}
});
req.done(function(data){
// do something with the data
});
req.fail(function(jqXHR, status, err){
// do something in case of failure
throw err;
});
Next get to know what you are dealing with :
data : PlainObject or String or Array
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. By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded".
Note: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks will be deprecated in jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
At last:
No need for : JSON.stringify({"content_type":content_type,"object_id":object_id}) as it is a wrong way to do it with JSON.stringify just :
{ 'content_type' : 'type', 'object_id' : 'id' }
Urahara's answer contains some useful suggestions, but does not seem to address your question.
Well, it seems that your server side code is expecting to find a json object in the body of the POST request. Why would that be? Because you specify that the content type be "application/json". So in the case of a PUT case, when you use JSON.stringify your data in the $.ajax call is a string that happens to represent a JSON object. This is passed as is and so this works. You end up sending something like
{"content_type":8, "object_id":40}
as the body of your POST request and your server side code is happy to process this. Not sure exactly what your server-side technology is, but presumably it also binds content_type to 8 and object_id to 40, which makes you happy :-)
But when you do not use JSON.stringify to turn the object into a JSON string, you end up passing the object itself to $.ajax having it turn it into a string in the way it knows how. Well, it only knows only one: the good old url-encoding way. So the server, would still be expecting a JSON object but would instead be getting
content_type=8&object_id=40
as the body of the PUT request. It will not be happy. This is not a JSON object like your content-type promised! :-)
Now, moving on to the case of a GET request. Here the content-type is pretty much irrelevant as the message body will be empty. If you use JSON.stringify what you pass as the request data is a weird JSON-object representing string and the monstrosity that you get as a URL
http://localhost:8000/api/points/?{%22content_type%22:8,%22object_id%22:40}
is as you 'd expect not very well received by the server. What the server is happy with is something like
http://localhost:8000/api/points/?content_type=8&object_id=40
Which is exactly what $.ajax produces when you do not use JSON.stringify but rather pass it a nice pair of attribute-value pairs. It just url-encodes them, exactly like it did in the PUT case, and the server is happy.
So $.ajax always url-encodes objects consisting of attribute-value pairs. This is fine in most cases. One way to fix your code to do a POST without using JSON.stringify would be to simply not put a content type parameter in the $.ajax call (in which case the default, 'application/x-www-form-urlencoded; charset=UTF-8' will be used).
But if you want to pass more complex, deeply hierarchical objects, using some object serialisation format you have to set the appropriate content type and pass the data as a string using the corresponding encoding (JSON, XML, etc.) like you did here.
Hope that answers your question :-)
Please also have a look at http://api.jquery.com/jquery.ajax/
Is there a way that I can parse an array from a web service to javascript using $.get and not using a json object? I still didnt finish my code becaus I dont know if this kind of approach will work.
is this kind of code correct? or will it work?
var url = "receipt.php";
$.get(url, {receipt:receipt}, function(value) {
$(receipt.value).each(function(){
});
});
the array to be returned is "value"
I have a script for updating a database table. I need to return a JSON array and to update some tables with JQUERY.
my php script:
$update = mysql_query("UPDATE PLD_SEARCHES SET STATUS = 1, TOTAL_RESULTS = ".$scrapper->getTotalResults().",RESULTS = $resultCounter WHERE ID = ".$searchId);
$output = array("status"=>"COMPLETED","results"=>$resultCounter,"totalResults"=>$scrapper->getTotalResults());
echo json_encode($output);
jquery code:
$("button").live("click", function(event) {
event.preventDefault();
$.getJSON("startsearch.php", {
searchId: $(this).val()
}, function(data) {
alert(data[0].status);
});
now ...the problem is that if i use $.post("startsearch.php",{ searchId: $(this).val() }, function(data)) the script gets executed and i get a nice alert with value undefined. if i add the parameter "json" the script doesn't get executed anymore. I tried to use getJSON but again the same problem.
Anybody has any ideas? I am desperate...this has been bugging me for almost a week and I still haven't managed to solve it.
In your php file make sure to set the correct content type:
header("Content-type: application/json; charset=utf-8");
so that jquery can correctly eval the response into a json object.
You can get to your response data as follows:
alert(data.status);
alert(data.results);
alert(data.totalResults);
please don't use alert, install firebug into your firefox or enable the javascript console in chrome or safari. after that you can use console.log(data);
my guess is that data isn't an array. also have a look at the each() exmaple on the jquery docs http://docs.jquery.com/Ajax/jQuery.getJSON
Well, I'm trusting json2.js to parse the json data returned from AJAX request. You can download it from http://json.org. This library provide a better way to parse any string, and will throw an exception if the sting is not in json.
I always write my AJAX request like this:
$.post(URL,
{ PARAM },
function(data){
try {
var r = JSON.parse(data);
//this for your code above
alert (r.status); //should be 'COMPLETED'
}
catch (e) {
//data is not in json format, or there are another exception in try block
//do something about it
alert('Exception occured, please check the data!');
}
});
When processing json, the array in php will become a variable member in json. So if in your php it is $output['status'], then in json, it will be r.status.