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);
Related
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();
}
Ok so what I'm basically trying to do is sending a form which contains a password (predefined, no DB) through AJAX. In my php file I check the input and I try to return true or false to my JS, but this part fails as I can't manage to access the value. Here is my code:
ajaxRequest.js
// Variable to hold request
var request;
// Bind to the submit event of our form
$(".lockForm").submit(function(event){
// Prevent default posting of form - put here to work in case of errors
event.preventDefault();
// Abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// Let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// Serialize the data in the form
var serializedData = $form.serialize();
// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// Fire off the request to /form.php
request = $.ajax({
url: "assets/php/lockscreen.php",
type: "POST",
data: serializedData,
dataType: 'text',
success: function (data) {
console.log(data.status);
}
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// Reenable the inputs
$inputs.prop("disabled", false);
});
});
lockscreen.php
<?php
// You can access the values posted by jQuery.ajax
// through the global variable $_POST, like this:
$pass = isset($_POST['pass']) ? $_POST['pass'] : null;
$response = false;
function CheckInput($pass){
if($pass == "SPV" || $pass == "TEACHERS"){
$response = true;
$responseLock['status'] = 'true';
echo json_encode($responseLock);
} else {
$response = false;
$responseLock['status'] = 'true';
echo json_encode($responseLock);
}
}
?>
So far I tried changing the dataType to JSON, but then I got an unexpected end of input error. If I leave it 'text', whenever I try to access the value, I get "undefined". If I only display the console.log, without trying to access any value, I get a success message. I have no idea why though.
call your CheckInput function:
<?php
$pass = isset($_POST['pass']) ? $_POST['pass'] : null;
$response = false;
function CheckInput($pass) {
if($pass == "SPV" || $pass == "TEACHERS"){
$result = true;
} else {
$result = false;
}
return array('status' => $result);
}
echo json_encode(CheckInput($pass));
?>
I have made a little AJAX-script for my site, which executes a php-script in another file on submission. I managed to echo out the result in the original file with the AJAX-function, but I have not managed to transfer a variable from the php file to the original one.
I need this variable in order to add an event listener which will look for changes in that particular variable (not sure how to do that either).
Here's are what you are looking for it's working:-
Put this in your forsok.php
<div id="input">
<input type="text" id="number" name="value">
<b id="show_result"></b>
</div>`
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$('#number').on('keyup',function(e){
if(e.which == 13){
var get_var_name = $(this).val();
$.get('result.php',{number:get_var_name},function(data,status){
if(status == 'success'){
alert(data['show']);
$('#show_result').text(data['show']);
}else{
alert('Nothing');
}
});
}
});
</script>
For hej.php:-
<?php
$one=$_GET['number'];
if(empty($one)) {
echo "Can't be blank";
$a['result']='null';
$a['error'] = 'No value!!';
} else {
if(is_numeric($one)) {
$show=$one*2;
$arr = array(
'show'=>$show
);
header('Content-Type:application/json');
echo json_encode($arr);
exit();
// echo $show;
} else {
echo "NaN";
$a['result']='null';
$a['error']='nan';
}
}
?>
First create an array of what should be the output. JSON encode that array and then you can parse the output in your ajax success handler. Like in your php file output like:
echo json_encode(array(
'result' => 'null',
'error' => 'nan'
));
Then in you ajax success turn the json into an object and parse data as you want:
success: function (data, textStatus, jqXHR) {
var obj = $.parseJSON(data);
$('#utmatning').html(obj.result); // result value from your json return
$('#utmatning').append(obj.error); // error value from your json return
}
At last of your php file, add,
json_encode($a);
In ajax success,
success: function(html) {
$.each(html, function(index, element) {
alert(element.result);
alert(element.error);
//append to which ever div you want.
});
}
Now with this, you can get n number of array indexes from php
Instead of echoing strings here and there in in hej.php it might better to return JSON data to your ajax call. so you can evaluate if an error occured, which error it is or which valid result has been returned.
hej.php:
<?php
$one=$_GET['value'];
if(empty($one)) {
$a['result']='null';
$a['error'] = 'No value!!';
} else {
if(is_numeric($one)) {
$a['result']=$one*2;
$a['error']='ok';
} else {
$a['result']='null';
$a['error']='nan';
}
}
die(json_encode ($a));
?>
if $value was 1 that would return
{"result":"2","error":"ok"}
In forsok.php you could check the reults and act accordingly
...
$.ajax({
type: "GET",
dataType: "json",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(response)
{
if (response.error=='ok'){
$('#utmatning').html(response.result); // show response from the php script.
}
else{
console.log(response.result); // handle the error
}
}
});
...
Regards,
Stefan
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;
}
AJAX function
var stopTime = 0;
var checkRequApprove = function ()
{
$.ajax({
url: 'http://127.0.0.1/ProgVsProg/main/checkApproveReq',
success:function(output){
jsn=JSON.parse(output);
if(output==false){
stopTime = setTimeout(checkRequApprove, 3000);
}
else {
bootbox.dialog({
message: "Battle",
title: "Request Accepted",
buttons:
{
success: {
label: "Approve",
className: "btn-success",
callback: function() {
$.ajax({
"type" : "POST",
"url" : "finalBattleApprove",
"data" : {'username' : jsn.user_name},
success: function(data){
$('#example').html(data);
$('#loadingmessage').show();
}
});
}
},
}
}
});
}
stopTime = setTimeout(checkRequApprove,3000);
Controller
public function checkApproveReq(){
$id = $this->session->userdata('userID');
$requApprove = '1';
$check = $this->lawmodel->checkRequApprove($id,$requApprove);
foreach($check as $row){
if($row->requApprove == '1')
{
$reqID = $this->lawmodel->getID($row->requestedID);
foreach($reqID as $row){
echo json_encode(
array(
'user_name' =>$row->username,
)
);
}
}
else
echo false;
}
}
I have this code wherein there is a realtime check to the database and if the condition has meet..custom dialog will pop up.
Im having this problem on my checkRequApprove function..The bootbox.dialog will not showup if the condition is meet in the controller...
i believe that my problem is because in the controller which echo json_encode. I cant find any solution .im still a newbie in ajax..
EDITED
the custom dialog will only show after i refresh the page.
output is a string - the comparison output == false will always yield false, because a non-empty string is always true (not considering the edgecase "0" in which case "0" == false yields true).
Instead of
if(output==false){
...
}
it should be:
if (!jsn){ // or jsn == false if you like that better
...
}
Also you should consider not returning a simple value in your controller, but always a proper json-object like:
else{ // consider always using brackets, for more robustness
echo
array(
'error' => true
);
}
Now, in your js you just check for
if (jsn.error){
...
}
In any case, you should include an error callback for your json to handle possible errors with the json request.