Ajax jquery call to GET application/x-javascript - javascript

How do I get content of "application/x-javascript" using jquery Ajax call?
As it keep getting me null content.
What I am trying to use for now:
$.ajax({
dataType: "json",
contentType: "application/x-javascript;charset=utf-8",
url:the_url,
async:false,
success:function(r){
console.log("el result" + r) ;
response = r;
}
});

This:
dataType: "json",
tells jQuery to ignore what the server claims it is sending back and to process the result as JSON. JavaScript isn't JSON, so this breaks it.
Remove that line.
Then you should get the data in the success function.
Asides:
This:
contentType: "application/x-javascript;charset=utf-8",
claims you are sending JavaScript. You aren't making a POST request, so you aren't sending anything. Remove it.
Even if you were sending JavaScript to the server, the application/javascript MIME type hasn't been experimental since 2006, so it shouldn't have the x- prefix on it.
async:false, is a terrible idea. It locks up the JS event loop waiting for the response. You shouldn't use it.
response = r;: assigning data to globals is usually a terrible idea. Process the data in the success event handler instead.

Try this out :
$.ajax({
url: 'my/url',
type: 'GET',
data: 'test=mytest&test2=mytest2',
success: function (data) {
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
And read the documentation, to see what each parameter is made for :
http://api.jquery.com/jquery.ajax/

Related

What happens when wrong dataType is returned

I perform a call
$.ajax({
type: "POST",
url: url,
data: dataToPost,
dataType: "json",
success: function(data, textStatus){ /*something*/ },
failure: myHttpReqErrorHandler
});
In certain cases when things goes wrong on the server I get
Content-type:text/html; charset=UTF-8
type, and content is a real HTML page, and there is not much I can do about that. I want to manage this case on JavaScript, but when this happens no callback is called on jQuery side (neither success nor failure).
Is there a further parameter to pass to ajax to handle that?
The error handler is error: function(){}
error: myHttpReqErrorHandler
It will throw a parse error(parsererror) if the content is not a parsable json format.
Demo: Fiddle

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.

Uncaught SyntaxError: Unexpected token : ajax call

So I'm trying to query the below json feed, however I keep getting the error in the topic.
I've searched around this site for possible answers however none that I've come across have worked so far. Commented out datatype and jsonp, jsonpCallback isnt it either, either is data, I've made sure that it validats via http://jsonformatter.curiousconcept.com/ and it does. I really dont know.
$.ajax({
type: 'GET',
url: 'http://raidbots.com/json/playerdata/us/mannoroth/usiris',
cache:true,
dataType: 'jsonp',
data: {
format: 'json',
},
success: ranks,
jsonpCallback:'callbackName',
error: function(data) { console.log(data); },
jsonp: false,
});
function callbackName(data){
console.log("jsonpCallback");
}
var ranks = function(data) {
console.log(data);
}
Thank you
-Art
The error is in your JSONp data because it's just JSON and not JSONp. JSONp requires the document to be valid JavaScript containing a function call.
If they don't support jsonp you need to use a proxy script (e.g. a php script on your server that retrieves the document) or ask them to send CORS headers so you can use a normal non-JSONp AJAX call to retrieve the data directly.

How do i read simple json result with jquery and how to post new

I built a WCF service which produces JSON. I want to make an external website which uses this webservice. For now I am executing the WCF service over LAN by IIS, so I can connect to the service by going to http://myownaddress/blabla.svc/
I tried to learn some json and to get some results from my service.
For example if I want to use this method:
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "json/{id}")]
string JSONData(string id);
I'll go to http://myownaddress/blabla.svc/json/123
And as result I get:
{"JSONDataResult":"You requested product 123"}
Now I have tried to receive this result with the JQuery statement getJSON. But I don't see any results.
My question is how can I get this simple data?
And secondly how can I post data(with javascript) back on to the wcf service is it also possible with json?
-edit-:
I have now updated my code and put this into my document ready function which is located between the <head> <script> .... on my page:
$.getJSON(
'http://myownaddress/blabla.svc',
function(data)
{
alert(data.JSONDataResult);
});
But this won't give the alert with the result. It doesn't even give an alert.. Besides that, in the function I need to give a parameter of id, so for example 123 (look in text above) don't I need to put that in the function also?
To get data use getJSON():
$.getJSON(
'http://myownaddress/blabla.svc/',
function(data) {
alert(data.JSONDataResult);
}
);
To post data you can use this:
$.post('http://myownaddress/postservice.svc', function(data) {
$('.result').html(data);
});
or this (if you need more control):
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
You can also use the ajax for getting the data instead of the getJSON method .
UPDATE:
try using ajax method as it gives you more control:
$.ajax({
type: 'GET',
url: "http://myownaddress/blabla.svc/json/123",
success: function(data){alert(data)},
dataType: "json",
complete: function(data){alert(data)},
error: function(jqXHR, textStatus, errorThrown){alert(errorThrown)}
});
Also, if you use firefox, check out firebug extension, it will help you greatly.
If you use chrome then use chrome developer tools.
In order for your to get the json data from a WCF service that is outside your website using Jquery you need to use JSONP.
You can perform the call as shown below:
$.ajax({
url: "http://myownaddress/blabla.svc/",
dataType: "jsonp",
type: "GET",
timeout: 10000,
data: null,
jsonpCallback: "MyCallback",
success: function (data, textStatus, jqXHR) {
alert(action.toLowerCase());
},
error: function (jqXHR, textStatus, errorThrown) {alert('error is:' + errorThrown);
},
complete: function (jqXHR, textStatus) {alert('complete');
}
});
JSONP is used when you want to perform a cross domain calls using Javascript.
Also your WCF service should be compatible to handle JSONP calls by injecting the results to the response stream using the callBack method specified in the URL.
Do you have your code like this ?
$.getJSON(
'http://myownaddress/blabla.svc/',
function(result) {
alert(result.JSONDataResult);
}
);
Remember getJSON will not immediately return you the data, you have to make use of the result in a callback function.
Why did you change your url?
$.getJSON(
'h t t p://myownaddress/blabla.svc' ==> 'h t t p://myownaddress/blabla.svc/123',
function(data)
{
alert(data.JSONDataResult);
});

jQuery $.ajax call works in Chrome, but not any other browser

The following call works perfectly in Chrome, but fails in every other browser.
function getInfo(r,c,f){
return $.parseJSON($.ajax({
url: baseURL + 'somethingAPI/getInfo',
data: {
"data_r": r,
"data_c": c,
"data_f": f
},
//success: function(data){},
dataType: "json",
async: FALSE
}).response);
}
Yes, I'm using a synchronous ajax call and I believe it is necessary as I don't want any of the other JS to run without this executing and returning data. Although, I'm not entirely sure if something else should be happening with the success callback.
Anyway, in Chrome I get the response object (JSON) and can access the data within just fine.
Does anyone know what I'm doing wrong?
Regarding your point about not knowing how to avoid async: false, is this something like what you're looking to accomplish?
function getInfo(r, c, f, callback) {
$.ajax({
url: baseURL + 'somethingAPI/getInfo',
data: {
"data_r": r,
"data_c": c,
"data_f": f
},
dataType: "json",
success: callback,
});
}
getInfo('foo', 'bar', 'baz', function(response) {
console.log(response);
});
Rather than parsingJson on the ajax query, here's the syntax I use to conquer these challenges
$.ajax({
url: "pagegoeshere.php",
timeout: 30000,
type: "POST",
data: 'data1='+data1+'&data2='+data2,
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("An error has occurred making the request: " + errorThrown)
},
success: function(returnjson){
var returnstuff = returnjson.returnstuff;
//Do next Javascript step here
}
});
You can run ensuing javascript/jquery in the success and "stack" events together on success of your Ajax call. That way, if it works, it proceeds. Otherwise, the error handling can occur in the provided error section in a manner that you define. I generally fire my ajax calls on a click handler, but it's certainly doable to run it in a function as you have chosen. Be sure to check your return JSON (could be mailed from your processing page, for example) to make sure it's valid JSON. Jsonlint is your friend!
I've had chrome effectively parse bad HTML and JSON while the other browsers don't on several occasions. I'd suspect it's something along those lines that's specifically causing your issues.

Categories

Resources