jquery ajax always throws error (never becomes success) - javascript

Below is my piece of code.
My issue is the function on success never gets called.
It always throws the error section.
$.ajax({
url: 'http://localhost/zd/get_list',
data: 'term=' + medical_provider,
dataType: 'json',
type: 'GET',
success: function(data){
alert('success');
},
error: function(jqXHR, textStatus, errorThrown){
alert(jqXHR);
}
});
when i alert jqXHR is get [object Object] and when I alert textStatus I get "error" and when I alert errorThrown I get a blank error message.
I am using jquery 1.11.0.
I never get the success alert.
Your help is greatly appreciated.
Also the the data returned in json is properly validated. I did a test on jsonlint.

Your get_list server-side functionality is erroring.
Use chrome developer tools to breakpoint and inspect your jqXHR object in the error callback, it will have more details about what is going wrong.
Edit:- based on your updated comments, try adding:
contentType: 'application/json',
to your ajax call parameters

So it turns out, the base url (was using codeigniter) was my computers ip address instead of localhost. Accessing the through the ip addy OR changing the base url to localhost worked.
Thank you all for the help.

Related

Jquery load function throws "XML Parsing Error: not well-formed" error in firefox

Trying to load an xml file and getting the xml parsing error.
$("#analyticForm_description").load('https://192.168.23.10/SystemServices/main?system:run=html/indicators/templates/editApp-definition.xml&Id=1000205&palletId=testtt', function() { MD.ui.editPallets.editform_definition(); } );
Should not throw any error. Note the url provided is valid and accessible from a browser directly. The function is also being called. Somehow even after the error reported on console, page loads successfully.
Do not want to see any errors reported on console.
I think Firefox expects an Content-Type and Chrome ignores it.
$.ajax({
url : "https://192.168.23.10/SystemServices/main?system:run=html/indicators/templates/editApp-definition.xml&Id=1000205&palletId=testtt",
contentType: "text/xml",
success : function(response) {
$("#analyticForm_description").html(response);
}
});
or for the load method use ajaxSetup:
Description: Set default values for future Ajax requests. Its use is
not recommended.
$.ajaxSetup({
contentType: "text/xml"
});
$("#analyticForm_description").load('https://192.168.23.10/SystemServices/...', function() {
MD.ui.editPallets.editform_definition();
});
I was also facing a similar error and upon search i stumbled upon this post, after debugging code for a while i found out the reason.
Error shown in console
XML Parsing Error: undefined entity
Location: path-to-file.html#link3
Line Number 26, Column 29:
Here is why i was getting this error
I was dynamically generating url that i want to hit, and due to some typo i was getting undefined as the url which was used in making ajax calls resulting in this issue
$.ajax({
url: url, //this was undefined
type: "get",
data: data,
contentType: "text/xml",
success: function (response) {
//some code
},
});
Posting this as it might help someone facing the same issue.

JSONP Parse Error with valid JSON Output

I am calling a Cross Domain AJAX Request using JSONP. Now, i am able to make it work using CORS. But, i want to know why it is not happening with JSONP. I looked at other threads with similar problem but couldnt figure out why it is not working in my case.
Here is the code:
$.ajax({
type: "GET",
url: http://XXXX:8000/sap/bc/test_rest/jsonp_test?mode=S&ticket=123,
dataType: "jsonp",
jsonp: false,
jsonpCallback: "myJsonMethod",
success: function (data) {
alert(data);
},
error: function (httpReq, status, exception) {
alert(status + " " + exception);
}
});
Now, this calls my server, the data is populated and then i get an alert "parse error myJSONMethod was not called" on a callback URL http://xxxx:8000/sap/bc/test_rest/jsonp_test?mode=S&ticket=123&_=1470322282936
Additionally, in the console i get the error as Uncaught SyntaxError: Unexpected token :
The response structure is:
{"ROOT":{"CONTRACT":"40002356","ITEM":"000010","KUNNR":"0000004676","NAME":"REALTY EXECUTIVES","NET_PRICE":19.95,"GROSS_PRICE":19.95,"MATNR":"144","SQFEET":""}}
When i run this JSON Output on jsonlint it says it is a valid JSON. I don't know where the JSON is getting messed up.
Your data must be like this to be valid for JSONP:
myJsonMethod({"ROOT":{"CONTRACT":"40002356","ITEM":"000010","KUNNR":"0000004676","NAME":"REALTY EXECUTIVES","NET_PRICE":19.95,"GROSS_PRICE":19.95,"MATNR":"144","SQFEET":""}});
the responsetext must be valid js code and it will run immediately when the response is over.So if you write your code
{"ROOT":{"CONTRACT":"40002356","ITEM":"000010","KUNNR":"0000004676","NAME":"REALTY
EXECUTIVES","NET_PRICE":19.95,"GROSS_PRICE":19.95,"MATNR":"144","SQFEET":""}}
in a <script> tag,the console will throw an err like that

Token error when parsing return data in Ajax call

I am creating an app using HTML, jQuery Mobile, jQuery and Cordova. My requirement is to authenticate an user from the app by calling a remote server. I am developing my localhost WAMP stack.
My jQuery is as below.
$.ajax({
type: 'POST',
url: 'http://localhost/server/',
crossDomain: true,
data:{appkey:'1234567',action:'authenticate', username: u, password :p},
dataType: 'jsonp',
async: true,
success: function (data){
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Invalid Username or Password");
window.location = "index.html";
}
});
The remote call url is below. JQuery automatially adds ?callback= to the remote url as the datatype is jsonp, which is fine.
localhost/server/?callback=jQuery18306688079617451876_1383495199431…4567&action=authenticate&username=fdf&password=fdfdf&_=1383495208981
The response from the remote url is as below in Chrome Developer console.
{"success":"false"}
In the PHP part at server, I am using the below code to return the json object.
header('Content-type: application/json');
echo json_encode($araryVal);
It looks for me that all things are perfect, but my code breakpoint never reaches the success section of the ajax call. It always break out in error section.
In the developer console I see the error message.
Uncaught SyntaxError: Unexpected token :
JsonLint says the json is valid. Please let me know what I am doing silly.
I don't think your data type is JSONP, it's just JSON. If it were JSONP, your content-type should be "application/javascript" and your response text should wrap the JSON object it returns with the javascript function provided to the server in the callback parameter.
(Actually your error is probably PHP emitting a notice about an undefined variable: araryVal ... You sure that shouldn't be arrayVal? :)
I already accepted the answer provided by #Fabio. I just want to provide the technical details which solved my problem.
The hint from Fabio helped me to do some research on this. Thanks man.
I have added the callback options to the ajax call as below.
$.ajax({
type: 'POST',
url: 'http://localhost/server/',
crossDomain: true,
data:{appkey:'1234567',action:'authenticate', username: u, password :p},
dataType: 'jsonp',
contentType: "application/javascript",
jsonp: 'callback',
jsonpCallback: 'mycallback',
async: true,
success: function (data){
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Invalid Username or Password");
window.location = "index.html";
}
});
The remote call url is as below after the above change. JQuery now add "mycallback" instead of some random callback value "jQuery18306688079617451876_1383495199431…4567" for callback parameter.
localhost/server/?callback=mycallback&action=authenticate&username=fdf&password=fdfdf&_=1383495208981
In the PHP side I modified the output to include the callback value with the json string.
header('Content-type: application/javascript');
echo "mycallback(" . json_encode($araryVal) . ")";
Today was the day I understood how to use jsonp with callback. Thanks to all.

Ajax call fails in Chrome, but works in Firefox

Any idea why the following Ajax call fails in Chrome, but not Firefox?
$.ajax({
type: "GET",
contentType: "text/csv; charset=utf-8",
dataType: "text",
cache: false,
url: "http://127.0.0.1:8080/param1/param2?param3=csv&otherParams=type1,type2,type3"
})
.done(function(data) {
console.debug("Data received from ajax call: " + data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.error("Data request failed (" + textStatus + "): " + errorThrown);
console.debug(jqXHR.responseText);
});
The URL that I am calling should return the data in csv format. I'm using jQuery 1.8.2. This works in Firefox, but not Chrome for some reason. The error message that I print out is:
Data request failed (text/csv): text/csv
Interestingly, in Chrome I can see the data returned in the jqXHR.responseText, so I can't figure out why it's throwing an error. I assume it has something to do with my not specifying the csv format properly, but I thought setting the dataType or contentType would fix that. What am I missing?
I realize this is a common problem, but in spite of my Googling and searching around Stack Overflow, I have been unable to find a solution that fixes this problem for me. All the suggestions I've found have said to set the contentType, the dataType, or the cache to false. As you can see, none of these solutions has worked for me. Your help is greatly appreciated!

how to get error message of failed ajax

I want to consume a webService which I get JSON Data from
$.ajax({
type: 'GET',
contentType: 'application/json',
dataType: 'JSON-P',
//the url shows the correct JSON Data when I copy the URL in my browser
url: 'http://url.com',
success: function(data){
console.log(data);
alert(data);
},
error: function(xhr, testStatus, error){console.log("Error occured: "+error+" "+xhr+" "+testStatus)}
})
In Firefox, It calls back with the error function, but I dont know what the problem is, it would be great to know the error message but my approach doesnt work.
thanks in advance
edit: In Chrome I get the following error:
Origin null is not allowed by Access-Control-Allow-Origin.
edit: It´s solved, the problem was indeed that json doesnt work cross site, and the data was not "jsonp-conform" (it had to set a function(json data...))arround the json data. This could be done by changing the url at the end "_&jsonp=successCallback. Sorry for bothering you
I think there was a JSON object syntax error. Check your JSON object syntax error with jsonlint.com.
Are you getting this error locally?
Try it on a server and if it doesn't work: XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin

Categories

Resources