GET ajax request - javascript

I'm sending GET request (which returns JSON).
The code looks like:
$.ajax({
url: "http://www.new.marketprice.ru/retrieveRegions.html",
dataType: "jsonp",
data: {
searchStr: request.term
},
error: function() {
console.log('epic fail');
},
success: function( data ) {
console.log(data);
}
});
It returns (into console);
Resource interpreted as Other but transferred with MIME type undefined.
epic fail
But in Network tab I see GET request with returned data:
[
{ "region":"Московская область","countryId":1,
"cityId":23,"regionId":12345,"city":"Москва","country":"Россия"},
{"region":"Ленинградская область","countryId":1,"cityId":453,
"regionId":54321,"city":"Санкт Петербург","country":"Россия"}
]
Why does error callback is called?
UPD
Okay, I set json and now no warning but error:
XMLHttpRequest cannot load http://www.new.marketprice.ru/retrieveRegions.html?searchStr=test. Origin http://new.marketprice.ru is not allowed by Access-Control-Allow-Origin
It's so strange because running script is located at same domain :(

It is only a json response not JSONP. Generally for JSONP the request will have callback method and response will be wrapped in that function name

Your headers don't specify the correct mime-type (application/json-p) and jQuery(?) is confused because it's not sure if it should process it as json or not.
See if you can get your server to respond with the correct type. The appropriate header is called Content-Type.
EDIT: whoops, and the OP is right, its not even JSON-P. Try changing what jquery is expecing to just 'json' first.

i was also in problem like this just try by using one more argument callback=? or json=jsonp

Related

jQuery ignores HTTP request method and appends weird URL parameters

I have a web service that expects POST requests carrying a JSON string in the body. I'm trying to use this web service using jQuery, but I have two problems :
1) jQuery seems to always use the GET method, no matter what I do ;
2) jQuery seems to append weird things into the URL.
The relevant pice of my code :
var WEB_SERVICE_URL = 'http://localhost/XXXX/';
// ...
$.post({
url: WEB_SERVICE_URL + 'GetConfigLabels/',
contentType: 'application/json; charset=utf-8',
dataType: 'jsonp',
data: JSON.stringify(data),
processData: false,
success: function(response) {
// Whatever
},
error: function(xhr, message) {
// Whatever
}
});
The developper tools of the browser (Firefox Quantum 60.0.2) shows me a weird URL :
http://localhost/XXXX/GetConfigLabels/?callback=jQuery331012146934861340841_1530707758905&{}&_=1530707758906
While the following was expected :
http://localhost/XXXX/GetConfigLabels/
Also the HTML file is openned as a file (using file:///) through the file system, hence the use of JSONP for cross domain.
I failed to find existing questions related to this issue. What could be causing this ? Thank you !
Please refer to the dataType : json section at http://api.jquery.com/jquery.ajax/ :
"json": Evaluates the response as JSON and returns a JavaScript
object. Cross-domain "json" requests that have a callback placeholder,
e.g. ?callback=?, are performed using JSONP unless the request
includes jsonp: false in its request options. The JSON data is parsed
in a strict manner; any malformed JSON is rejected and a parse error
is thrown. As of jQuery 1.9, an empty response is also rejected; the
server should return a response of null or {} instead. (See json.org
for more information on proper JSON format
overrding random name of callback using jsonpCallback :
jsonpCallback Type: String or Function() Specify the callback function
name for a JSONP request. This value will be used instead of the
random name automatically generated by jQuery. It is preferable to let
jQuery generate a unique name as it'll make it easier to manage the
requests and provide callbacks and error handling. You may want to
specify the callback when you want to enable better browser caching of
GET requests. As of jQuery 1.5, you can also use a function for this
setting, in which case the value of jsonpCallback is set to the return
value of that function.

Uncaught SyntaxError: Unexpected token : - data still coming through

I'm very new to JSON and JSONP.
I've read through each of the posts that are recommend by the SO search for this error, but I can't seem to get a handle on it.
I have the following code to grab data from an EXTERNAL website:
$.ajax({
url: "https://url.com/authenticate?login=test&apiKey=test",
dataType: 'jsonp',
success:function(json){
console.log("login successful");
}
});
When I load the page, I get:
Uncaught SyntaxError: Unexpected token :
and when I click on the error in Chrome, I see
{"Status":{"Code":"2","Message":"Authentication Succeeded","Success":"true"}}
with a little red x after "true"})
From this, it seems as though I have succeeded in logging in, but I'm doing something else wrong because my console.log("login successful"); never fires. What am I doing wrong?
P.S.
I've tried dataType: 'json' but I get the No 'Access-Control-Allow-Origin' header is present as I'm on a different server, so I went back to jsonP as this is cross-domain.
I've also tried the above url as url: "https://url.com/authenticate?login=test&apiKey=test&callback=?", as I've read I need a callback, but I don't really understand what the functionality of callback is and either way, the error that gets returned (whether &callback=? is in there or not) is:
authenticateUser?login=test&apiKey=test&callback=jQuery111107732549801003188_1423867185396…:1 Uncaught SyntaxError: Unexpected token :
so it's adding the callback in either way....
Also, from the API I'm trying to access:
"this uses the REST protocol, and provides data structured as XML or JSON"
This is not a duplicate of the linked post as the information in the linked post does a great job of explaining what JSONP is, but doesn't answer my specific question regarding why I get data back (so my call is successful,) but why I still get an error and cause my script to stop.
The API you're sending the AJAX request doesn't implement JSONP. It ignores the callback= parameter, and just returns ordinary JSON. But when the browser tries to process this as JSONP, it gets a syntax error because it's not properly formatted. JSONP is a JSON object wrapped in a call to the specified callback function, e.g. it should be sending back:
jQuery111107732549801003188_1423867185396({...});
where {...} is the JSON object you're trying to retrieve. But it's just returning {...}.
You should implement this using a PHP script on your own server. It can be as simple as this:
<?php
$username = urlencode($_POST['user']);
readfile("https://url.com/authenticate?login=$username&apiKey=test");
Then your AJAX call would be:
$.ajax({
url: "yourscript.php",
type: "post",
dataType: "json",
data: { user: "test" },
success: function(json) {
console.log("login successful");
}
});

How to get PHP page returned by a jQuery Ajax request

So I have to send some data to a php page, and it will return me another php page based on my data.
I send the data this way:
$(document).ready(function() {
$.ajax({
url: '//www.example.com/page.php',
type: "post",
dataType: 'jsonp',
data: { myvar:myvalue },
success: function(response) { console.log("success."); },
error: function(XMLHttpRequest, textStatus, errorThrown) { console.log("error."); },
complete: function() { console.log("complete."); }
});
});
It shows an alert saying jQuery180014405992737595236_1357861668479 was not called (numbers are copied from other question)
I think the reason is that it's expecting a json result from the page, when it's not.
In Chrome it says Uncaught SyntaxError: Unexpected token < referring to the returned php page, so I assume that my code isnt expecting that kind of file to be returned.
To sum up, this works, but that jQuery alert and the console error needs to be fixed, and I think the right way would be handling properly the returned result page.
I hope you guys can help me fix it that seems quite a simple task, but Im really new to this. Thanks
Removing the dataType: 'jsonp' or changing it to 'json' turns out on my script not being executed and getting the following error:
XMLHttpRequest cannot load http://www.example.com/page.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://myserver.com/myPage' is therefore not allowed access.
I think the reason is that it's expecting a json result from the page
It's expecting a JSONP response. (JSONP is not JSON). You said:
dataType: 'jsonp',
… which explicitly forces jQuery to treat the response as JSONP (and, as a side effect, GET).
the returned php page, so I assume that my code isnt expecting that kind of file to be returned.
The server shouldn't be returning a PHP page. It should be executing the PHP code and returning whatever that outputs. It looks like it is outputting HTML.
You need to either:
Not tell your script to expect JSONP. (Note that you'll probably then have to configure CORS on the server to deal with same origin issues) or
Change the PHP to return JSONP

JQuery AJAX JSONP Invalid Label

I know this question has been asked, but I cannot get it working.
I execute the following AJAX request:
function dislikeMeme(memeId) {
$.ajax({
dataType: "jsonp",
url: "http://<url>.com/dislike/" + memeId,
data: {
u: "username",
p: "password"
},
jsonpCallback: 'successCallback'
});
}
function successCallback(data) {
alert("Test"); // Not firing because of previous 'Invalid label' error
};
Looking at firebug I see that the request was successful, but there is an Invalid Label error which fires the Error callback of the request. The response of the request is as follows:
{
"id":6220673,
"myScore":-1,
"msg":"Not loved"
}
I see that the parentheses are causing JavaScript to interpret the response as an object, but I know this is the format I am retrieving, isn't there anyway to parse this before it causes an error?
I also see that the URL of the page returning this information is:
http://<url>.com/dislike/123456?callback=successCallback&u=username&p=password&_123456789
Everything is working perfectly except this Invalid label error. Does anyone have any ideas?
Thanks in advance everyone
A server that can handle JSONP takes the callback paramater (can be different parameter depending on WS) and passes it in the response. So the response from the server should be:
successCallback({
"id":6220673,
"myScore":-1,
"msg":"Not loved"
})
If you don't have control over the server your only route is proxy. See my cross domain answer for information on getting around same origin policy.
What prevents me from using $.ajax to load another domain's html?

JQuery ajax call to cross-domain webservice

I would like consume cross-domain web-service from client with jquery
function TestService() {
$.ajax({
url: "http://service.asmx/GetGeoCompletionList",
data: { "prefixText":"eka", "count":"10", "contextKey":"Trace_0$Rus" },
dataType: "jsonp",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.statusText);
}
});
}
At the error hander I have:
textStatus=parseerror
XMLHttpRequest has status 200 and readyState 4
errorThrown is jQuery16103495572647140...78197139 was not called
I've spent on it for a lot of hours and couldn't make it work. Can u help me?
UPDATED
Thanks, I change to GET, and fix my data string.
Service returns valid JSON object. I can see it at firebug on other site, which consume this service. But that site is getting common json(since it has one domain).
So, if the web-service returns valid JSON(not jsonp), I can't use the same method with jsonp? What can I do for consiming json web-service from other domain?
That string you are passing and claiming is JSON isn't JSON.
Only " characters may be used to quote strings.
Also, you can't make a cross domain JSON-P POST request.
You cannot do cross-domain POST requests using JSONP. JSONP works by adding script tags to the page. script tags always fetch their source using GET HTTP requests. You won't get any data posted.
Summary of problems:
Make sure you're using valid JSON
as #Quentin mentioned.
Make sure you're using GET requests, as
#lonesomeday mentioned
Make sure the response from the server is
JSONP, as seen here

Categories