I'm doing a simple post of a form using jquery. The problem is the $.ajax with POST is working but $.post is not. Look at the code below:
$.post(
{
url: url,
data: form.serialize(),
success: function (result) {
alert('startline posted');
}
});
And the working edition
$.ajax(
{
url: url,
type: "POST",
data: form.serialize(),
success: function (result) {
alert('startline posted');
},
error: function (jqXhr, textStatus, errorThrown) {
alert("Error '" + jqXhr.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')");
}
});
Been debugging the $.post example until I just wanted to try out the $.ajax edition to get an error msg. But unfortunatly it just worked :)
How are the two methods different?
The parameter format for jQuery.post is url, data, callback, datatype. The parameter for jQuery.ajax is url, options or just options as you are using. In other words, the formatting on your $.post call is incorrect.
$.post( url, form.serialize())
.success( function (result) {
alert('startline posted');
});
try it
$.post takes multiple arguments, not one object like $.ajax. try it like this:
$.post(url, form.serialize(), function (result) {
alert('startline posted');
});
That's not how you use $.post
$.post('url/here.php', {
data: form.serialize()
}, function(result) {
alert('startline posted');
});
Related
var jso = { "namep": "a", "age": "10" };
$.ajax({
type: 'POST',
url: '#Url.Action("gettestjsn","Cart")',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(jso),
success: function (data) {
alert(data.namep);
},
error: function () { alert("err"); }
});
this code always go to error function and i does not fire my mvc action,aslo i have a prop class which does match to this json obj. why is that i m new to json and jquery ajax please help
this is my action
public ActionResult gettestjsn(jso jso)
{
//do some here
return View();
}
Remove contentType from the ajax attributes and add
dataType: 'json',
This will work if the url is correct
this is how your code should look like
var jso = { "namep": "a", "age": "10" };
$.ajax({
type: 'POST',
url: '#Url.Action("gettestjsn","Cart")',
data: jso,
success: function (data) {
alert(data.namep);
},
error: function () { alert("err"); }
});
Also i would refrain from using alerts. Either use console.log or debug using the inspector in your browser (comes inbuilt with chrome) to see what your data from the server looks like.
Try like this,
var jso = { "namep": "a", "age": "10" };
$.ajax({
type: 'POST',
url: '/Cart/gettestjsn',
contentType: 'application/json; charset=utf-8',
data: jso,
success: function (data) {
alert(data.namep);
},
error: function (jqxhr, status, error) { alert("err:" + status + ':' + error); }
});
and your action should be,
[HttpPost]
public ActionResult gettestjsn(jso jso)
{
//do some here
return View();
}
Hope it helps.
I have to generate several graphs and each graph data I should get it from mvc controller.
so I am using the below jquery to do ajax calls from jquery to mvc
$(".emailgraphs").each(function () {
YAHOO.Report.Print("Email", $(this).attr("responsefield"), $(this).attr("id"), $(this).attr("metricid"));
});
Print: function (name, graphid, divid, metricid) {
try {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: m_oReport.ds,
data: JSON.stringify(m_oReport.printp(name, graphid, metricid)),
beforeSend: function () {
//Displays loading image before request send, till we get response.
//$("#" + divId).addClass("loading");
},
success: function (data) {
// if they define a success function (s), call it and return data to it.
if (typeof m_oReport.prints === "function") {
m_oReport.prints(data, divid, name)
}
},
error: function (err) {
$("#" + divid).html(err);
}
});
}
catch (err) { alert("catch"); }
}
The problem is the calls are asynchronous. sometimes I am getting one graph and sometime 2 like that and sometimes nothing.
Is there any fix for this?
try to use something like this
function getDataSync() {
return $.ajax({
type: "POST",
url: remote_url,
async: false,
}).responseText;
}
Im trying to use jQuery AutoComplete but all i get is a single item with all results all in it.
I have this ASP.Net WebMethod:
[WebMethod]
public static string FetchCompletionList(string term)
{
var json = JsonConvert.SerializeObject(CustomerProvider.FetchKeys(term, 8));
return json;
}
being called by this script:
$("[id$='txtLKey']").autocomplete({
minlength: 2,
source: function(request, response) {
$.ajax({
type: "POST",
url: "/Views/Crm/Json/Json.aspx/FetchCompletionList",
data: '{term: "' + $("[id$='txtLKey']") .val() + '", count: "8"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
response(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR.responseText);
alert(textStatus);
alert(errorThrown.toString());
}
});
}
});
And the result is this:
When what I actually want is a list of options the user can select i.e. each NZ should be an item in a list.
There are two problems here,
you need to pass data.d to response like response(data.d).
your value string is invalid it should be {"d":["NZ0008","NZ0015","NZ0017","NZ0018","NZ0026","NZ0027","NZ003??1","NZ0035"]}
Below is an Ajax call I'm using to determine which menu options to show to users (I know it's a flawed method, just up against a time crunch for a demo). When the page loads, I can step through the controller method in Visual Studio so I know it's hitting the controller and sending back the right information.
Looking at Chrome's Network console I can also see that the browser received the right response. However, neither the console.log or the alert are firing. Nothing in the success or error methods is executed either. Does anyone see what's going wrong?
View
$(document).ready(function ($) {
//Determine which links to show in navbar
window.onload = function () {
$.ajax({
type: 'GET',
url: '#Url.Action("CheckSecurity","Home")',
dataType: 'json',
succcess: function (data) {
console.log(data);
alert(data);
if (data == "admin") { $('#adminLink').show(); }
else if (data == "IT") { $('#ITLink').show(); }
else if (data == "viewer") { $('#viewerLink').show(); }
else if (data == "modifier") { $('#modifierLink').show(); }
},
error: function (data) {
alert("error");
}
});
};
Controller
[HttpGet]
public JsonResult CheckSecurity()
{
if (Security.IsAdmin(User)) return Json("admin", JsonRequestBehavior.AllowGet);
if (Security.IsItSupport(User)) return Json("IT", JsonRequestBehavior.AllowGet);
if (Security.IsViewer(User)) return Json("viewer", JsonRequestBehavior.AllowGet);
if (Security.IsModifier(User)) return Json("modifier", JsonRequestBehavior.AllowGet);
return Json("NA", JsonRequestBehavior.AllowGet);
}
Here are a couple screen shots of the Network and regular console in Chrome. Bother are from after I've stepped through the controller method and the program has returned a value back to the browser.
Network Console
Standard Console
There is an extra c in your
succcess:
So the response is a 200 request , but because you have no mapping for success defined, it is just never logged
It is success instead of succcess
NealR
Deprecation Notice:
The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks
will be deprecated in jQuery 1.8. To prepare your code for their
eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always()
instead.
Check the done, fail and always callbacks below.
$.ajax({
url: 'Your Url',
data: JSON.stringify(Parameter list),
type: 'POST',
contentType: 'application/json, charset=utf-8',
dataType: 'json',
beforeSend: function (xhr, opts) {
}
}).done(function (data) {
debugger;
}).fail(function (data) {
debugger;
}).always(function(data) {
alert("complete");
});
.ajax().always(function(a, textStatus, b){});
Replaces method .complete() which was deprecated in jQuery 1.8.
In response to successful transaction, arguments are same as .done() (ie. a = data, b = jqXHR) and for failed transactions the arguments are same as .fail() (ie. a = jqXHR, b = errorThrown).
This is an alternative construct for the complete callback function above. Refer to deferred.always() for implementation details.
$.ajax({
url: 'Your Url',
data: JSON.stringify(Parameter list),
type: 'POST',
contentType: 'application/json, charset=utf-8',
dataType: 'json',
beforeSend: function (xhr, opts) {
}
}).always(function(data) {
alert("complete");
});
.ajax().done(function(data, textStatus, jqXHR){});
Replaces method .success() which was deprecated in jQuery 1.8.
This is an alternative construct for the success callback function above. Refer to deferred.done() for implementation details.
$.ajax({
url: 'Your Url',
data: JSON.stringify(Parameter list),
type: 'POST',
contentType: 'application/json, charset=utf-8',
dataType: 'json',
beforeSend: function (xhr, opts) {
}
}).done(function (data) {
debugger;
});
.ajax().fail(function(jqXHR, textStatus, errorThrown){});
Replaces method .error() which was deprecated in jQuery 1.8.
This is an alternative construct for the complete callback function above. Refer to deferred.fail() for implementation details.
$.ajax({
url: 'Your Url',
data: JSON.stringify(Parameter list),
type: 'POST',
contentType: 'application/json, charset=utf-8',
dataType: 'json',
beforeSend: function (xhr, opts) {
}
}).fail(function (data) {
debugger;
});
Check here for more details
Check here for the documentation details
Here's my jquery method:
$.ajax({
type: "GET",
url: "Home/GetSocialMentionBlogs/"
dataType: "json",
success: function (data) {
var obj = JSON.parse(data);
$.each(obj.items, function (i, item) {
$("<strong><p>" + item.title + "</strong></p>").appendTo("#blogs");
if (i == 5) return false;
});
}
});
What I want to do is when a user clicks a button, callt his method, and pass in the value of a textbox so that the URL will now be:
url: Home/GetSocialMentionBlogs/value from text box
Of course I'll need to URL encode that, but as of now, I don't know how to pass in values to this .ajax function.
I'm completely new to jQuery and MVC so pardon my ignorrance ont he subject so far.
Well if the input field has an "id" value you'd just do
url: "Home/GetSocialMentionBlogs/" + $('#inputFieldId').val(),
If all you've got is the name, then you could do:
url: "Home/GetSocialMentionBlogs/" + $('input[name=inputFieldName]').val(),
Is that all you need to do or am I missing some detail?
Oh and to URL encode just use the Javascript encodeURIComponent() function.
$.ajax({
type: "GET",
url: "Home/GetSocialMentionBlogs/" + $('#textBoxID').val(),
dataType: "json",
success: function (data) {
var obj = JSON.parse(data);
$.each(obj.items, function (i, item) {
$("<strong><p>" + item.title + "</strong></p>").appendTo("#blogs");
if (i == 5) return false;
});
}
});