I'm trying to stop an Ajax request when a user click a button. But even if I made use the .abort(); the ajax keep requesting each 2 seconds. Basically, a user wait for an input from the server. If the response is 2, then after 2 second an ajax request need to be call. If the response is 3, then is it good. the function is not called anymore.
I tried different solutions, .arbord(); changed the ajax completely...etc None of the solution worked out. I guess I'm missing some concept here.
////////////////////// index.php
.
<button id="cancel" onclick="CancelRequest()">Cancel</button>
.
<script>
function CheckStatus(){
var jqXHR = $.ajax({
url: "status.php",
async: true,
cache: false,
type: "POST",
data: {data: id},
success: function(response){
var response;
if (response == 2) {
alert(response);
setTimeout(CheckStatus, 2000); /// NEED TO SEND THE REQUEST AJAX REQUEST AGAIN, the response needs to be 3
} else if (response == 3) {
alert("good");
} else {
alert("error");
}
}
});
}
CheckStatus(); // start ajax automatically
}
//cancel request if the user press a button
function CancelRequest() {
jqXHR.abort();
}
</script>
///////////////////////////////////// status.php
$number = $_POST['id'];
.
.
.
.
$number = 2;
if ($number['status'] === 3) {
echo "good";
} elseif ($result['status'] == 2) {
echo "repeat again";
} else {
echo "error";
}
I expect that when I call jqXHR.abort(); the ajax should stop. However it keep going forever.
Declare the variable jqXHR outside of the CheckStatus() function
<script>
var jqXHR;
function CheckStatus(){
jqXHR = $.ajax({
url: "status.php",
async: true,
cache: false,
type: "POST",
data: {data: id},
success: function(response){
var response;
if (response == 2) {
alert(response);
setTimeout(CheckStatus, 2000); /// NEED TO SEND THE REQUEST AJAX REQUEST AGAIN, the response needs to be 3
} else if (response == 3) {
alert("good");
} else {
alert("error");
}
}
});
}
CheckStatus(); // start ajax automatically
}
//cancel request if the user press a button
function CancelRequest() {
jqXHR.abort();
}
Related
I have a global ajaxSuccess event and a local success function attached to an ajax request.
I want to cancel the success function if the global find status = false in the response.
like this
$(document).ajaxSuccess(function (event, xhr) {
let result = xhr.responseJSON;
if (result.status === false) {
//here the ajax should be stopped, I don't want to call the local functio
}
}
$.ajax(url, {
'method': method,
'success': function () {
//success function to call if the global ajaxSuccess is ok
}
})
can this be achieved ?
This will give you an insight into what you may be looking for. You will need to return the backend data in json.
why don't you set status to certain values
Eg. false= 0 and true = 1. You can then print success or failure based on values returned from the backend in this sample from PHP backend.
Here am sending a post variable with value of test_ok. If the value is test_ok then alert success else alert fail and
stop further action
<script>
$(document).ready(function(){
var test ='test_ok';
var datasend = "test="+ test;
$.ajax({
type:'POST',
url:'test.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(result){
$('#result').fadeIn('slow').prepend(msg);
if (result.status ==0) {
alert('failed');
return false;
}
if (result.status == 1) {
alert('success');
}
}
});
});
</script>
test.php
<?php
$test = $_POST['test'];
$output = array();
if($test == "test_ok"){
$output[] = array(
"status" => '1'
);
}
if($test != "test_ok"){
$output[] = array(
"status" => '0'
);
}
echo json_encode($output);
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 a memory game code, using javascript, php and css.
I would like to register somehow the event when the game is finished by php so that I can save the results in database.
In other words I would like to place php code inside <div id="player_won"> </div> and trigger that winning event properly.
css
#player_won{
display: none;
}
javascript
$(document).ready(function(){
$(document).bind("game_won", gameWon);
}
function gameWon(){
$.getJSON(document.location.href, {won: 1}, notifiedServerWin);
var $game_board = $("#game_board");
var $player_won = $("#player_won");
$game_board.hide();
$player_won.show();
$game_board = $player_won = null;
};
You'll want to create an ajax call that sends some information from the page and tells the php file below if the player has won or lost. After which you can deal with the logic needed for the player inside foo.php and send back Json to the success function inside the ajax call and update your page accordingly.
index
$(document).ready(function () {
//look for some kind of click below
$(document).on('click', '#SomeId', function () {
//Get the information you wish to send here
var foo = "test";
$.ajax({
url: "/foo.php",
type: 'POST',
cache: false,
data: {Info: foo},
dataType: 'json',
success: function (output, text, error)
{
//here is where you'll receive the son if successfully sent
if(ouput.answer === "yes"){
$("#player_won").show();
} else {
// Do something else
}
},
error: function (jqXHR, textStatus, errorThrown)
{
//Error handling for potential issues.
alert(textStatus + errorThrown + jqXHR);
}
})
})
});
foo.php
<?php
if(isset($_POST['Info'])){
//figure out if what was sent is correct here.
if($_POST['Info'] === "test"){
$data['answer'] = "yes";
echo json_encode($data);
exit;
} else {
// do something else
}
}
?>
I am using twitter bootstrap form wizard to submit data on each page with validation. Now i want to prevent, scroll to next step if ajax response gets error while submitting data. Below is my code,
'onNext': function(tab,navigation,index){
//scrollTo('#wizard',-100);
if(index == 1){
var $valid = $('#register_form').valid();
if(!$valid){
$validator.focusInvalid();
return false;
}
else
{
var options = $('form[name=register_form]').find('input, textarea, select').filter('.fw1').serialize();
var data = options + '&step=1';
$.ajax({
type: 'POST',
url: 'employeeEntryProcess.php',
data: data,
success: function(data){
this.show(2);
},
error: function(){
return false;
}
});
}
}
},
Thanks,
Its working after changes. Thanks to all for helping.
'onNext': function(tab,navigation,index){
if(index == 1){
var $valid = $('#register_form').valid();
if(!$valid){
$validator.focusInvalid();
return false;
}
else
{
var options = $('form[name=register_form]').find('input, textarea, select').filter('.fw1').serialize();
var data = options + '&step=1';
$.ajax({
type: 'POST',
url: 'employeeEntryProcess.php',
data: data,
success: function(response){
$('#wizard').bootstrapWizard('show',1);
},
error: function(){
alert('Error');
}
});
}
}
return false;
},
The only way to do this is to always return false so that it doesn't scroll to next step automatically, and then manually scrolling to the next step in the success function of the AJAX request (so that it would only proceed if it was successful). You may want to put an animation for the duration of the AJAX request as otherwise it would look like nothing is happening.
I have the below JQuery ajax function which is used to update a PHP Session variable.
I POST two variables, which the PHP page collects and sets the relevant Session variable.
Occasionally though it doesn't work, even though the correct values are being Posted across.
So I started to look at whether the Ajax was completing OK in these cases by adding success / error functions to the ajax.
But what I have found is that on every occasion I am gettng a response from the error function, and not the success function, even when it does complete succesfully and update the PHP variable.
Am I missing something here. Do I need to create a response or should that be automatic?
My Javascript is:
GBD.updateFunction = function(p,x)
{
$.ajax(
{
type: "POST",
url: "SetSession.php",
dataType:'text',
data:
{
item:p,
section:x
},
success: function()
{
alert('success');
},
error: function()
{
alert('failure');
}
});
console.log(p + " " + x + " selected");
return false;
}
The setSession . php is:
$section = (isset($_POST['section']) ? $_POST['section'] : 0 );
if($section == 1)
{
if(isset($_POST['item']))
{
$pageVar = $_POST['item'];
$_SESSION['pagevar'] = $pageVar;
}
else
{
$_SESSION['pagevar'] = $_SESSION['pagevar'];
};
}
?>
Try this way
//server code
$section = (isset($_POST['section']) ? $_POST['section'] : 0 );
if($section == 1)
{
if(isset($_POST['item']))
{
$pageVar = $_POST['item'];
$_SESSION['pagevar'] = $pageVar;
}
else
{
$_SESSION['pagevar'] = $_SESSION['pagevar'];
};
echo "success";
}
?>
//ajax call
GBD.updateFunction = function(p,x)
{
$.ajax(
{
type: "POST",
url: "SetSession.php",
dataType:'text',
data:
{
item:p,
section:x
},
success: function(data)
{
console.log(data);
},
error: function(jqxhr)
{
//it will be errors: 324, 500, 404 or anythings else
console.lgo(jqxhr.responseText);
}
});
return false;
}