Ajax Post not sending data Correctly - ajax

VB.net, MVC4, asp.net views.
I would like to know why I cannot send or what I am doing wrong sending a parameter(int), parameter(model).
data:
var ID = '<%: Model.ID%>';
var data = $('#dlg').find('form').serialize();
Ajax Post:
$.ajax({
url: '<%: Url.Action("EST", "Now")%>',
type: 'POST',
data: { id: ID, model: data },
success: function (rData) {
$('#divE').html(rData);
}
});
Now - Controller:
<HttpPost> _
Function EST(id As Integer, model As EViewModel) As ActionResult
So I'm passing a modelID and the forms data, sending them separately( with modifications ) both work, but sending them together it seems to null the 2nd parameter. Found by debugging the action.

try use JSON.stringify.
Include contentType: "application/json; charset=utf-8", when you omit the contentType value default is 'application/x-www-form-urlencoded; charset=UTF-8' this could become a trouble when you will post data
$.ajax({
url: '<%: Url.Action("EST", "Now")%>',
type: 'POST',
data: JSON.stringify({ id: ID, model: data }) ,
contentType: "application/json; charset=utf-8",
success: function (rData) {
$('#divE').html(rData);
}
});

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

How to Display Json Data when ajax request is success

Here I am using Ajax+Mvc when I call my data from database it comes in Json format but how can I display that data in div?
Html
<div id="Div1">
</div>
<b>Get data</b><input type="button" id="BtnGetData" value="GetData" />
When user click on BtnGetData the data should be display in #Div1 Here my AJax working fine.But please suggest me where to write $('#Div1').load();
$('#BtnGetData').click(function () {
alert('ok data')
$.ajax({
url: '/Home/Getdata',
method: "GET",
type: "JSON",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(),
})
})
MvcController
public JsonResult Getdata()
{
var x = Objrepo.GetEmplo();
return new JsonResult { Data = x, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
You can write to the div on the success function of your $.ajax call.
eg:
$('#BtnGetData').click(function () {
$.ajax({
url: '/Home/Getdata',
method: "GET",
type: "JSON",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(),
success: function (data) {
console.log(data);
}
})
});
You need to add a success callback to your ajax:
$('#BtnGetData').click(function () {
alert('ok data')
$.ajax({
url: '/Home/Getdata',
method: "GET",
type: "JSON",
contentType: 'application/json; charset=utf-8',
success: function(data){
$("#Div1").append(data);
}
})
})
There is no need to add the data property to the ajax if your are not sending anything.
May be, you can add this function in your script.
$('#BtnGetData').click(function () {
alert('ok data')
$.ajax({
url: '/Home/Getdata',
method: "GET",
type: "JSON",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(),
writeResponse(data)
})
});
writeResponse(data){
$("Div1").html(data);
};

Instagram API for posting to relationship not working

I have tried for a day now so I will post - does anyone know why the following code for posting follow relationship using Instagram API wont work?
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: 'https://api.instagram.com/v1/users/<user-id>/relationship?access_token=' + instagramaccesstoken,
data: JSON.stringify({ "action": "unfollow" }),
dataType: "jsonp",
cache: false,
beforeSend: function () {
$("#loading").show();
},
success: function (data) {
alert(data);
$("#loading").hide();
}
});
If you replace the <user-id> placeholder in your URL with a real user ID, then it will work.

Correct spelling in ajax POST

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

Send FormData and String Data Together Through JQuery AJAX

I have the below that uploads an image using JQuery's AJAX function
var id = <?php echo $id; ?>;
var img_data = new FormData($("form")[0]);
$.ajax({
url: 'add.php',
data: img_data,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
I'd like to include a string with the FormData sent. I tried the following, but no luck
data: img_data {id: id},
What's the correct syntax here?
Use append
var img_data = new FormData($("form")[0]);
img_data.append('id', id);
You could create a JSON data object and pass that as application/json and process the data within add.php:
var data = {
id : <?php echo !empty($id) ? $id : "''",
img_data : new FormData($("form")[0])
};
$.ajax({
url: 'add.php',
data: data,
contentType: "application/json",
type: 'POST',
success: function(data){
alert(data);
}
});
Although unconventional, you could also append the data as a query string to the URL with the POST. You'd also need to edit add.php to get this parameter.
$.ajax({
url: 'add.php?id=' + id,
data: img_data,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});

Resources