Request payload is [Object Object] in the AJAX post request triggered - javascript

I am sending a ajax request with the following data. The data here is an object and I intend to send an object itself (not stringified JSON). But when I see the request in browser, the request payload is displayed as [object object] even though I am sending a project JS object.
let emailIdForAPICall = { "email": "abc#gmail.com"};
$.ajax({
type: 'POST',
url: gigyaServlet,
data: {
'profile': emailIdForAPICall,
}
})
Once the above API call is triggered, the payload looks like below -
Tried using JSON.parse(JSON.stringify(emailIdForAPICall)) but it still did not work.
Whats worrying is, same type of request works a different site properly.

let emailIdForAPICall = {
"email": "abc#gmail.com"
};
$.ajax({
type: 'POST',
url: gigyaServlet,
data: JSON.stringify({ //stringify your obj
'profile': emailIdForAPICall,
}),
contentType: 'application/json', // add contentType
})

Ramya Shivu your request is from data or JSON. if JSON then please pass contentType: 'application/json',in header & if it is form data
let emailIdForAPICall = { "email": "abc#gmail.com"};
$.ajax({
type: 'POST',
url: gigyaServlet,
data: JSON.stringify({ //stringify your obj
'profile': emailIdForAPICall,
})
})

Related

Jquery ajax call wrong payload

I have some troubles whit jquery ajax call, infact I tried to perform a post call passing like data a string variable:
myVar = 'Hello';
$.ajax(
type: 'POST',
url : 'https://...',
data: myVar,
success : function(data) {
},
complite: function() {...},
error: function(err) {...}
)
If I inspect the http call I can see that the payload is:
'Hello': ""
I don't know how it is possible and how fix the problem.
jQuery, by default, will put a Content-Type: application/x-www-form-urlencoded header on data it sends via Ajax.
You, however, are passing a plain text string.
You need to either change the Content-Type to match the data you are sending or the data you are sending to match the Content-Type. (Or you could change both).
The important things are:
The data and content-type need to match
The server needs to be able to handle data in the format you are sending
So you might:
$.ajax({
type: 'POST',
url : 'https://...',
data: myVar,
contentType: 'text/plain'
// ...
})
or, since jQuery will encode objects as URL encoded data:
$.ajax({
type: 'POST',
url : 'https://...',
data: { myVar },
// ...
})
or, if you want multipart data:
const data = new FormData();
data.append('myVar', myVar);
$.ajax({
type: 'POST',
url : 'https://...',
data,
contentType: false // XHR will read the content-type from the FormData object (which it needs to do in order to determine the boundary paramater), putting 'false' here stops jQuery overriding it
// ...
})
or, for JSON
$.ajax({
type: 'POST',
url : 'https://...',
data: JSON.stringify(myVar), // This will be a JSON text representing a string
contentType: 'application/json'
// ...
})
i think you are passing payload in the wrong formate.
myVar = 'Hello';
$.ajax(
type: 'POST',
url : 'https://...',
data: {
'name':myVar
},
success : function(data) {
},
complite: function() {...},
error: function(err) {...}
)
On the server side you will get the value in the key 'name' you can fetch the value using 'name' key.

error: AJAX call within AJAX response

I am working with a file to interact with an API. First the API sends some HTML and Javascript to create a search form, then the API can process the query of that search form.
I am having some problems with my second request, which is called within the success function of the first request (this seems to be the problem!). Here's the code I'm working with.
$.ajax({
type: "POST",
url: "https://vq3rsgkd94.execute-api.us-east-1.amazonaws.com/deploy",
crossDomain: true,
data: JSON.stringify({
"stage": "load",
"fields": ["first_name", "last_name", "graduation_year"]
}),
success: function(response) {
response = JSON.parse(response);
$(response.html).prependTo("#content");
$(response.scripts).appendTo("body");
},
complete: function() {
//get field inputs
var fieldInput = {
"first_name_query": "",
"last_name_query": "",
"graduation_year_query": ""
};
$('form').find('input[type=search]').each(function(index, value) {
var variableName = value.name;
var fieldId = "#" + value.name;
$(fieldId).keyup(function() {
variableName = $(this).val();
fieldInput[value.name + "_query"] = variableName
console.log(value.name + ":" + fieldInput[value.name + "_query"]);
})
.keyup();
});
$('#search_form').submit(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "https://vq3rsgkd94.execute-api.us-east-1.amazonaws.com/deploy",
data: JSON.stringify({
"stage": "search",
"fields": ["first_name", "last_name", "graduation_year"],
"query": {
"first_name": fieldInput["first_name_query"]
}
}),
success: function(response) {
response = JSON.parse(response);
console.log(response);
}
});
})
}
});
When trying to parse the response, I get unexpected token: o. If I run this code outside of the first ajax request like this:
$.ajax({
type: "POST",
url: "https://vq3rsgkd94.execute-api.us-east-1.amazonaws.com/deploy",
data: JSON.stringify({
"stage": "search",
"fields": ["first_name", "last_name", "graduation_year"],
"query": {
"first_name": "Bob"
}
}),
success: function(response) {
response = JSON.parse(response);
console.log(response);
}
});
I don't have any problem and the code executes normally. So the problem seems to be running one Ajax call inside another's success response, but I don't know why? I can probably do things another way instead, but wanted to see if anyone had some insight into why this doesn't work.
The error you are getting suggests that you are trying to parse an object with JSON.parse
since
var x = {}
console.log(x.toString()) //> [object Object]
JSON.parse(x)
// Uncaught SyntaxError: Unexpected token o in JSON at position 1
// at JSON.parse (<anonymous>)
// at <anonymous>:3:6
Are you sure that response is a string in the second case
Instead of explicitly converting the JSON allow jquery to parse it for you with dataType: 'json'
$.ajax({
type: "POST",
url: "https://vq3rsgkd94.execute-api.us-east-1.amazonaws.com/deploy",
data: JSON.stringify({
"stage":"search",
"fields":["first_name","last_name","graduation_year"],
"query":{"first_name": fieldInput["first_name_query"] }
}),
dataType: 'json'
)}
So the problem ended up being pretty strange. I'm developing an API for Nationbuilder platform (maybe my first mistake). For unknown reasons, Nationbuilder was appending a authenticity token to any request made, which my LAMBDA based API couldn't parse. Just in case anyone else is in the same very tiny boat as I was, I ended up using GET requests instead of POST requests and Nationbuilder stopped appending the authenticity token.
Also, if anyone is using Lambda, I ended up switching to Digital Ocean hosted Express JS and am much happier.

jQuery - AJAX Request

I am working on an app that sends a POST request to a web service. My POST request looks like this:
$.ajax({
type: 'POST', url: getEntityUrl(), cache: 'false',
contentType:'application/json',
headers: {
'api-key':'myKeyHere',
'Content-Type':'application/json'
},
data: {
firstName:'Jon',
lastName:'Smith'
},
success: function() { alert('good job'); },
error: function() { alert('oops'); }
});
When I execute this, I'm getting a 400 Bad Request. I watched the request in Fiddler. I noticed that the parameters I sent are being sent as "firstName=Jon&lastName=Smith". However, they need to be sent across as JSON like I have them defined in the data parameter. I confirmed this is the problem by modifying the request in the composer in Fiddler. What am I doing wrong?
Thanks
If you pass jQuery a plain object through the data parameter (as you do here) then it will encode the data as application/x-www-form-urlencoded.
Just setting the contentType is insufficient.
If you want to send JSON then you must encode it yourself. You can use JSON.stringify for that.
data: JSON.stringify({
firstName:'Jon',
lastName:'Smith'
}),
You need to stringify the data like following.
$.ajax({
type: 'POST',
url: getEntityUrl(),
contentType: 'application/json',
headers: {
'api-key': 'myKeyHere',
'Content-Type': 'application/json'
},
data: JSON.stringify({ firstName: 'Jon', lastName: 'Smith' }), //change here
success: function () { alert('good job'); },
error: function () { alert('oops'); }
});

Invalid Json Primitive on Ajax Post

I am posting my form using AJAX:
$(function () {
$("#Compare").click(function (e) {
$.ajax({
url: '#Url.Action("_Compare","API")',
dataType: 'application/json',
data: {
model: $("#CompareForm").serialize()
},
type: "post",
success: function(response) {
alert (response);
}
});
e.preventDefault();
});
});
I am trying to deserialize my JSON result but I am getting an 'Invalid Json Primitive Exception'.
My Json Result:
"%5B0%5D.Id=1&%5B0%5D.Description=Sutherland+Silver+Plans+offers+you...&%5B0%5D.Price=30&%5B0%5D.Title=Silver+Plan&%5B0%5D.isSelected=true&%5B0%5D.isSelected=false&%5B1%5D.Id=2&%5B1%5D.Description=Sutherland+Gold+Plans+offers+you...&%5B1%5D.Price=50&%5B1%5D.Title=Gold+Plan&%5B1%5D.isSelected=true&%5B1%5D.isSelected=false&%5B2%5D.Id=3&%5B2%5D.Description=Sutherland+Platinum+Plans+offers+you...&%5B2%5D.Price=80&%5B2%5D.Title=Platinum+Plan&%5B2%5D.isSelected=false"
You seem confused about what JSON is, and whether the issue is with the request or the response.
The issue is with the request. You are attempting to put the querystring that serialize() creates in to the model parameter of an object, which itself will be serialised and encoded again. Instead, just pass the querystring that serialise generates to the action:
$("#Compare").click(function (e) {
$.ajax({
url: '#Url.Action("_Compare","API")',
dataType: 'application/json',
data: $("#CompareForm").serialize(),
type: "post",
success: function(response) {
console.log(response);
}
});
e.preventDefault();
});
You have specified the response will be JSON. If this is the case, use console.log to inspect it, otherwise the alert() will only show [object Object].

Trying to send a POST request and get json data but getting 400

I'm trying to send an ajax POST request and I've set the content type to be application/json etc. But in the backend I keep getting 400 (BAD REQUEST). What's wrong with the code?
var data = {key0: 'val0', key1: 'val1'};
$.ajax({
type: "POST",
url: 'http://localhost:8000/api/users',
data: data,
success: function(data) {
console.log(data);
},
contentType: 'application/json',
dataType: 'json'
});
Flask:
#usersapi.route('/api/users', methods=['POST'])
def create_user():
#raise Exception(request.headers.get('Content-Type'))
d = dict(request.get_json())
You aren't sending JSON.
You've passed data an object, so it is being serialised as form data.
You need to explicitly convert it to JSON:
data: JSON.stringify(data),

Categories

Resources