jQuery - Ajax POST request converted to GET request - javascript

I am trying to POST json data via ajax. The json data contains a large html table. However, this POST request is converted to GET request and I get Error 414 (Request-URI too long). I know jsonp POST requests are converted to GET, but why my json request is converted to GET?
$.ajax({
url: 'api.php',
method: 'POST',
data: {
'call': 'emailSalesReportToAdmin',
'tableHtml': $('#tblSalesReport').parent().html()
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
});

Yes , for older version, please use type:'POST' instead of method:'POST'
As mentioned on jQuery documentation
type (default: 'GET') Type: String An alias for method. You should use
type if you're using versions of jQuery prior to 1.9.0.

I found the issue and it was an older version of jQuery. The above code worked fine in jQuery version 1.12.

Related

Javascript POST to API

So I am a bit lost and hoping you can help me out. I am writing an app in simple PHP/HTML/Javascript app.
My Goal: To POST json data to an API.
How can I go about this? I just can't find any good examples to show me the best way to handle this.
In my request I need to send Basic Authorization as well as the json values.
This is what I have right now
$.ajax({
type: "POST",
url: "host.com/api/comments",
dataType: 'json',
async: false,
headers: {
"Authorization": "Basic xxxxxxxxxxxxxxxxxxxxxxx"
},
data: '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}',
success: function (){
alert('Comment Submitted');
}
});
I can't get the above code to work. Im using a button to call a function that will start the ajax call but nothing is happening.
Any help be be amazing! Thank You.
Use
contentType:"application/json"
You need to use JSON.stringify method to convert it to JSON format when you send it,
And the model binding will bind the json data to your class object.
The below code will work fine (tested)
$(function () {
var customer = {contact_name :"Scott",company_name:"HP"};
$.ajax({
type: "POST",
data :JSON.stringify(customer),
url: "api/Customer",
contentType: "application/json"
});
});
If you're writing the API in PHP, and it uses $_POST to get the parameters, you shouldn't send JSON. PHP only knows how to decode multipart/form-data and application/x-www-form-urlencode. If you pass an object to $.ajax, jQuery will use the urlencode format.
Just take the quotes off the object that you're passing to the data: option.
$.ajax({
type: "POST",
url: "host.com/api/comments",
dataType: 'json',
async: false,
headers: {
"Authorization": "Basic xxxxxxxxxxxxxxxxxxxxxxx"
},
data: {"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}},
success: function (){
alert('Comment Submitted');
}
});
You also shouldn't use async: false, it is deprecated. Learn to write proper async code.
Nobody seems to have addressed one issue - the URL
If the page this is requested from is http://yourhost.com/path/file.html the request will be sent as http://yourhost.com/path/host.com/api/comments
As you have host.com in the URL, I assumed the request is to a different domain?
use one of
http://host.com/api/comments
https://host.com/api/comments
//host.com/api/comments
will only work if your page is loaded http and not https
will work only if the remote API supports https
will only always work properly if the remote API supports both http and https
The other issue is regarding the format of the sent data
The default content-type for $.ajax POST is application/x-www-form-urlencoded; charset=UTF-8
So, sending a POST request with various combinations of contentType and data shows the following
Firstly, without setting contentType
data: '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}'
request is sent as formData '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}'
data: {"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}},
request is sent as formdata, the following values:
value1: 2.0
value2: setPowerState
value3[state]: 0
looks better, because there's actually multiple values, not just a string
Now, let's set contentType
contentType: 'json', data: {"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}},
firefox does not tell me the format of the following string: 'value1=2.0&value2=setPowerState&value3%5Bstate%5D=0' - looks useless
And finally
contentType: 'json', data: '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}',
sends the following JSON: '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}'
So, finally, if the API requires JSON request data, and it's actually on a domain called "host.com"
$.ajax({
type: "POST",
url: "//host.com/api/comments",
dataType: 'json',
contentType: 'json', data: '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}',
});

JSONP via getJson not working?

I have getJson like this:
$.getJSON(userUrl+'scanp?callback=?', { 'someparametar': 100 }, function(data){
console.log(data);
});
and I do get a response from my url, and it looks like this:
'"jQuery1110010384737118147314_1401820556204({'hasWon':'false','code':'120580e9fce67a4921f31af7ffa358cc10c83b10','defaultReward':'{\"secure_url\":\"https://res.cloudinary.com/deh0vdgzd/image/upload/v1401318096/k6jrm2pehwycmehrkicz.png\",\"url\":\"http://res.cloudinary.com/deh0vdgzd/image/upload/v1401318096/k6jrm2pehwycmehrkicz.png\",\"resource_type\":\"image\",\"format\":\"png\",\"height\":960,\"width\":640,\"signature\":\"a8ca9bb867e0a3d99e1666b7891e8f918d81e627\",\"version\":1401318096,\"public_id\":\"k6jrm2pehwycmehrkicz\"}''}"'
Any idea why I don't get any response when I console.log it?
With 'callback' in your querystring, JQuery wraps the response with a randomly generated method name. To get JSON (without method name), remove 'callback=?' from querystring.
If your server supports JSONP, you can make a call like this :
$.ajax({
type: 'GET',
url: url,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.log(JSON.stringify(json));
},
error: function(e) {
console.log(e.message);
}
});
Hope this helps.
Well I figured it out, the request I wrote was perfectly fine. The thing that was causing the the problem was response I was getting from server.
It was JSON stringified before return.

SyntaxError: missing ; before statement jquery jsonp

I am using below code to access rest service hosted on another domain.
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType:"jsonp",
success: function(json) {
alert(json);
},
error: function(e) {
console.log(e.message);
}
});
I am able to get the data correctly, but I get this error in firebug in mozilla:
SyntaxError: missing ; before statement
{"Hello":"World"}
Can anyone suggest me what I am doing wrong here? Even though Json data is valid. I tried all the suggestions posted in this question But still I am getting same error.
If it's really JSON you ask for, don't set "jsonp" as dataType, and don't provide a callback :
$.ajax({
type: 'GET',
url: url,
contentType: "application/json",
success: function(json) {
alert(json);
},
error: function(e) {
console.log(e.message);
}
});
the format of JSON and JSONP are slightæy different
JKSONP is a function invocation expression
callback({"hellow":"world"});
whereas JSON is simply a serialized object
{"Hello":"world"}
fromyour posting it would seem that the server is returning JSON and not JSONP
So you either need to change the server to reply correctly (The actual callback name is a get parameter to the request). You should do this if you are using the ajax call across domains
If you are not using ajax across domains stick to regular JSON

jQuery Ajax PUT not firing

The following ajax works exactly as advertised in Chrome. HTTP PUT is used to trigger the insertion of an object into a RESTful API.
$.ajax({
type: "PUT",
url: "/ajax/rest/team/create/",
dataType: "json",
processData: false,
data: JSON.stringify(teamObject),
success: function (response) {
teamObject = response.object;
}
});
I note that the jQuery API docs helpfully tell me that PUT and DELETE may work but are not guaranteed in all browsers. Such as is my problem.
How is a RESTful API supposed to be implemented on the client side with a problem like this?
EDIT: Firebug tells me that FF is indeed issuing a PUT, but for some currently unknown reason it's dying before getting to the server. To repeat, this works fine in Chrome.
EDIT: Fiddler doesn't see the FF attempt at all. :(
I got the following to work.
var payload = JSON.stringify(teamObject)
syncHTTP('/ajax/rest/team/create/', 'PUT', payload);
function syncHTTP(url,method,payload) {
var client = new XMLHttpRequest();
client.open(method, url, false);
client.setRequestHeader("Content-Type", "text/plain");
client.send(payload);
}
I'd rather use jQuery than roll my own tho. :| If anyone ever figures it out, just add an answer and if it works I'll accept it.
Thanks.
$.ajax({
type: "PUT",
url: "/ajax/rest/team/create/",
dataType: "json",
contentType: "application/json",
processData: false,
data: JSON.stringify(teamObject),
success: function (response) {
teamObject = response.object;
}
});
You need to add contentType. When contentType is set to application/json jquery do not try to create JSON object from JSON string but send it as is - as string.

jQuery Handling JSON responses

I have the following from the server response:
{"invalid_emails":["adsasdasd"],"result":"success","valid_emails":["jobs#apple.com"]}
But this errors?
$.ajax({
type: 'POST',
url: '/users/invitation',
data: $('#user_invitation_new').serialize(),
success: function(e) {
jsonObject = jQuery.parseJSON(e);
jsonObject.valid_emails
jsonObject.invalid_emails
I get the following error: Uncaught TypeError: Cannot read property 'valid_emails' of null
As Jason and Jonathon mentioned, you should not manually deserialize the JSON. Depending on what version of jQuery you're using, jQuery will automatically deserialize JSON based on the response's content-type header. So, you're probably trying to $.parseJSON() something that's already an object, not a JSON string.
To be sure that jQuery does this automatic deserialization for you, add a dataType parameter to the $.ajax() call:
$.ajax({
type: 'POST',
dataType: 'json',
url: '/users/invitation',
data: $('#user_invitation_new').serialize(),
success: function(response) {
console.log(response.valid_emails);
console.log(response.invalid_emails);
}
});
You may not have to parse that JSON, as it is already a JSON object. try doing
var emails = e.valid_emails;
If this still does not work, include dataType: 'json' in your .ajax() declaration.
If your server responds with the JSON then you should have to run jQuery.parseJSON(e);. The e parameter might already be the about so try this for your success handler:
success: function(e)
var valEmails = e.valid_emails,
invalEmails = e.invalid_emails;
};
Just try including
dataType: 'json',

Categories