I have an odd problem regarding jQuery dataType.
I have a very simple PHP program that returns (echo's) an XML file (string). Looks like this:
$xmlFile = "sampleXMLFile.xml";
$xml = simplexml_load_file($xmlFile);
echo $xml->saveXML();
My client/javascript code calls the php program via ajax:
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "myPHPFile.php",
dataType: "xml",
success: myCompleteFunction,
complete: mySuccessFunction,
failure: function(data) {
alert("Problem getting XML");
} });
});
The "myCompleteFunction" takes the XML and simply writes the first node into a div element, like this:
function myCompleteFunction(xml)
{
$(xml).find("Row").each(function()
{
$("#result3").append($(this).attr("myrow"));
});
}
OK - in IE 8, this works fine. In Firefox and Chrome I get no results. However, if I change the dataType to "html" I get correct results in Firefox and Chrome and then get no results in IE.'
Continue to go crazy with this. Do I actually need to put conditional logic for the browsers?
The dataType: option explained in the jQuery manual seems clear enough. I even tried to leave dataType out
(per manual: If none is specified, jQuery will try to infer it based on the MIME
type of the response)
I also tried multiple types - e.g. "text xml". No good.
Anyone ever run into this problem? Any direction would be appreciated.
Thank you.
p.s. I know I can read an XML file in jQuery. The resultant XML from the PHP program would be substantially more involved. I only used that as an example.
Updated:
Well, I saw Phil's comment about producing something before XML data sent. There was certainly nothing obvious. I removed a blank line above my first <?php line. This has somehow worked! Still seems odd to me. So my new, tighter PHP code is now:
<?php
// Load XML
$xmlFile = "sample.xml";
$xml = simplexml_load_file($xmlFile);
header('Content-type: text/xml');
echo $xml->saveXML();
?>
I will also pay mind to your other suggestion about properly handling jQuery.ajax() callbacks. Thanks.
I very much appreciate your help w/this!!
Stick with the "xml" dataType and add this to your PHP file before the echo...
header('Content-type: text/xml');
Also, you seem to be mixing up some of the jQuery.ajax() callbacks.
Use success to handle the returned data.
Use error(jqXHR, textStatus, errorThrown) (not failure) to handle HTTP errors
Use complete to execute some tasks after success and error callbacks have executed
Related
I tried following some basic examples, and it is not working. I am not sure I completely understand jsonp, but I followed the basic tutorials and on an intuitive level, I can't see anything wrong. (Of course, I am missing something, hence the question).
JavaScript code:
postData = $(this).serialize();
console.log(postData);
$.ajax({
data: postData,
url: 'externaldomain.php',
dataType: 'jsonp',
success: function(data){
console.log(data);
alert('Your comment was successfully added');
},
error: function(){
console.log(data);
alert('There was an error adding your comment');
}
});
PHP code:
$tag = mysql_real_escape_string($_GET["callback"]);
The annoying part is that it is not even showing me an error to Google for.
Can anyone help out figuring the problem please?
Since you haven't posted your full or relevant PHP code I'm going to assume it looks like this
$tag = mysql_real_escape_string($_GET["callback"]);
echo $tag."(";
// print json here
echo ")"
I'm not really sure how jquery handles jsonp requests but what I used to do is add a new script tag to the DOM that looks like this
<script> function cb(json) { alert(json); } </script> // (I)
<script src="{url}?callback=cb"></script> // (II)
When (II) is loaded, and because we have a callback then the script that we are including in the DOM looks like this
cb({
// json goes here
})
which pretty much is like a function call to some function called cb that we are using. It is therefore natural to have an implementation of cb (which is in (I)). That implementation is similar to the success(data) function in jQuery's ajax. It is used to use and manipulate the json requested
However I noticed that you are doing a POST request along the ajax call with jsonp. Unfortuantely (according to this question How to make a jsonp POST request that specifies contentType with jQuery?) doing POST with JSONP is not feasable due to implementation pursposes.
You can't POST using JSONP... it simply doesn't work that way...
So you can usually only perform GET requests. You can NOT perform POST requests.
For details about how jsonp work look at this nice article. jsonp-how-does-it-work
For more clearification :
See Other SO question Link1 Link 2
But there is work around for that with some limitations look at this Using PUT/POST/DELETE with JSONP and jQuery. (for me nothing works at all)
I've been using stackoverflow for months now as it really is the the most reliable resource I can think about. However, I now have my own question.
I'm working on a script that displays available courses in an HTML5 page using ajax after calling some php/MySQL interaction. I was using jQuery 1.4.1 (yeah... i know) and due to some interesting new plugins available, I updated to 1.10.2.
Now my page doesn't display the product of the PHP/SQL processing anymore, nor does the autoscroll work.
I did some search and didn't find any answer.
I was hoping you guys would see directly the incompatibility in my code, or the usage of a too old syntax.
Trigger :
<a class="internal-link" href="#" onclick="goToByScroll('reanimation');"></a>
Script :
function goToByScroll(id){
$.ajax({
type: "POST",
url: "kernel/appel-tableaux-ajax.php",
dataType: "script",
data:{type_cours : id},
success: function(array){
var objet = JSON.parse(array);
var message = objet["message"];
var nombre = objet["nombre"];
$("#conteneur-tableaux").html(message);
$("#nombre-cours").html(nombre);
if(nombre==0)
{
$("#titre-section-tableaux").css("color","darkred");
}else{
$("#titre-section-tableaux").css("color","darkgreen");
}
$('html,body').animate({scrollTop: $("#section-tableaux").offset().top},'slow');
}
});
}
PHP code (I erased stuff where mistakes are less probable) :
ob_start(); // I want to catch all the 'echos' to insert them in an array.
while ($donnees = $reponse->fetch())
{
// Lots of Date comparison stuff and many ECHOS.
}
$out = utf8_encode(ob_get_contents()); // --- I put every echos inside the 'OUT' variable.
ob_end_clean();
// --- I want to send back 2 things to my script, some infos about the courses available, and the total number of available courses. So I create an array.
$output_final = array ("message" => $out, "nombre" => $compteur_cours);
echo json_encode($output_final);
?>
As you can see, I'm a beginner in Ajax and jQuery usage.
UPDATE :
Thanks a lot to all those who already helped.
I tried the debug tools in Chrome, the php generates exactly what it's supposed to do, which means that my ajax is able to call the PHP code placed in kernel/appel-tableau-ajax.php. The Console.log() placed in the success case doesn't display anything.
I'm adding a screenshot of the syntax errors that Chrome detected. If someone could help me to understand how to handle those errors it would be wonderful.
Link to the screenshot
Also, Safari's debugger says : SyntaxError: JSON Parse error: Unexpected identifier "object".
I can't believe all this worked on the old jQuery version...
Thanks a lot, I hope I'm not asking too much!
if your php code return json why the 'dataType' in your ajax is 'script'? try change it to json.
hope it will work! :)
i know that there was similar questions, but i would like to get some clarification here.
With following Ajax setup:
$.ajaxSetup({
cache: true,
dataType: 'json',
error: function(xhr, status, error){
console.log(status);
},
timeout: 60000, //Timeout of 60s
type: 'POST',
url: 'test.php'
}); //Close $.ajaxSetup()
$('#openTest').bind('click', function(){
$.ajax({
data: {val: "Hello", val2: "Hello2"},
success: function(response){
console.log('complete');
console.log(response);
}
});
When 'test.php' is:
<?php
$return= array ('one'=>'one1', 'two'=>'two1');
return json_encode($return);
?>
I am getting parseerror. But when I replace 'return' with an 'echo', it works fine.
<?php
$return= array ('one'=>'one1', 'two'=>'two1');
echo json_encode($return);
?>
I will be retrieving much more complex data via this $.ajax calls, and I was expecting 'return' to works, 'echo' doesn't seems to me like good solution.
So, what are you suggesting? Is there something wrong with the Ajax setup, or call, so 'return' doesn't work, and is 'echo' a good solution?
Thanks.
return returns data to the caller of the function and since you are not in a function you cannot use return.
echo prints the data. So echo is the way to go.
when you do a return in php, it is not printed. When you do an echo, it gets printed.
Nothing is wrong with php or Ajax, it is just the context which is wrong.
Sinply put, use return when u need to catch the returned data and maybe process it. Best case for using return is in functions.
Use echo when you need to print something directly.
Here in this case using an echo and exit is what i recommend.
Return is used in functions to get the data back and use it in some fashion in your PHP. Echo is used for ajax calls because your PHP code will output the data to whatever is calling it (the browser, your ajax call, etc).
You also probably want to have header('Content-Type: application/json'); in your PHP file to make things all right and proper.
No, there is no problem with your ajax setup, it's because the return is used with PHP objects or variables and it can't return a value to other language like javascript. when you are using echo it sends the values to HTTP response so your ajax response can handle it.
The best way to do complex data is to send them in arrays like:
$arr = array();
$arr['res'] = 'something';
$arr['res2'] = 'somethingelse';
echo json_encode($arr);
and then you can handle it as object.parameter in your jquery code as I have specified it before in this example.
Always make echo or print or parsing php as html file in ajax call and then get the data, this will save you a lot of efforts.
the ajax is just reading the file, there is no way to make calls in two different languages PHP and JS.
The JS just returned the filed from the server, if it was php then it will interpreted and go to the Ajax call as html or else possible.
My jQuery/AJAX script posts to a php file in hopes of returning XML. When I print if the data I get all the html source code returned and the xml is not properly parsed in IE 8 or less. The code works in IE 9 and all other browsers. If anyone has a suggesion to what is goin on or a solution to my problem?
jQuery:
$.post("load-content/", {type: "POST", img: placeholder, dataType: "XML", selection: $(this).html()}, function(xml) {
// format and output result
// alert(placeholder+' && '+$(this).html());
nshow = $("content", xml).text() ;
$("div p.p2").html(
$("content", xml).text()
);
alert("HERE IE 9+ "+xml.length);
});
php:
if(isset($_REQUEST["img"]) && isset($_REQUEST["selection"])) {
$xml='<ratings><content>test</content></ratings>';
echo $xml;
*FYI this code is being run in Zencart folder
Solved.
There were two problems here.
As the above answer suggested there was a problem with headers.
Again as the answer above suggested there was a problem with the datatype... code for older IE browsers should look something like
$.post("/load-content/", {type: "POST", img: showcase, menuv: aname}, function(response) { ...
Actually i think your problem is making the ajax call itself. You are using $.post but youre supplying the options hash as if it is $.ajax. The two are different...
$.post takes the url, data, callback and response type as the arguments. You are supplying a hash similar to the one you would supply to $.ajax as your second argument which is not what it wants.
If you are going to use $.post it shoudl look like this:
$.post("load-content/", {img: placeholder, selction: whatever}, function(), 'xml');
Additionally its not obivous what the contex of your call is... this may not exist unless this is inside an event handler or jQuery.each iteration so using selection: $(this).html() may not make sense.
Have you tried setting the proper header for your response and exiting immeadiately?
if(isset($_REQUEST["img"]) && isset($_REQUEST["selection"])) {
header('Content-type: application/xml');
$xml='<ratings><content>test</content></ratings>';
echo $xml;
exit(0);
}
I have this function for getting a server id from a list. The function always returns "parsererror". I have looked at the JSON data returned but I cant seem to get it working, since jQuery have rewritten the ajax in v1.5.
function server_id()
{
$.ajax({
type: "GET",
url: "http://localhost/server_list.php",
dataType: "json",
success: function(data, status) {
alert(status + "\n\n" + data.server_id);
},
complete: function(data, status){
alert(status);
}
});
}
server_list.php
header('Content-type: application/json');
$output['server_id'] = '123';
print json_encode($output);
In firebug Net >> XHR it reads it as JSON as it brings up the tab and the Response tab shows what is below.
{"server_id":"123"}
I have also tried setting the content type header like below but having no luck.
Content-type: application/json
UPDATED
I only get "parsererror" if the validation plugin is loaded from http://bassistance.de/jquery-plugins/jquery-plugin-validation docs.jquery.com/Plugins/Validation v1.7.
If you add the plug jquery automatically adds the jsonp callback to the query string even when you set to false or dont include the parms for jsonp. Very Strange
Any ideas on how to fix?
Thanks
The simple solution here seems to be that jQuery 1.5 is not compatible with 1.7 of the validation plugin. Downgrading to jQuery 1.4.x (or otherwise patching or removing the validation plugin code as philhag suggested) solves the issue.
Huge thanks to those on this thread who identified the conflict. It saved me a bunch of headaches having to debug the jQuery code.
You seem to want regular json communication (dataType is "json" instead of "jsonp" and server_list.php sends json), but you're setting jsonp options. Remove the jsonp and jsonpcallback lines. Setting jsonp to false does not mean you disable it!
When these two lines are commented out, everything seems to work fine.
I suffered for days before finding this thread, thanks to those who pointed at jQuery.validate as the culprit.
In my testing it actually seems to be jquery.validate-vsdoc.js which is causing the issue, not the plugin itself, in case that's of any use to anyone else.