Post Function in jQuery is not working - asp.net-mvc-3

I am using Ajax function to add product in cart in MVC 3
In Ajax i have a function for adding product, inside that function i want to call a another function but its not working..
My Ajax function is
var AjaxCart = {
addproductvarianttocart: function (urladd, formselector) {
if (this.loadWaiting != false) {
return;
}
this.setLoadWaiting(true);
$.ajax({
cache: false,
url: urladd,
data: $(formselector).serialize(),
type: 'post',
success: this.successprocess,
complete: this.resetLoadWaiting,
error: this.ajaxFailure
});
refreshPage();
},
refreshPage: function () {
$.post('/ShoppingCart/OrderSummaryChild', function (data) {
alert("Inside2");
// Update the ItemList html element
$('#CartUpdatePanel').html(data);
alert("Out");
});
}
};
The link is from where i am calling addproductvarianttocart function
<a onclick="AjaxCart.addproductvarianttocart( '/addproductvarianttocart/25/1/');return false;">

The ajax call is asynchronous. You should put the function refreshPage inside the success or complete function. This way the refreshPage function will be called right after the ajax call is finished and the page is ready to be refreshed with the new data.
Extracted from jQuery api:
Description: Perform an asynchronous HTTP (Ajax) request.

Related

Ajax request, how to call an other function than "success" one's?

I use JQuery Ajax function :
$.ajax({
url: ...,
success: function (){
...
},
...
});
I need to execute some code just before every call of the success function (but after the response has been received).
I suppose that this success function is triggered like an event, so is there a way to make an other function call in place of success one's?
You can use the Global Ajax Event Handlers methods to do this.
Sounds like you might want to use AjaxComplete:
$(document).ajaxComplete(function(){
// do something here when ajax calls complete
});
Be warned -- this will occur for EVERY jQuery ajax call on the page...
You could also call that other function right at the biginning of done:
$.ajax({
url: ...,
done: function (){
someOtherFunction();
},
...
});
This should pretty much accomplish what you described in your question.
Is beforeSend what you are looking for:
$.ajax({
url: "...",
beforeSend: function (x) {
//do something before the the post/get
}
}).done(function (data) {
//done code
});
I succeed in calling an other function just before success one by replacing $.ajax() by a custom function like :
function mYajax(options) {
var temporaryVariable = options.success;
options.success = function () {
console.log('Custom')
if (typeof temporaryVariable === 'function')
temporaryVariable()
};
return $.ajax(options);
}
$('button').click(function () {
mYajax({
url: "/echo/json/",
data: {
foo: "bar"
},
success: function (data, textStatus, jqXHR) {
console.log('succeed action');
},
});
});

Call ajax inside a custom method and return ajax result to called method

in my JSP I have link and button, for both I want to call Ajax action and use with result.
I am creating events for both link and button and calls Ajax. I need to return the result to the calling method.
//event for button
$(document).on('click', ".addComponent", function(){
var htmlContent=$(this).html();
$('.addComponent').html('Loading...').fadeIn();
var urlAction=$(this).attr("id");
var dataFields=$(this).data('val');
var data=callActionUsingAjax(urlAction, dataFields); //data not returning from ajax
var ajaxActionResult=ajaxResult(data);
$('.addComponent').html(htmlContent).fadeIn();
$('#popUpForm').html(ajaxActionResult);
$('#popUpForm').dialog("open");
return false;
});
//event for link
$(document).on('click', "#dimComponentList >TBODY > TR > TD > a", function(){
$("body").css("cursor", "progress");
var urlAction=$(this).attr("href");
var dataFields="";
var data=callActionUsingAjax(urlAction, dataFields);
var ajaxActionResult=ajaxResult(data); //ajax not returning data
$("body").css("cursor", "auto");
$('#applicationList').html(ajaxActionResult);
return false;
});
Here is my method to call Ajax
function callActionUsingAjax(urlAction,datafields)
{
$.ajax({
type: "post",
url: urlAction,
data: datafields,
success: function (data) {
return data;
}
});
}
I tried this link but I don't know how to use call back on my custom method like that. There are some other events also I need to call this Ajax. That's why I used Ajax inside a custom method.
Can anyone give me a solution?
The Ajax call is asynchronous and takes its time to complete, while the execution goes on and that's why you don't have any data in the "return".
You need to pass a callback function to your callActionUsingAjax and call it in your success handler (or complete or error that depends on the logic.
Like this:
$(document).on('click', ".addComponent", function(){
//... other stuff
callActionUsingAjax(urlAction, dataFields, function (data) { //this is tha callback (third argument)
var ajaxActionResult=ajaxResult(data);
$('.addComponent').html(htmlContent).fadeIn();
$('#popUpForm').html(ajaxActionResult);
$('#popUpForm').dialog("open");
// all of the above happens when ajax completes, not immediately.
});
return false;
});
function callActionUsingAjax(urlAction, datafields, callback)
{
$.ajax({
type: "post",
url: urlAction,
data: datafields,
success: function (data) {
callback(data);
}
});
}

Rendering a simple ASP.NET MVC PartialView using JQuery Ajax Post call

I have the following code in my MVC controller:
[HttpPost]
public PartialViewResult GetPartialDiv(int id /* drop down value */)
{
PartyInvites.Models.GuestResponse guestResponse = new PartyInvites.Models.GuestResponse();
guestResponse.Name = "this was generated from this ddl id:";
return PartialView("MyPartialView", guestResponse);
}
Then this in my javascript at the top of my view:
$(document).ready(function () {
$(".SelectedCustomer").change( function (event) {
$.ajax({
url: "#Url.Action("GetPartialDiv/")" + $(this).val(),
data: { id : $(this).val() /* add other additional parameters */ },
cache: false,
type: "POST",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
SetData(data);
}
});
});
function SetData(data)
{
$("#divPartialView").html( data ); // HTML DOM replace
}
});
Then finally my html:
<div id="divPartialView">
#Html.Partial("~/Views/MyPartialView.cshtml", Model)
</div>
Essentially when a my dropdown tag (which has a class called SelectedCustomer) has an onchange fired it should fire the post call. Which it does and I can debug into my controller and it even goes back successfully passes back the PartialViewResult but then the success SetData() function doesnt get called and instead I get a 500 internal server error as below on Google CHromes console:
POST http:// localhost:45108/Home/GetPartialDiv/1 500 (Internal Server
Error) jquery-1.9.1.min.js:5 b.ajaxTransport.send
jquery-1.9.1.min.js:5 b.extend.ajax jquery-1.9.1.min.js:5 (anonymous
function) 5:25 b.event.dispatch jquery-1.9.1.min.js:3
b.event.add.v.handle jquery-1.9.1.min.js:3
Any ideas what I'm doing wrong? I've googled this one to death!
this line is not true: url: "#Url.Action("GetPartialDiv/")" + $(this).val(),
$.ajax data attribute is already included route value. So just define url in url attribute. write route value in data attribute.
$(".SelectedCustomer").change( function (event) {
$.ajax({
url: '#Url.Action("GetPartialDiv", "Home")',
data: { id : $(this).val() /* add other additional parameters */ },
cache: false,
type: "POST",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
SetData(data);
}
});
});

how can i get file data on ajax page in magento?

I have made a custom module in magento. I am using ajax in it(prototype.js).i can find the post variable on ajax page. But I am unable to find the file array on ajax page.
I am using following code for this.Please let me know where i am wrong?
//Ajax code on phtml page
new Ajax.Request(
reloadurl,
{
method: 'post',
parameters: $('use-credit-Form').serialize(),
onComplete: function(data)
{
alert(data.responseText);
}
});
//Php code on ajaxpage
public function ajaxAction()
{
$fileData = $_FILES;
echo '<pre>';
print_r($fileData);die;
}
It always print blank. but when I added this line
"VarienForm.prototype.submit.bind(usecreditForm)();"
I can get the value of file array. but draw back now page starts refreshing.
Please give me some suggestion.
Try this:
Event.observe('use-credit-Form', 'submit', function (event) {
$('use-credit-Form').request({
onFailure: function () {
alert('fail.');
},
onSuccess: function (data) {
alert(data.responseText);
}
});
Event.stop(event); // stop the form from submitting
});
Credit: submit a form via Ajax using prototype and update a result div

jQuery.ajax() sequential calls

Hey. I need some help with jQuery Ajax calls. In javascript I have to generste ajax calls to the controller, which retrieves a value from the model. I am then checking the value that is returned and making further ajax calls if necessary, say if the value reaches a particular threshold I can stop the ajax calls.
This requires ajax calls that need to be processes one after the other. I tried using async:false, but it freezes up the browser and any jQuery changes i make at the frontend are not reflected. Is there any way around this??
Thanks in advance.
You should make the next ajax call after the first one has finished like this for example:
function getResult(value) {
$.ajax({
url: 'server/url',
data: { value: value },
success: function(data) {
getResult(data.newValue);
}
});
}
I used array of steps and callback function to continue executing where async started. Works perfect for me.
var tasks = [];
for(i=0;i<20;i++){
tasks.push(i); //can be replaced with list of steps, url and so on
}
var current = 0;
function doAjax(callback) {
//check to make sure there are more requests to make
if (current < tasks.length -1 ) {
var uploadURL ="http://localhost/someSequentialToDo";
//and
var myData = tasks[current];
current++;
//make the AJAX request with the given data
$.ajax({
type: 'GET',
url : uploadURL,
data: {index: current},
dataType : 'json',
success : function (serverResponse) {
doAjax(callback);
}
});
}
else
{
callback();
console.log("this is end");
}
}
function sth(){
var datum = Date();
doAjax( function(){
console.log(datum); //displays time when ajax started
console.log(Date()); //when ajax finished
});
}
console.log("start");
sth();
In the success callback function, just make another $.ajax request if necessary. (Setting async: false causes the browser to run the request as the same thread as everything else; that's why it freezes up.)
Use a callback function, there are two: success and error.
From the jQuery ajax page:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
// Do processing, call function for next ajax
}
});
A (very) simplified example:
function doAjax() {
// get url and parameters
var myurl = /* somethingsomething */;
$.ajax({
url: myurl,
context: document.body,
success: function(data){
if(data < threshold) {
doAjax();
}
}
});
}
Try using $.when() (available since 1.5) you can have a single callback that triggers once all calls are made, its cleaner and much more elegant. It ends up looking something like this:
$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1, a2){
// a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively
var jqXHR = a1[2]; /* arguments are [ "success", statusText, jqXHR ] */
alert( jqXHR.responseText )
});

Resources