POST request ajax jquery error - javascript

I am trying to run post request to parse json format data into the page. An example query is:
$("#click").click(function () {
$.ajax({
type: "POST",
url: "http://ut-pc-236:9000/kanye/flow/search",
contentType: "application/json;charset=UTF-8",
data: {
"fromDate":"2011-01-01",
"toDate":"2011-03-16T14:35:00Z",
"limitTotalFlows":1000,
"operator":"AND",
"keyValues":[ "J0419:E", "J0410:AMPY", "J1043:BEDFORD" ]
},
success: function (data) {
console.log(data);
}
});
});
but it gives an error - bad request (400). I guess it should be some syntax error since the get method works ok. If anyone can help I would really appreciate it. Thanks

You're not sending a valid json object as you claim to be doing with the contentType.
JSON.stringify your data:
data: JSON.stringify({
"fromDate":"2011-01-01",
"toDate":"2011-03-16T14:35:00Z",
"limitTotalFlows":1000,
"operator":"AND",
"keyValues":[ "J0419:E", "J0410:AMPY", "J1043:BEDFORD" ]
}),

Related

Undefined index Jquery Ajax POST

I have this small but annoying problem. I really not usual with a web thing. I try to request to my php file using ajax jquery. When I want to retrieve the data I send from ajax, it return undefined index. I dunno what's the problem, it make me spend a lot of time to solve it. Thanks
Below is my ajax code
var at=this.name.substring(this.name.length,7);
var value_header = $("#key"+at).val();
var jsObj = { new_value:value_header, id:at, data:'header'};
console.log(JSON.stringify(jsObj));
$.ajax({
type: 'POST',
headers: 'application/urlformencoded',
url: 'admin_crud.php',
data: jsObj,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
console.log("Sukses");
}
When I call the below code in my php file, the result is 'Undefined index: data'
echo $_POST['data'];
//Edit
So, when I try var_dump($_POST);, the result is array(0) {}. Where is my mistake? I thought I had send the right one
//Edit
As I mention above, I want it to run perfect without error. Thanks
Remove headers, change your datatype to text and catch errors in the ajax call
$.ajax({
type: "POST",
dataType: "text",
data: jsObj,
url: "admin_crud.php",
success: function (result) {
console.log("success", result);
},
error: function (e) {
console.log("Unsuccessful:", e);
}
});
I have another solution beside #Marco Sanchez too, I don't know it always work or not, but in my case, it work :
$.ajax({
type: 'POST',
url: 'admin_crud.php',
headers: "Content-type: application/x-www-form-urlencoded"
data: "new_value="+value_header+"&id="+at+"&data=header",
success: function(data){
console.log("Sukses");
console.log(data);
}
});

Ajax POST error (400 BAD REQUEST)

and thank you in advance for helping me.
I'm trying to make a POST where I pass the TOKEN in the URL and I want to pass another param too so I can save the info in the DB. I have this:
$("#btnAddCompany").click(function(e) {
var token = "123";
var companyValue = document.getElementById("companyValue").value;
var obj ={CompanyId: 4 ,Name: companyValue }
var postData = JSON.stringify(obj);
console.log(postData);
$.ajax({
type: "POST", //REQUEST TYPE
dataType: "json", //RESPONSE TYPE
contentType: "application/json",
data: postData,
url: "http://banametric.ddns.net/BanaMetricWebServices/BanaSov_WS.svc/CompanySave/"+token,
success: function(data) {
toastr.success("Lidl Adicionado!");
},
error: function(err) {
console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
}
}).always(function(jqXHR, textStatus) {
if (textStatus != "success") {
alert("Error: " + jqXHR.statusText);
}
})
});
But I'm getting an 400 error (Bad Request) so I assume that I'm making something wrong, but I don't find out what. The error trace is this:
AJAX error in request: { "readyState": 4, "responseText": "\r\n
The server encountered an error processing the request. The
exception message is 'The incoming message has an unexpected message
format 'Raw'. The expected message formats for the operation are
'Xml', 'Json'. This can be because a WebContentTypeMapper has not been
configured on the binding. See server logs for more
details. The exception stack trace is: \r\n at
System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message
message, Object[] parameters)\r\n at
It's error because of
The expected message formats for the operation are 'Xml', 'Json'.
So you can pass contentType in your ajax call
$.ajax({
....,
contentType: "application/json"
})
I am not sure, but it depends on what server wants to read from you.
Server does not want to read raw bytes, it wants xml or json
Try to add headers like
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
in $.ajax() function
You need to set the content type header in your request to inform the server you're sending the data as JSON.
The error message is telling you that the server does not understand the content you're sending it - you have to give it a hint that the data is in a particular format, especially because, again as mentioned in the error message, it allows you to submit in more than one different format (JSON or XML in this case).
Adding
contentType: "application/json"
to the options in your $.ajax call should resolve the issue.
P.S. We can't see the signature of your controller method but it's possible you may also need to give your parameter a name within the JSON, e.g. something like data: JSON.stringify({ "companyValue": postData }); , but there's not enough info in your question to say for certain what the correct structure should be.
$("body").on("submit", ".example_form", function() {
$.ajax({
url: 'http://example.com/{ROUTE_URL}',
data: new FormData(this),
processData: false,
contentType: false,
/* OR contentType: "application/json; charset=utf-8"*/
type: 'POST',
dataType: "json",
success: function(data) {
console.log(data);
}
});
});
Instead of this
var postData = JSON.stringify(companyValue);
why don't you try this:
var obj ={token :token ,companyValue:companyValue }
And then make use of the json stringify function
var postData = JSON.stringify(obj);
After that in ajax call only change the url:
url: "http://webservice/CompanySave/"

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.

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].

500 (Internal Server Error)

function update(){
var data = $form_value;
$.ajax({
url: "https://api.knackhq.com/v1/scenes/scene_93/views/view_848/records/542bdc7a1e953ed90509aeab",
type: "PUT",
headers: {"X-Knack-Application-Id": "", "X-Knack-REST-API-Key":""},
data: data,
success: function(response) {
alert('Record created');
console.log($form_value);
}
});
}
I am not sure why I am getting Internal server 500 error, url seams to be corect because it works with GET.
500 means there is a problem internal to the server. There's nothing you can do about that other than contact the people who run it and ask whats going on.
I think type: "POST" instead of type: "GET" should work for you

Categories

Resources