$.ajax post request not sending data parameters to server - javascript

I am running into problem requesting data from an API. The documentation states that I must make a post request. My goal is to make the request with jQuery, then style the resulting data.
Since I'm using a Cross-Domain-Request, I know that I have to use jsonp. The issue is that I get parseerror when I run this code because the server is returning an XML error. (The server defaults to an xml response if no format is specified)
$.ajax({
type: 'POST',
url: url,
data: {format: 'json'},
dataType: 'jsonp',
success: function(data) {
console.log("Success.");
},
error: function(data, error, err) {
console.log(data.status);
console.log(error);
console.log(err);
}
});
Inside the inspector I see:
Uncaught SyntaxError: Unexpected token <
menu?&callback=jQuery2240569993828256961_1469752734662&format=json&_=1469752734663:1
This is the XML response...
<?xml version="1.0" encoding="UTF-8"?><response> <response_header> <response_code>ERROR</response_code>
</response_header>
<response_details> <error_details>The post parameters contain an invalid or disabled API ID</error_details>
</response_details>
</response>
Because it returns XML, I can determine that the server is not even recognizing my parameter {format: 'json'}, because here is the same request in Python:
from urllib.parse import urlencode
from urllib.request import Request, urlopen
url = url # Set destination URL here
post_fields = {'format':'json'} # Set POST fields here
request = Request(url, urlencode(post_fields).encode())
json = urlopen(request).read().decode()
print(json)
And the resulting JSON response:
{"response_header":{"response_code":"ERROR"},"response_details":{"error_details":"The post parameters contain an invalid or disabled API ID"}}
As you can see, it responds with JSON demonstrating that the server read the post request.
For some reason, the AJAX request is not sending the parameters through which means I can't even get back the actual data I need by including the api key + api id.
Can anyone tell me what is going on here?
Thank you.

Related

How can i do cross domain query using ajax & jsonp?

I send ajax to url , but i get error.
Here is my code:
$.ajax({
url: "http://webrates.truefx.com/rates/connect.html?q=ozrates&c=EUR/USD&f=csv&s=n",
dataType : 'jsonp',
success: function (data) {
alert(data);
}
})
Maybe i doing something wrong?
In order to access data using JSONP, the server you are requesting the data from must format its response as JSONP.
You are getting an error because the response is not JSONP (it is CSV, which you asked for explicitly when you put t=csv in the query string).
Either:
Use a different method to get the data
Change the server so it responds with JSONP formatted data

Ajax post response coming back successfully - can't log/print to screen

I'm successfully posting data to the server via $.post(). When I attempt to do anything with the response, I get nothing. No console log. Can't replace text or HTML with the data. Nothing.
Here's the post:
$.post(myUrl, {myVar: myVar}, function(data) {
console.log(data);
});
And here's the response:
It may not be able to "guess" the data type as the default 4th parameter not set implies. set dataType parameter
$.post(myUrl, {myVar: myVar}, function(data) {
console.log(data);
}, 'text');
Also be sure that it returns a 200 OK response from the server or else success won't run.
You need to modify the response (probably) into a JSON format so that you can catch it. PHP's header for JSON is:
header("Content-Type: application/json"); //Set header for outputing the JSON information
You will need to include that in your PHP file that you are sending a request to. You may also need to specify the headers content in the post request, as I mainly use Angular, I'm a bit unsure of what the AJAX header for this case, but try something like:
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }

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");
}
});

415 Unsupported Media Type Using JQuery/FormData and Web Api

I'm getting a Error :
"POST {URL} 415 (Unsupported Media Type)" error
And cannot figure out why it's happening.
I'm trying to upload an excel file in JQuery using FormData.
Here is the code:
var formdata = new FormData();
var file = input.get(0).files[0];
formdata.append('content', file);
var url = "/Phrase/Import/" + $('.exportPanel #Language').val()
var ajax = $.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (data, textStatus, jqXHR) {
//Do something.
},
error: function (jqXHR, textStatus, errorThrown) {
//Do something.
}
});
Here is the controller code:
[Route("Import/{languageID}")]
[HttpPost]
public void ImportPhrases([FromUri]int languageID, [FromBody]Stream content)
{
_service.ImportPhrases(content, languageID);
}
I noticed that, according to Fiddler, the content type of the request is different to that of the response (not sure if this makes a difference?).
Request: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Response: application/json; charset=utf-8
The JQuery above is being used in a different part of the system, but uses WCF instead of Web API (am in the process of changing from WCF to MVC/Web API), again I'm not sure if this makes a difference?
Can anyone tell me what I'm doing wrong please?
Many thanks.
415 Unsupported Media Type
The request entity has a media type which the server or resource does not support. For example, the client uploads an image as image/svg+xml, but the server requires that images use a different format.
contentType does matter - it tells the server what you are uploading. In this instance, you have set the value to false. The server cannot recognise this, so it returns false. If you do not need a specific content type, you should remove the contentType line to allow the jQuery default to kick in.

GET ajax request

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

Categories