Different behavior for empty XML response between IE and Firefox - javascript

I'm using jQuery to read an XML file. Sometimes the XML is empty, and I expect the error function (no_info) is executed because the file is not formatted according to the dataType.
In IE 10 the Error function is executed. But in Firefox (40.0.2) the success function (parse) is executed. Why both browsers behave differently and which one is correct?
$.ajax({
url: '/~play/shout.xml',
dataType: "xml",
success: parse,
error: no_info
});

Looks like there's a bug in IE
how about you handle it yourself?
function parseXml(xml) {
if ($.browser.msie) {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "XML_file.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
xml = xmlDoc;
}
return xml;
}
previous answer

which JQuery version do you use? I use the most actual and with my ajax function I couldn't encounter any issues. That's my code
function sync(arg, callback){ //ajax result
$('.loader').show();
$.ajax({
method: 'GET',
url: 'liveSearch.php',
data: arg, // send argument and update
success: function(data, status, xhr){
$('.loader').hide();
callback(data);
},
error: function(xhr, ajaxOptions, thrownError){
console.log(thrownError);
}
});
}
function onCallback(data) {
result = data;
}

dataType parameter merely indicates what "Content-Type" header you are expecting.
As long as the file exists and served with a valid Content-Type Success function should be triggered.

instead of just /~ try passing the whole URL from which you want to retrieve the XML file.

Related

ajax submit wrong data to PHP

This is html file that submit ajax by button click to PHP script(on IIS).
But PHP script received wrong formatted data (there are brackets added [] and no parameter 'section' transmitted
What can be wrong
It would be good to have solution both: in JQuery and pure javascript
------------------- HTML
<!DOCTYPE html>
<html STYLE="height:100%;">
<head></head>
<body>
<SCRIPT>
function zPostToTopic_ajax(){
var url='http://the_server/infospace/php/infospace2.php';
var formData2 = new FormData();
formData2.append('section', 'general');
formData2.append('action2', 'preview');
http_request=new XMLHttpRequest();//work for IE11 too, // code for IE7+, Firefox, Chrome, Opera, Safari
http_request.open("POST", url);
//------------------------------------
http_request.onreadystatechange = function() {
if(http_request.readyState == 4 && http_request.status == 200)
alert(http_request.responseText)
}
http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
http_request.send(formData2);
}
</SCRIPT>
<FORM NAME=form_post_to_topic ID=form_post_to_topic METHOD=POST action="http://the_server/infospace/php/infospace2.php">
&nbsp <INPUT TYPE=BUTTON VALUE=Send onClick="zPostToTopic_ajax();return false;">
</FORM>
</body>
</html>
-------------------------- PHP script
<?php
print_r($_REQUEST);
?>
--------------------------- Received data:
Array
(
[-----------------------------276402058428
Content-Disposition:_form-data;_name] => "section"
general
-----------------------------276402058428
Content-Disposition: form-data; name="action2"
preview
-----------------------------276402058428--
)
Use jQuery's .ajax() function. Here's an example where I post a file upload too.
var jform = new FormData();
jform.append('supply_id',supply_id);
jform.append('fuel_usage',$('#fuel_usage').val());
jform.append('cost',$('#cost').val());
jform.append('currency',$('#currency').val());
jform.append('evidence',$('#evidence').get(0).files[0]);
$.ajax({
url: '/your-form-processing-page-url-here',
type: 'POST',
data: jform,
dataType: 'json',
contentType: false,
cache: false,
processData: false,
success: function(data, status, jqXHR){
alert('Hooray! All is well.');
console.log(data);
console.log(status);
console.log(jqXHR);
},
error: function(jqXHR,status,error){
// Hopefully we should never reach here
console.log(jqXHR);
console.log(status);
console.log(error);
}
});
Your problem is that you are setting the wrong content type for your request. When you use a formdata object the content type will be multi-part/formdata.
So when you are using a formdata object you do not set the content type and it is set for you.
function zPostToTopic_ajax(){
var url='http://the_server/infospace/php/infospace2.php';
var formData2 = new FormData();
formData2.append('section', 'general');
formData2.append('action2', 'preview');
http_request=new XMLHttpRequest();//work for IE11 too, // code for IE7+, Firefox, Chrome, Opera, Safari
http_request.open("POST", url);
//------------------------------------
http_request.onreadystatechange = function() {
if(http_request.readyState == 4 && http_request.status == 200)
alert(http_request.responseText)
}
http_request.send(formData2);
}

How can I make a Ajax request & response with firefox OS?

I'm having a php function which returns a Json data from db.
I want get all the json from the function and display that into my Firefox App. I tried Jquery Ajax. But its not working.
Any other library or Ajax coding?
var a=1;
$.ajax({
url:"http://localhost/shop/home/home/demo",
type:"POST",
data:{b:a},
success: function(msg){
alert(msg);
}
});
It's not working with firefox app. Help me.
You must use the mozSystem property. Here's an example using native XMLHttpRequest.
var xhr = new XMLHttpRequest({
mozSystem: true
});
xhr.open("POST", "http://localhost/shop/home/home/demo");
xhr.onload = function() {
if (xhr.status == 200) {
console.log(xhr.responseText);
}
};
xhr.send("b=" + a); //serialized data
Hope it helps!

Making an API call in Javascript - new call at each click

Here's what I want to achieve:
I have an element on a webpage, let's call is storm
Every time the user clicks on the storm link, I want the following:
perform an API call which parameters are pre-defined BUT with the storm string as one of them
store the result (the API generates a JSON file) somewhere
parse the result with one method or another.
I have no problem parsing the JSON returned, but I would like to know how to do the first two steps.
NB: I use JS more than jQuery, but I'm not nazi on this.
Thank you very much for your help.
EDIT: thanks #ema
I've got a XHR model, attached under here.
Can you help me identify where I have to add my API url (from what I've understood, what is before the first question mark), and how to add to it the pre-defined parameters and the custom parameter (a string, containing storm for example)?
Thanks again
function XHR(url, method, data, onsuccess, onfailure, onprogress, onload, onabort) {
var request = new XMLHttpRequest();
// Ten seconds is ought to be enough for anybody.
var xhrtimeout = setTimeout(onfailure, 10000);
request.addEventListener("progress", onprogress, false);
request.addEventListener("load", onprogress, false);
request.addEventListener("error", onfailure, false);
request.addEventListener("abort", onabort, false);
request.addEventListener("readystatechange", function (e) {
if (request.readyState == 4) {
if (request.status == 200) {
clearTimeout(xhrtimeout);
onsuccess(request.responseText);
} else {
onfailure(e);
}
}
});
request.open(method, url, true);
request.send(data);
}
function getJSONAndParse(url, allDone) {
XHR(url, "GET", null, function(data) {
allDone(JSON.parse(data));
}, function() {
alert("error");
});
}
getJSONAndParse("http://lalala.com/json", function(parsedJSON) {
alert(parseJSON[0].name);
console.log(parseJSON);
});
You can use XMLHttpRequest, something like this:
var r = new XMLHttpRequest();
r.open("POST", "api/url", true);
r.onreadystatechange = function () {
var json = r.responseText;
// parse your json here
};
r.send("storm=value_of_storm&another_param=value_of_whatever");
HTH
Let me see if I understood..
To call an API from JQuery is very simple, and you cand use $.ajax (most complete) or $.post (simplest)
both you call on the click event that you can bind in $(document).ready with
$(document.ready(function(){
$('.mybuttons').off('click');//to only hit once if you have Postbacks
$('.mybuttons').on('click', myapicall);
});
example with $.ajax:
function myapicall(){
$.ajax({
beforeSend: function () {
// a 'Loading'
},
type: 'POST',
url: 'URL-OF-API',
contentType: 'application/json; charset=utf-8',
data: { stormvalue: 'the sorm value you want to send to API'},
dataType: 'json',
success: function (json) {
try {
json = JSON.parse(json.d);
// now you have a json object to play with, and if its a string, then you can """save""" using eg. input hidden
} catch (ex) {
alert(ex);//show the error parsing json
}
},
error: function (xhr, ajaxOptions, thrownError) {
var r = jQuery.parseJSON(xhr.responseText);
alert(r); // show the error of callback
},
complete: function (json) {
alert('sucess!');
}
});
}
example with $.post
function myapicall(){
$.post('URL-OF-API', { stormvalue: 'the sorm value you want to send to API'},
function (json) {
try {
json = JSON.parse(json.d);
// now you have a json object to play with, and if its a string, then you can "save" using eg. input hidden
} catch (ex) {
alert(ex);//show the error parsing json
}
}
);
}
Hope I can help you, and sorry for bad english, ;-)

How to pass AJAX variables to PHP

I understand I can't pass AJAX Vars directly to PHP, being a client versus server side script. But that being said, here's my code:
setInterval(function()
{
//do something after you receive the result
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("message_area").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","messages.txt",true);
xmlhttp.send();
}
I know I can indirectly process AJAX variables by POSTing them to a PHP page using AJAX, like so:
$.ajax (
{
type: "POST",
url: "decode.php",
});
I just need to know how to pass the contents of the "messages.txt" file used in the xmthttp.open call to a PHP file for further processing.
How can I do this?
If you are using pure javascript:
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
or if you're using jquery, simply:
$.ajax (
{
type: "POST",
url: "decode.php",
params: {param1: "val1", param2: "val2"}
});
Hope this helps :
$.get( "messages.txt", function( data ) { //Fetching contents of messages.txt file.
$.ajax ({
type: "POST",
url: "decode.php",
data: data, //passing contents of messages.txt file to decode.php
success: function(result){
alert(result);//Getting result from decode.php
}
});
});
cheers
Are you using jquery? You first code block is regular js, the second is jQuery's ajax short hand.
That said, if you want to POST data with ajax using jQuery, you would do something like the following.
var PostData = "something";
$.ajax({
type: "POST",
url: "someurl",
data: PostData
}).done(function(returnData) {
//process data returned from server, if there is any
});

How do I know when an ajax request is completed

How to know when all ajax calls are complete?,now I just use a delay timeout to wait the request complete,these is a better way?i want make sure ajax requests are completed...
The XMLHttpRequest object has readyState property and onreadystatechange that you can manipulate like that:
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) { // xmlhttp.status==200 == successful request
// What you want here
}
}
xmlhttp.open("GET", "foo_url.php", true);
xmlhttp.send();
}​
You can do it simpler with jQuery, if you're using that library:
$.ajax({
url: 'foo_url.php',
complete: function() {
// What you want here
}
});
If you're using jQuery's AJAX, it has a complete option, see docs
$.ajax({
url: 'foo.php',
complete: function(jqXHR, textStatus) {
alert('AJAX call complete');
}
});
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// This is when your Ajax request is complete
}
}
that is depend on your library; ex, if you are using jquery then you can use success: parameter and if javascript then you can use if (xmlhttp.readyState==4 && xmlhttp.status==200) statement.
If you are using xmlhttp object for ajax call then when xmlhttp.readyState==4 then it is consider as ajax request is completed.
$.ajax({
url: 'abc.php',
data: "&id=" + id ;
complete: function(data) {
alert(data.responseText);
}
});

Categories

Resources