I was facing some problem with AJAX code. I was using MVC3 for our project. My requirement is bind the dropdown value using AJAX when page load. What happens when loading the page, the AJAX request send to the controller properly and return back to the AJAX function and binds the exact values in dropdown. But sometimes (When page refreshed or first time load) its not binding retrieved value. Rather its showing default value. Pls see my code and suggest me where i am doing wrong.
Edit: Even i tried to use async property to false. Its not at all send to the controller action method for getting the data.
Code
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("GetUser", "Invoices")',
data: "{'id':" + JSON.stringify(currval) + "}",
dataType: "json",
async: true,
success: function (data) {
$("#User-" + curr).select2("data", { id: data.Value, Name: data.Text });
$(this).val(data.Value);
}
});
Thanks,
Let's say your Action method is below
public JsonResult hello(int id)
{
return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}
and JQuery should be like below
<script language="javascript" type="text/javascript">
$(document).ready(function () {
var currval = 2;
$.ajax({
url: 'URl',
async: true,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ id: currval }),
success: function (data) {
}
});
});
</script>
You are declaring your data property incorrectly. Try this:
data: { id: currval },
Related
I have this simple ajax method:
$.ajax({
type: 'POST',
url: 'http://localhost:1195/widget/postdata',
datatype: "jsondata",
async: false,
success: function (data) {
alert("ok")
},
error: function (data) {
alert(data.status + ' ' + data.statusText);
}
});
And this simple method in c#:
[HttpPost]
public JsonResult PostData()
{
return Json("1");
}
When I check the inspector console I have "1" in response but my ajax method always goes to error function.
Why is it so?
In your AJAX call it should be dataType: "json" and not datatype: "jsondata". You can refer to the docs
Also use #Url.Action tag in your url call: url: '#Url.Action("postdata", "widget")'
For a small test, I have used the following AJAX call to the same controller method that you have posted and I am getting the correct result:
$(document).ready(function () {
$("#button_1").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url:'#Url.Action("PostData", "Home", null, Request.Url.Scheme)',
datatype: "json",
async: false,
success: function (result) {
alert(result);
},
error: function (error) {
alert(error);
}
});
});
});
</script>
<button id="button_1" value="val_1" name="but1">Check response</button>
Output:
Change the Ajax request to the following :
$.ajax({
type: 'POST',
url: '/widget/postdata',
datatype: "json",
async: false,
success: function (data) {
console.log(data);// to test the response
},
error: function (data) {
alert(data.status + ' ' + data.statusText);
}
});
Always use relative URL instead of full URL that contains the domain name, this will make the deployment easier so you don't have to change the URls when going live
I'm posting data with ajax and it's successfully posted. At the controller side I'm filling a ViewBag with data posted but i'm having a problem getting data from ViewBag.
Here's Ajax Code:
$.ajax({
type: "POST",
url: '../Home/getExistUsersFromJSON',
data: JSON.stringify({ jsonString: JSON.stringify(array) }),
traditional: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function () {
// Alert that it was succesful!
var jsonList = '#Html.Raw(Json.Convert(ViewBag.newUsers))';
var jsList = JSON.parse(jsonList);
bootbox.dialog({
message: jsList,
title: "Utilisateurs",
buttons: {
success: {
label: "Success!",
className: "btn-success"
}
}
});
}
});
And this is the controller side
[ActionName("getExistUsersFromJSON")]
public void getExistUsersFromJSON(string jsonString)
{
IList<newUser> ctm =
new JavaScriptSerializer().Deserialize<IList<newUser>>(jsonString);
ViewBag.newUsers = ctm.ToList();
}
ViewBag is just an object that gets passed to the view when you render the page.
It doesn't make any sense to use that with AJAX; your server-side Razor code runs on initial server render only.
You need to server JSON as the response (using Json()).
I have implemented the following $.Post Jquery function in my asp.net page MAIN Page.aspx
the
$.post({ url: "MAIN Page.aspx",
data: { "Status":ddl },
contentType: "application/json; charset=utf-8",
dataType: "json",
});
where ddl is my data to be posted ...i have placed this $.post in the document.ready() and i tried accessing the posted value in the code behind as
var status= Request.Form.Get["Status"]...
but when i run the code the value of the status is null..
please help and guide if i am correct in my implementation of the logic
Try like this:
$.post('MAIN Page.aspx', { status: ddl }, function(result) {
alert('success');
});
and on your server:
var status= Request.Form["Status"];
Also you haven't shown what this ddl javascript variable is and how you assigned it a value but make sure that it is not a complex object but it contains some simple type.
Alternatively if you want to use the $.ajax method:
$.ajax({
url: 'MAIN Page.aspx',
type: 'POST',
data: { status: ddl },
success: function(result) {
alert('result');
}
});
In my MVC3 app, I'm using $.ajax to call a method of type JsonResult to get data to be displayed:
function GetData(e) {
var ordersId = e.row.cells[0].innerHTML; //this is fine
$.ajax({
type: "POST",
url: "/Documents/GetDocumentData",
contentType: "application/json; charset=utf-8",
data: "{'id': '"+ordersId +"'}",
dataType: "json",
success: function (result) {
//load window
},
error: function (result) {
if (!result.success)
//show error
}
});
This is my Action:
[HttpPost]
public JsonResult GetDocumentData(string id)
{
//my code
return Json(new { success = true});
}
When im debugging on my development machine, it works fine. I deployed it to my test web server and i get '404 page not found dev/testwebsite/Documents/GetDocumentData' I should get this when debugging if something was wrong, but i dont. Why am I getting this error? Thanks
Your URL in the javascript is wrong, if that dev/testwebsite/Documents/GetDocumentData is the URL on the server.
You should be using #Url.Action() to automatically form those URLs in the cshtml page.
Example:
#Url.Action("actionName","controllerName" )
So, for your specific case, it would be:
#Url.Action( "GetDocumentData", "Documents" )
In the javascript, it would look like this:
function GetData(e) {
var ordersId = e.row.cells[0].innerHTML; //this is fine
$.ajax({
type: "POST",
url: '#Url.Action("GetDocumentData","Documents")',
contentType: "application/json; charset=utf-8",
data: "{'id': '"+ordersId +"'}",
dataType: "json",
success: function (result) {
//load window
},
error: function (result) {
if (!result.success)
//show error
}
});
$(function () {
$("#tbNominalAccounts").autocomplete({
source: function (request, response){
$.ajax({
url: "TestPage3.aspx/GetUserNominalAccounts",
type:"POST",
datatype:"json",
data :{ searchText : request.term},
success: function(data)
{
response(
$.map(data, function(item)
{
return { label: item.NominalAccount, value:item.NominalAccount, id:item.NominalAccount}
}))
}
})
}
});
});
Added breakpoints and it hits the ajax call but when i put a breakpoint on the method GetUserNominalAccounts it doesent even reach it!! Any ideas of why its not posting?!
I have a textbox with an ID of #tbNominalAccounts just for background information
Reformat your data like so:
pString = '{"searchText":"' + request.term + '"}';
$.ajax({
data: pString,
...
and your server side code should have been properly "decorated" to allow page access.
Thought I would add some code from a working sample using asp.net: you might need this converter for generic handling of the asp.net data:
dataType: "jsond",
type: "POST",
contentType: "application/json",
converters: {
"json jsond": function(msg)
{
return msg.hasOwnProperty('d') ? msg.d : msg;
}
},
EDIT: And for the use of the return value:
focus: function(event, ui)
{
return false; // return "true" will put the value (label) from the selection in the field used to type
},
try putting a contentType in the ajaxRequest:
contentType: "application/json; charset=utf-8",
I've noticed that when using jQuery Ajax the default content Type application/x-www-form-urlencoded doesn't work well enough.