Correct spelling in ajax POST - ajax

I have two verions of code I believe should do the same thing, but the first one works and other one doesn't (Post vars: agenti, week_, team_). I have searched for few examples of how to do it the other way and I am sure my example is similar.
What do I do wrong?
First:
$.post("index.html",
{
agenti: getItems(),
week_: week_array,
team_: team
},
function(data,status){
if (status = 'Success'){
alert('Aktuální řazení operátorů bylo úspěšně uloženo.');
} else {
alert('Aktuální řazení operátorů se nepodařilo uložit.\nKontaktujte prosím správce aplikace.');
}
Second:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "index.html",
data: JSON.stringify({agenti: getItems(), week_: week_array, team_: team}),
success: function (msg)
{
alert('Aktuální řazení operátorů bylo úspěšně uloženo.')
},
error: function (msg)
{
alert('Aktuální řazení operátorů se nepodařilo uložit.\nKontaktujte prosím správce aplikace.')
}
});
I want to do the second one because I need to specify content type and i couldn't figure how to do it in the first way.
Thanks you!
edit: I use IE; this code will be used only in IE.

so the first thing is that, no need to use JSON.stringify function, as the data accepts JSON objects, as well the string represented like a url (test1=1&test2=2...). So to use it like the following is ok.
data: {agenti: getItems(), week_: week_array, team_: team},
Also when you are using contentType: 'application/json' the GLOBAL $_POST variable is not being populated as it is being populated only for form-urlencoded data which is default value for contentType option, here you go with data from jQuery reference`
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
In order you like to use application/json, you can retrieve that information in PHP side using php input like this following. file_get_contents('php://input');
---Working Example---
Javascript:
$.ajax({
type: "POST",
// contentType: "application/json; charset=utf-8",
dataType: "json",
url: "http://localhost",
data: {agenti: 'test1', week_: 'test2', team_: 'test3'},
success: function(msg) {},
error: function(msg) {}
});
PHP:
// Retrieve the input
var_dump(file_get_contents('php://input'));
// Use $_POST var
echo json_encode($_POST);

Related

ASP.NET Core FromBody is null on AJAX POST but populates in Postman

I'm trying to perform an AJAX post but I keep getting a null FromBody in my .NET controller. I think it has to do with how I'm formatting my AJAX post.
When I attempt to post with AJAX I get a null FromBody.
var data = {
Date: "2016-12-01",
BurnIdx: 23,
BurnStatIdx1: 3,
BurnStatIdx2: 3,
BurnStatIdx3: 3,
BurnSevIdx: 5,
WorkOrder: 32426,
Comment: "Hi"
};
$('#submit').on('click',function () {
$.ajax({
type: 'POST',
url: 'Home/BurnerMapUpdate',
dataType: 'json',
contentType: 'application/json',
data: data,
success: function (result) {
console.log('Data received');
console.log(result);
}
});
});
However, when I attempt a post in Postman it's successful.
Figured out my problem. Needed to use JSON.stringify on my data.
$('#submit').on('click',function () {
$.ajax({
type: 'POST',
url: 'Home/BurnerMapUpdate',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(data),
success: function (result) {
console.log('Data received');
console.log(result);
}
});
Not only the JSON.stringify().
If your data don't match with csharp class data it doesn't receive anything.
Like if you define in the class a field with int type, and send it in the json like "1", it happens to receive the whole data as null
I know you are already figured out of this problem. But I faced with the same just right now. My mistake was I used BODY parameter instead DATA in ajax request.
My Invalid ajax:
function sendRequest(url, method, body, callbackOk, callbackFail) {
$.ajax({
url: url,
body: JSON.stringify(body),
method: method,
contentType: 'application/json; charset=utf-8',
success: callbackOk,
error: callbackFail
})
Valid:
function sendRequest(url, method, body, callbackOk, callbackFail) {
$.ajax({
url: url,
data: JSON.stringify(body),
method: method,
contentType: 'application/json; charset=utf-8',
success: callbackOk,
error: callbackFail
})
}

Ajax request - xml/json

Studying for an exam and came across the following practice question.
You develop a web application by using jQuery. You develop the following jQuery code:
$(document).ready(function () {
$('#submit').click(function () {
$.ajax({
//INSERT CODE
data: $('#myForm').serialize(),
success: function (result) {
$('#result').text(result.message);
}
});
})
})
The web application exposes a RESTful web api that has an endpoint of product/create. You need to create a new product by using AJAX.
Which code segment should you insert at line 04?
//Option A:
type: "POST",
dataType: "xml",
contentType: "application/x-www-urlencoded; charset=UTF-8",
url: ".product/create",
//OPTION B:
type: "POST",
dataType: "json",
url: ".product/create",
Could someone explain why option B is correct?
I understand that it should be a post request since a new product is being created. Datatype could be either json or xml. Content-type is optional. Is it because result.message can only work when a json is passed in?
For the datatype:"xml", The contenttype is not valid in Option A. The valid options for XMLs are: text/xml, application/xml.
But, Option B has valid entries.
The corrected option A is below,
//Option A:
type: "POST",
dataType: "xml",
contentType: "application/xml; charset=UTF-8",
url: ".product/create",

jQuery send string as POST parameters

I want to send a string as an ajax Post parameter.
The following code:
$.ajax({
type: "POST",
url: "http://nakolesah.ru/",
data: 'foo=bar&ca$libri=no$libri',
success: function(msg){
alert('wow'+msg);
}
});
Is not working. Why?
Try like this:
$.ajax({
type: 'POST',
// make sure you respect the same origin policy with this url:
// http://en.wikipedia.org/wiki/Same_origin_policy
url: 'http://nakolesah.ru/',
data: {
'foo': 'bar',
'ca$libri': 'no$libri' // <-- the $ sign in the parameter name seems unusual, I would avoid it
},
success: function(msg){
alert('wow' + msg);
}
});
$.ajax({
type: 'POST',
url:'http://nakolesah.ru/',
data:'foo='+ bar+'&calibri='+ nolibri,
success: function(msg){
alert('wow' + msg);
}
});
I see that they did not understand your question.
Answer is: add "traditional" parameter to your ajax call like this:
$.ajax({
traditional: true,
type: "POST",
url: url,
data: custom,
success: ok,
dataType: "json"
});
And it will work with parameters PASSED AS A STRING.
For a similar application I had to wrap my data object with JSON.stringify() like this:
data: JSON.stringify({
'foo': 'bar',
'ca$libri': 'no$libri'
}),
The API was working with a REST client but couldn't get it to function with jquery ajax in the browser. stringify was the solution.
Not sure whether this is still actual.. just for future readers.
If what you really want is to pass your parameters as part of the URL, you should probably use jQuery.param().
Not a direct answer to your question.. But following is the only syntax that used to work for me -
data: '{"winNumber": "' + win + '"}',
And the parameter-name match with the argument of the server method
I was facing the problem in passing string value to string parameters in Ajax. After so much googling, i have come up with a custom solution as below.
var bar = 'xyz';
var calibri = 'no$libri';
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "http://nakolesah.ru/",
data: '{ foo: \'' + bar + '\', zoo: \'' + calibri + '\'}',
success: function(msg){
alert('wow'+msg);
},
});
Here, bar and calibri are two string variables and you can pass whatever string value to respective string parameters in web method.
I have also faced this exact problem. But I have got a solution and it worked perfectly. I have needed to pass the parameters which are already produced by javascript function. So below code is working for me. I used ColdFusion for the backend. I just directly used the parameters as a variable.
$.ajax({
url: "https://myexampleurl.com/myactionfile.cfm",
type: "POST",
data : {paramert1: variable1,parameter2: variable2},
success: function(data){
console.log(data);
} )};
Instead of this, encode the POST request as a string and pass to the data parameter,
var requestData = "Param1=" + encodeURIComponent(jsParam1) + "&Param2="+ encodeURIComponent(jsParam2);
var request = $.ajax({
url: page + "?" + getVars,
method: "POST",
data: requestData,
dataType: "html",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
});

jQuery.ajax returns 400 Bad Request

This works fine:
jQuery('#my_get_related_keywords').click(function() {
if (jQuery('#my_keyword').val() == '') return false;
jQuery.getJSON("http://boss.yahooapis.com/ysearch/web/v1/"
+jQuery('#my_keyword').val()+"?"
+"appid=myAppID"
+"&lang=en"
+"&format=json"
+"&count=50"
+"&view=keyterms"
+"&callback=?",
function (data) {//do something}
This returns 400 Bad Request (Just a reformulation of the above jQuery using .ajax to support error handling).
jQuery('#my_get_related_keywords').click(function()
{
if (jQuery('#my_keyword').val() == '') return false;
jQuery('#my_loader').show();
jQuery.ajax(
{
url: "http://boss.yahooapis.com/ysearch/web/v1/"
+jQuery('#my_keyword').val()+"?"
+"appid=myAppID"
+"&lang=en"
+"&format=json"
+"&count=50"
+"&view=keyterms"
+"&callback=?",
success: function(data)
{//do something}
I think you just need to add 2 more options (contentType and dataType):
$('#my_get_related_keywords').click(function() {
$.ajax({
type: "POST",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8", // this
dataType: "json", // and this
success: function (msg) {
//do something
},
error: function (errormessage) {
//do something else
}
});
}
Add this to your ajax call:
contentType: "application/json; charset=utf-8",
dataType: "json"
Late answer, but I figured it's worth keeping this updated. Expanding on Andrea Turri answer to reflect updated jQuery API and .success/.error deprecated methods.
As of jQuery 1.8.* the preferred way of doing this is to use .done() and .fail(). Jquery Docs
e.g.
$('#my_get_related_keywords').click(function() {
var ajaxRequest = $.ajax({
type: "POST",
url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
contentType: "application/json; charset=utf-8",
dataType: "json"});
//When the request successfully finished, execute passed in function
ajaxRequest.done(function(msg){
//do something
});
//When the request failed, execute the passed in function
ajaxRequest.fail(function(jqXHR, status){
//do something else
});
});
Be sure and use 'get' or 'post' consistantly with your $.ajax call for example.
$.ajax({
type: 'get',
must be met with
app.get('/', function(req, res) {
===============
and for post
$.ajax({
type: 'post',
must be met with
app.post('/', function(req, res) {
I was getting the 400 Bad Request error, even after setting:
contentType: "application/json",
dataType: "json"
The issue was with the type of a property passed in the json object, for the data property in the ajax request object.
To figure out the issue, I added an error handler and then logged the error to the console. Console log will clearly show validation errors for the properties if any.
This was my initial code:
var data = {
"TestId": testId,
"PlayerId": parseInt(playerId),
"Result": result
};
var url = document.location.protocol + "//" + document.location.host + "/api/tests"
$.ajax({
url: url,
method: "POST",
contentType: "application/json",
data: JSON.stringify(data), // issue with a property type in the data object
dataType: "json",
error: function (e) {
console.log(e); // logging the error object to console
},
success: function () {
console.log('Success saving test result');
}
});
Now after making the request, I checked the console tab in the browser development tool.
It looked like this:
responseJSON.errors[0] clearly shows a validation error: The JSON value could not be converted to System.String. Path: $.TestId, which means I have to convert TestId to a string in the data object, before making the request.
Changing the data object creation like below fixed the issue for me:
var data = {
"TestId": String(testId), //converting testId to a string
"PlayerId": parseInt(playerId),
"Result": result
};
I assume other possible errors could also be identified by logging and inspecting the error object.
Your AJAX call is not completed with the following two params.
contentType: "application/json; charset=utf-8",
dataType: "json"
contentType is the type of data you're sending
dataType is what you're expecting back from the server
In addition try to use JSON.stringify() method. It is used to turn a javascript object into json string.

$.ajax is not working

In my web page there is a textbox to get the scanned barcode value. Once we scan the barcode it has to get details from the database. I am creating the change event for the textbox.
Problem: $.ajax is not working.
Code:
var target = $('#txtBarcode'), val = target.val();
target.change(monitor());
function monitor() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
url: "HomePage.aspx/SearchProduct",
dataType: "json",
success: function(data) {
alert("Success!!!");
}
});
}
You are trying to pass 'monitor' to the change method but you're actually calling it. It should look like this (no parens)
var target = $('#txtBarcode'), val = target.val();
target.change(monitor);
function monitor() {
You can always declare it inline too:
var target = $('#txtBarcode'), val = target.val();
target.change(
function() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
url: "HomePage.aspx/SearchProduct",
dataType: "json",
success: function(data) {
alert("Success!!!");
}
});
});
Add an error handler.
Make sure your relative URL is right.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
url: "HomePage.aspx/SearchProduct",
dataType: "json",
success: function(data) {
alert("Success!!!");
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
// ...
}
});
EDIT: Dan is right about your change handler.
You can copy some answers posted here, and at least one of will likely to work, but you won't get the intimate knowledge of why. Here's an additional way:
Since you use asp.net, put the break point in the first line of HomePage.aspx/SearchProduct. This ensure that the request goes to the right URL on the server.
Step all the way through this method to make sure there's no exception that gets thrown.
Use FireFox and install Firebug (even if you target IE and have no intention to make it run on FF). You can inspect the http response.
Add an error handler in addition to the success handler.

Resources