JSON with jQuery and PHP - javascript

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.

Related

AJAX - Why page redirect is failing here?

I have a problem here. I am posting data using $ajax to update a MySQL table. The update logic is done fine.
PHP Snipet
$count=$stmnt->rowCount();
if ($count==1){
$output=array('op'=>'tt');
echo json_encode($output);
}else{
$output=array('op'=>'ff');
echo json_encode($output);
}
JS Code
success: function(data) {
console.log(data);//On update, this is printing{"op":"tt"}
if (data.op ==='tt') {
console.log(data);//this is not executing.
window.location.href= 'post.php'
}else{
alert("Error!");
}
}
I have realized that my if statement is not being executed. What has gone wrong here?
By default, jquery ajax without a dataType will try to set the response based on the MIME type.
If you have a string, you can manually parse it, ie:
success: function(data) {
data = $.parseJSON(data);
or you can specify the dataType for jquery to use on the $.ajax request.
You should parse the json first before you can get the plain text out of it.
var result = jquery.parseJSON(data);
if (result.op == 'tt') {
...
}

How to get a JSON string result from a database for later use

I am working on the backend for a webpage that displays EPG information for TV channels from a SQlite3 database. The data is provided by a PHP script echoing a JSON string. This itself works, executing the php program manually creates a JSON string of this format
[{"id":"0001","name":"RTL","frequency":"626000000"},{"id":...
I want to use these objects later to create HTML elements but the ajax function to get the string doesn't work. I have looked at multiple examples and tutorials but they all seemed to be focused more on having PHP return self contained HTML elements. The relevant js on my page is this:
var channelList;
$(document).ready(function() {
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data.success);
channelList = data;
}
});
});
However the channelList variable remains empty when inspected via console.
What am I doing wrong?
Please ensure that your PHP echoing the correct type of content.
To echo the JSON, please add the content-type in response header.
<?php
header(‘Content-type:text/json’); // To ensure output json type.
echo $your_json;
?>
It's because the variable is empty when the program runs. It is only populated once AJAX runs, and isn't updating the DOM when the variable is updated. You should use a callback and pass in the data from success() and use it where you need to.
Wrap the AJAX call in a function with a callback argument. Something like this:
function getChannels(callback){
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data);
if (typeof(callback) === 'function') {
callback(data);
}
},
error: function(data) {
if (typeof(callback) === 'function') {
callback(data);
}
}
});
}
Then use it when it becomes available. You should also use error() to help debug and it will quickly tell you if the error is on the client or server. This is slightly verbose because I'm checking to make sure callback is a function, but it's good practice to always check and fail gracefully.
getChannels(function(channels){
$('.channelDiv').html(channels.name);
$('.channelDiv2').html(channels.someOtherProperty);
});
I didn't test this, but this is how the flow should go. This SO post may be helpful.
EDIT: This is why frameworks like Angular are great, because you can quickly set watchers that will handle updating for you.

When making an ajax call I receive "TypeError: e is undefined"

I am trying to display the contents of a website by using file_get_contents in a PHP script and ajax on the front-end. I can display the whole page just fine but if I try to only display a certain amount of images on the page, than I receive the "TypeError: e is undefined" error. Here is my PHP:
<?php
$url= 'https://twitter.com/twitter';
if($url!="")
echo file_get_contents($url);
?>
Here is my jQuery:
$.ajax({
url : "twitter.php",
dataType: "html",
success : function (data) {
console.log("loaded");
//$(data).appendTo('#images');
$.each(data.items, function(i,item) {
$("<img />").attr("src", item.media.m).appendTo('#images');
if (i == 5) return false;
});
}
});
data is an HTML string, to iterate over it (like a DOM tree) using jQ, you'll have to call the jQ constructor (or init method). Which you actually did when you tried to append it to the current dom:
$(data).appendTo('#images');
// \==>$() is a function call, returns a jQ instance
// When passing a markup string, jQ will parse it for you
The loop, therefore, should look like:
$.each($(data), function(){});
And please, do try adding in a couple of console.log statements, that will help you a lot when debugging.
I believe the issue here is that data.items will be undefined. I'm guessing that data is of type string, as you're expecting HTML back. So you're going to be receiving the HTML for the webpage, which you'd have to parse yourself.

Turning post request data into .each() function

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");

jquery ajax post - json is returning but not working right

I've started the following skeleton for an ajax/post/update function I'm wanting to write in javascript (using jquery):
$.post("/gallery/resize",
function (data) {
alert(data);
alert(data.complete);
if (data.complete) {
alert("done");
} else {
alert("blah");
}
},
"json"
);
And the response script on the server is:
$return['complete'] = 'complete';
header('Content-type: application/json');
echo json_encode($return);
exit;
The FireBug console shows that I get a JSON string in response - but the value of data.complete is 'undefined'. Here is the string from the server as reported by the FireBug (I also have a corresponding value/data pair under the JSON tab under the XHR display in the console):
{"complete":"complete"}
Any pointers on what I might've missed...
I am working on a localhost server - apache on ubuntu - if that makes a difference?
oh boy - turns out that I was a bit too trusting of the power of jQuery - I was missing a parameter in the $.post() method which may be optional unless you want to specify the other things.
the odd thing is that the callback works without the preceding data parameter being set - but it freaks out when you want to set the datatype (and must have the data and callback set).
So - the correct code for what I want would be:
$.post("/gallery/resize", "",
function (data) {
alert(data);
alert(data.complete);
if (data.complete) {
alert("done");
} else {
alert("blah");
}
},
"json"
);
I'm not sure how jQuery parses JSON data, but it may be the JSON string is being evaluated incorrectly. If you enter {"complete":"complete"} in the FireBug console, it is interpreted as a block statement rather than an object literal (the "complete" property name is evaluated as a label). This is fixed by evaluating either ({"complete":"complete"}) or {complete:"complete"}, or using JSON.parse on {"complete":"complete"}. The quickest way to fix this would be to remove the "json" parameter from the $.post call and parse the data your self, like so:
$.post("/gallery/resize",
function (data) {
var obj;
if (JSON.parse) {
obj = JSON.parse(data);
} else {
obj = eval("(" + data + ")"); // obligatory eval() warning
}
if (data.complete) {
alert("done");
} else {
alert("blah");
}
}
);
Incidentally, if you're debugging with Firebug, always try to use console.log instead of alert - it doesn't interrupt execution of the JS, and it gives much more informative JSON serialization than [object Object]
Try this:
header('Content-Type: application/json');
$return = array('complete' => 'complete');
echo json_encode($return);
exit;
JSON data is like a javascript array. So you should access it the same.
Therefore, in the code you provided, you should access the entry "complete" this way instead:
data.items[0].complete
That should do the trick.
You may look here for further jQuery/JSON information.

Categories

Resources