I am using a button to trigger an AJAX call to retrieve data from an SQL database. The problem I'm having is when the button click also triggers a call to the server, the AJAX call fails.
Code:
$('.ptimage').click(function () {
document.getElementById('loading').style.display = "block";
if (dataStore.getItem('mlist') == null || dataStore.getItem('flist') == null) {
alert('isnull');
var nulldata = {};
nulldata.nullvar = "thing";
var jsonData = JSON.stringify({
nulldata: nulldata
});
$.ajax({
type: "POST",
url: "WebService.asmx/Getmf",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response) {
var arraystring = response.d;
alert(arraystring);
mlist = arraystring.split(',');
mlist.splice(0, 1);
mlist.splice(-1, 1);
dataStore.setItem('mlist', JSON.stringify(mlist));
flist = arraystring.split(';');
flist.splice(0, 1);
flist.splice(-1, 1);
dataStore.setItem('flist', JSON.stringify(flist));
}
function OnErrorCall(response) {
alert("fail");
}
}
ptsession = dataStore.getItem('ptsessionval');
if (ptsession !== focusedcell) {
btn57.click();
}
})
So if ptsession != focusedcell, essentially if the clicked record is different from the current one, it will trigger a server call to the c# codebehind to get the new record.
If the record is different, the AJAX call fails and the call to the server from button57 (postback) succeeds. If the record is the same (so no call to the server from button57) the AJAX call succeeds. I can't figure out why this is happening.
Related
Bear with me I'm my javascript is a little rusty. So I'm trying to use a call by ajax to a PHP file and give it a plan type then make sense of it check to see if it then return a true or false if some allowed slots are less than some slots used up for the plan. Here is the Form in XHTML.
<form method="post" action="/membership-change-success" id="PaymentForm">
<input type="hidden" name="planChosen" id="planChosen" value="" />
</form>
On the same file. The ( < PLAN CHOICE > ) gets parsed out to the current plan.
<script>
var hash = window.location.hash;
var currentPlan = "( < PLAN CHOICE > )";
$(".planChoice").click(function(event){
var isGood=confirm('Are you sure you want to change your plan?');
var success;
$("#planChosen").val($(this).data("plan"));
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: ({plan: $(this).data("plan")}),
success: function (data) { //This is what is not working I can't get it to return true
success = data;
}
});
if(success) {
if (isGood) {
$("#PaymentForm").submit();
}
window.location = '/membership-change-success';
} else {
alert('Please make sure you deactivate your listings to the appropriate amount before you Downgrade.')
}
});
My PHP for the ajax response looks like this.
<?php
require ('../includes/common.php');
include_once ('../includes/db-common.php');
require ('../includes/config.php');
$membership = new membership($dbobject);
$listing = new listing($dbobject);
$totalAvailableListings = ($membership->get_listingsAmount($_POST['plan']));
if($totalAvailableListings>=$listing->get_active_listings($user->id)){
echo json_encode(true); // I've tried with out jason_encode too
} else {
echo json_encode(false);
}
And that's pretty much it if you have any suggestions please let me know.
So I've tried to do it another way.
$(".planChoice").click(function (event) {
var isGood = confirm('Are you sure you want to change your plan?');
var success;
$("#planChosen").val($(this).data("plan"));
if (false) {
if (isGood) {
$("#PaymentForm").submit();
alert('you did it');
}
} else {
alert(isSuccessful($(this).data("plan")));
//alert('Please make sure you deactivate your listings to the appropriate amount before you downgrade.');
}
});
and I have an ajax function
function isSuccessful(plan) {
return $.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: {plan: plan}
});
}
The alert tells me this [object XMLHttpRequest]
any suggestions?
$.ajax() returns results asynchronously. Use .then() chained to $.ajax() call to perform task based on response
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: {plan: $(this).data("plan")}
})
.then(function(success) {
if (success) {
$("#PaymentForm").submit();
}
// if `form` is submitted why do we need to set `.location`?
// window.location = '/membership-change-success';
} else {
alert('Please make sure you deactivate your listings to the appropriate amount before you Downgrade.')
}
}, function err(jqxhr, textStatus, errorThrown) {
console.log(errorThrow)
})
You should use the following form for your ajax call
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: ({plan: $(this).data("plan")}),
success: success = data
})
.done(function(response) {
if(success) {
if (isGood) {
$("#PaymentForm").submit();
}
window.location = '/membership-change-success';
}
else {
alert('Please make sure you deactivate your listings to the
appropriate amount before you Downgrade.')
}
});
the .done() clause ensures that you perform that code after the ajax call is finished and the response is obtained.
I have an ajax request, whereby I am installing a magento shop automatically, and when the process is done, it would redirect the user to the newly created shop. Here are my codes:
function postSuccessFormData() {
var targetUrl = '/index.php/install/wizard/successPost';
jQuery('.form-button').addClass('loading');
setInterval(installStatus(),4000);
jQuery.ajax({
url: targetUrl,
global: false,
type: 'POST',
data: ({
finish: 1,
password_key: jQuery('#password_key').val()
}),
async: true,
dataType: 'json',
error: function() {
alert("An error has occurred. Please try again.");
},
success: function(data) {
window.location.href = '/';
}
});
function installStatus() {
var installerUpdatesUrl = '/index.php/install/wizard/installerStatus';
//showProgressBar();
jQuery.ajax({
url: installerUpdatesUrl,
// global: false,
type: 'GET',
async: true,
dataType: 'json',
error: function (data) {
// alert(data.result);
},
success: function (data) {
handle data.result
var dataKeys = Object.keys(data);
var lastElementKey = dataKeys[dataKeys.length - 1];
var lastMessage = data[lastElementKey]['message'];
if(data[lastElementKey]['progress'] == '') {
updateProgressBar(data[dataKeys[dataKeys.length - 2]]['progress'],100);
}
setting message
jQuery("#message").html(lastMessage);
if (data[lastElementKey]['state'] == 'Failure') {
var stepStr = lastElementKey.split('_');
var stepString = stepStr[0].toUpperCase() + ' ' + stepStr[1] + ':';
alert(stepString + "\n" + data[lastElementKey]['message']);
//hideProgressBar();
jQuery('.form-button').removeClass('loading');
return false;
} else if (data[lastElementKey]['state'] == 'Finish') {
alert(data[lastElementKey]['message']);
//hideProgressBar();
jQuery('.form-button').removeClass('loading');
//window.location.href = '/';
} else {
// installStatus();
}
},
complete: function () {
installStatus();
jQuery('.form-button').removeClass('loading');
}
});
}
The way this is done:
After every 4 seconds the function installStatus is run, which will output the current progress in JSON format. My problem is, this function needs to be executed simultaneously with the function post().
This is not happening, the installStatus is only run after the first function has been completed.
What is wrong?
You are executing installStatus when you define it. So this:
setInterval(installStatus(),4000);
needs to be
setInterval(installStatus, 4000);
The new XMLHttpRequest has a nice progress event you can listen to show the user the upload progress.
Here's the spec with a nice demo: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress
Initially you should call installStatus() only once and then inside the method inside ajax success you should update the procent in the progress bar and call it recursively the same method. On the server side you can save the current procent in a cookie and with every recursive call you can update the cookie and return the procent.
I want to display Updated records count when Ajax process is going on. When i click on start process button updateRecords()function will execute and it will update records status from open to waiting status one by one in database.So at the same time i want display the waiting records count .For this when user click on strat process button i want to call displayWaitingRecords() using setinterval.
I am calling that function like this from updateRecords()
clear_Process = setInterval(function(){displayWaitingRecords()},200);
But displayWaitingRecords() will not call until updateRecords() process completes.But my requirement is displayWaitingRecords() also will execute simaltaniously with updateRecords().
Function to display updated record count
function displayWaitingRecords()
{
jQuery.ajax({
type: 'GET',
crossDomain:true,
async: false,
url: "/curlRRQCount.php",
success: function(count){
if(count)
{
jQuery("#processed_poids_div").html("Processed Order ids:"+count) ;
}
}
});
}
Function when i click on start process button
var clear_Process = "";
function updateRecords()
{
clear_Process = setInterval(function(){displayWaitingRecords()},200);
var str = jQuery("#rrq_form :input[value!='']").serialize();
jQuery.ajax({
async: false,
type: 'POST',
data : str,
url: "/updaterecord_status.php",
success: function(valid_result)
{
if(jQuery.trim(valid_result) == 'Success')
{
jQuery("#rrq_load_img").hide();
jQuery("#rrq_orders_status").html("some success message");
}
}
});
}
Where i am doing wrong? Any help would be greatly appreciated.
You have set async: false. So the ajax call will process synchronized. Set it to false or leave it out (because true is default):
var clear_Process = "";
function updateRecords()
{
clear_Process = setInterval(function(){displayWaitingRecords()},200);
var str = jQuery("#rrq_form :input[value!='']").serialize();
jQuery.ajax({
async: true,
type: 'POST',
data : str,
url: "/updaterecord_status.php",
success: function(valid_result)
{
if(jQuery.trim(valid_result) == 'Success')
{
jQuery("#rrq_load_img").hide();
jQuery("#rrq_orders_status").html("some success message");
}
}
});
}
If you leave it out you have the same result:
function displayWaitingRecords()
{
jQuery.ajax({
type: 'GET',
crossDomain:true,
url: "/curlRRQCount.php",
success: function(count){
if(count)
{
jQuery("#processed_poids_div").html("Processed Order ids:"+count) ;
}
}
});
}
I have a web-page with the following script
Javascript
function LinkClicked() {
var stage = this.id;
var stop = $('#ContentPlaceHolderMenu_txtDate').val();
var nDays = $('#ContentPlaceHolderMenu_txtNumberOfDays').val();
$("[id$='spinner']").show();
$.ajax({
type: 'POST',
contentType: 'application/json',
url: "...",
data: "{stage:'" + stage + "',stop:'" + stop + "',nDays:'" + nDays + "'}",
success: function (data) {
$("[id$='spinner']").hide();
PlotData(data.d);
},
error: function () {
$("[id$='spinner']").hide();
alert("An error occured posting to the server");
}
});
}
How do I stop the user from repeatedly clicking whilst the query is running? The call is from a cell in a grid and can't easily be disabled. Ideally, I'd like a way of doing it in the script without disabling the link on the DOM.
Here I clicked five times, and you can see five AJAX requests are sent. The page should disable the same call being repeatedly invoked whilst it is already running.
Thanks in advance.
You could have an external variable tracking the state
var linkEnabled = true;
function LinkClicked() {
if(!linkEnabled){
return;
}
linkEnabled = false;
var stage = this.id;
var stop = $('#ContentPlaceHolderMenu_txtDate').val();
var nDays = $('#ContentPlaceHolderMenu_txtNumberOfDays').val();
$("[id$='spinner']").show();
$.ajax({
type: 'POST',
contentType: 'application/json',
url: "...",
data: "{stage:'" + stage + "',stop:'" + stop + "',nDays:'" + nDays + "'}",
success: function (data) {
$("[id$='spinner']").hide();
PlotData(data.d);
linkEnabled =true;
},
error: function () {
$("[id$='spinner']").hide();
alert("An error occured posting to the server");
linkEnabled = true;
}
});
}
This also has the advantage that you can choose to enable other effects of this function if you want, and only prevent the repeat ajax calls.
(Note that ideally you would want to stick the external variable in a closure or a namespace rather than making it a global).
Disable a button when user clicks it, and set disabled to false when you get response from ajax.
Declare a variable outside of the function with an initial value of false:
var pending = false;
When you make the request, you'd do:
if (pending == true) {return;}
pending = true;
This makes it stop if you're already running, and when the request is done:
pending = false;
Now even without a button, the request won't fire multiple times.
As a side note, your data doesn't need to be a string. You can just do:
data: {stage: stage, stop: stop, nDays: nDays}
you can just check use this
var ajax_stat = false
function doing_ajax(){
if(ajax_stat) return;
ajax_stat = true;
var xmlRequest = $.ajax({
type: 'POST',
contentType: 'application/json',
url: "...",
data: "{stage:'" + stage + "',stop:'" + stop + "',nDays:'" + nDays + "'}",
success: function (data) {
$("[id$='spinner']").hide();
PlotData(data.d);
},
error: function () {
$("[id$='spinner']").hide();
alert("An error occured posting to the server");
ajax_stat = false;
}
});
}
Use below code. it will not make multiple ajax calls.
function LinkClicked() {
if($(window).data("ajaxRUnning")){
return;
}
$(window).data("ajaxRUnning",true);
var stage = this.id;
var stop = $('#ContentPlaceHolderMenu_txtDate').val();
var nDays = $('#ContentPlaceHolderMenu_txtNumberOfDays').val();
$("[id$='spinner']").show();
$.ajax({
type: 'POST',
contentType: 'application/json',
url: "...",
data: "{stage:'" + stage + "',stop:'" + stop + "',nDays:'" + nDays + "'}",
success: function (data) {
$("[id$='spinner']").hide();
PlotData(data.d);
$(window).data("ajaxRUnning",false);
},
error: function () {
$("[id$='spinner']").hide();
alert("An error occured posting to the server");
$(window).data("ajaxRUnning",false);
}
});
}
This question already has an answer here:
javascript alert messages is not show in mvc3
(1 answer)
Closed 9 years ago.
I am working on a form in mvc3 and use form validations in javascript and ajax.
in my form i add code and description in database and before form submission want to check that code already exist in database or not.i get the code in javascript through ajax function call andd eturn data in json form. when i get the data i display error message in alert to user that code already exist. but my alert is not display.what can i do for it.
below is my javascript save button click function
$('#sve').click(function () {
//e.preventDefault();
var iscodeexis = CodeExistChk();
if (iscodeexis) {//
//***********************CODE TO SAVE DATA IN DATABASE***********************************
var person = { AcCode: $('#AcCode').val(), Descrip: $('#Descrip').val(), AddOn: dd };
$.ajax({
url: '/Home/Save?action=Sve',
type: "POST",
data: JSON.stringify(person),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
// $('#message').html('Record saved successfully' + result).fadeIn();
alert("Record saved successfully");
},
error: function () {
// $('#message').html('Error Occurred').fadeIn();
alert("Record not saved successfully");
}
});
}//end of is valid function chk
else
return false;//if isvalid function return false then save button also return false
}); //end button clcik function
function CodeExistChk() {
subA = $('#AcCode').val().trim();
// ===========================check whether code exist already or not
if (subA.length === 10) {
str1 = "select AcCode from Account where AcCode='";
str2 = str1 + subA + "'";
GetCodeData(str2); //check whether code exist or not
strRes = strRes.substring(1, strRes.length - 1);
if (strRes.length > 0 && strRes != "") //if code exist then return false and not allow to enter code
{
alert('Code already exist cannot insert record');
return false;
}
}
//===============================
}
below is getcodedata function which use in above code to get code from database
//===============FUNCTION TO GET CODE FROM DATABASE TO USE IN JS FILE==========
function GetCodeData(Str) {
var p = {
StrSql: Str
};
$.ajax({
url: '/Home/GetGenVal',
type: 'POST',
// contentType: 'application/x-www-form-urlencoded',
dataType: "JSON",
contentType: "application/json; charset=utf-8",
processData: false,
crossDomain: false,
traditional: true,
data: JSON.stringify(p),
cache: false,
// success: callback
success: function (data) {
//$("#Descrip").val(data);
// ResSubCode = data;
strRes = null;
strRes = data;
return strRes;
}
});
}
waiting for early solution.
Whoa, I see a some mistakes in this code.
At first, never construct your sql queries on client side to execute them. What if I modify the query to be a "delete from"? Bye bye database!
I would simply edit your logic and use a [RemoteAttribute] MVC3/4 feature to call a controller action and return simply a true or false.
Check it here: Remoteattribute test usage
You cannot be wrong!
Vincenzo.