I would like to retry an ajax request when response data is an empty json object.
My ajax code is following.
$.ajax({
type: "POST",
url: "index.php?r=funding/getPaymentButton",
data: {email:benfEmail,data:JSON.stringify(data),paymentType:method},
async: true,//false
success: function (data)
{
if(data.length === 0)
{
$(this).ajax();//retry ajax request here, if data is empty
console.log('err');
}
else
{
obj = jQuery.parseJSON(data);
// prcessing ajax request
}
}
});
PHP
echo json_encode(array(
'type'=>$paymentType,
'btn'=>$this->PaymentBtn,
'usd' => round($this->finalUSDAmount,2),)
);
You can put your ajax request in a function and then call that function If the respons is empty.
Like this:
function yourCall(){
$.ajax({
type: "POST",
url: "index.php?r=funding/getPaymentButton",
data: {email:benfEmail,data:JSON.stringify(data),paymentType:method},
async: true,//false
success: function (data)
{
if(data.length === 0)
{
yourCall();
console.log('err');
}
else
{
obj = jQuery.parseJSON(data);
// prcessing ajax request
}
}
});
}
this setup will however keep trying the ajax call untill it gets a valid respons. This meaning that it will keep firing if the respons length == 0
Just Simply Do Following:
$.ajax({
url : 'index.php?r=funding/getPaymentButton',
type : 'POST',
data : {email:benfEmail,data:JSON.stringify(data),paymentType:method},
tryCount : 0,
retryLimit : 3,
success : function(json) {
//do something
},
error : function(xhr, textStatus, errorThrown ) {
if (textStatus == 'timeout') {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
//try again
$.ajax(this);
return;
}
return;
}
if (xhr.status == 500) {
//handle error
} else {
//handle error
}
}
});
Related
I'm very new with Ajax and I need help to store the data from an Ajax request into an array. I looked at answers here at the forum, but I'm not able to solve my problem.The Ajax response is going into $('#responseField').val(format(output.response)) and I'm want store "output.response" into an array that can be used outside of the Ajax. I tried to declare a variable outside of the Ajax and call it later, but without success. I'm using $json_arr that should get the data. How do I do to get the data from the Ajax and store it in a variable to be used outside of the Ajax? This variable will an array that I can access the indexes.
function sendRequest(postData, hasFile) {
function format(resp) {
try {
var json = JSON.parse(resp);
return JSON.stringify(json, null, '\t');
} catch(e) {
return resp;
}
}
var value; // grade item
$.ajax({
type: 'post',
url: "doRequest.php",
data: postData,
success: function(data) { //data= retArr
var output = {};
if(data == '') {
output.response = 'Success!';
} else {
try {
output = jQuery.parseJSON(data);
} catch(e) {
output = "Unexpected non-JSON response from the server: " + data;
}
}
$('#statusField').val(output.statusCode);
$('#responseField').val(format(output.response));
$("#responseField").removeClass('hidden');
data = $.parseJSON(output.response)
$json_arr=$('#responseField').val(format(output.response));
},
error: function(jqXHR, textStatus, errorThrown) {
$('#errorField1').removeClass('hidden');
$("#errorField2").innerHTML = jqXHR.responseText;
}
});
}
window.alert($json_arr);
let promise = new Promise(function(resolve, reject) {
$.ajax({
type: 'post',
url: "doRequest.php",
data: postData,
success: function(data) { //data= retArr
var output = {};
if(data == '') {
output.response = 'Success!';
} else {
try {
output = jQuery.parseJSON(data);
} catch(e) {
output = "Unexpected non-JSON response from the server: " + data;
}
}
$('#statusField').val(output.statusCode);
$('#responseField').val(format(output.response));
$("#responseField").removeClass('hidden');
data = $.parseJSON(output.response)
resolve(format(output.response));
},
error: function(jqXHR, textStatus, errorThrown) {
$('#errorField1').removeClass('hidden');
$("#errorField2").innerHTML = jqXHR.responseText;
}
});
});
promise.then(
function(result) { /* you can alert a successful result here */ },
function(error) { /* handle an error */ }
);
The issue is you are calling asynchronously.
You call the alert synchronously, but it should be called asynchronously.
A little snippet to help you see the difference:
// $json_arr initialized with a string, to make it easier to see the difference
var $json_arr = 'Hello World!';
function sendRequest() {
$.ajax({
// dummy REST API endpoint
url: "https://reqres.in/api/users",
type: "POST",
data: {
name: "Alert from AJAX success",
movies: ["I Love You Man", "Role Models"]
},
success: function(response){
console.log(response);
$json_arr = response.name;
// this window.alert will appear second
window.alert($json_arr);
}
});
}
sendRequest();
// this window.alert will appear first
window.alert($json_arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I have the below Ajax function
ajax = function (params, action) {
$.ajax({
type: "POST",
url: "ajax.php",
data : params+"&action="+action,
dataType: "json",
success: function(response) {
switch(action)
{
case "save":
//some stuff
break;
case "del":
var seclastRow = $("."+table+" tr").length;
if(response.success == 1)
{
$("."+table+" tr[id='"+response.id+"']").effect("highlight",{color: '#f4667b'},500,function()
{
$("."+table+" tr[id='"+response.id+"']").remove();
});
}
break;
}
},
error: function() {
alert("Unexpected error, Please try again");
}
});
}
The following is the ajax.php that it calls. The file is a big if-else series, but I am pasting the wrong part only.
else if ($action == "del")
{
$id = $_POST['rid'];
$res = $obj->delete_record($id);
if ($res)
{
echo json_encode(array("success" => "1","id" => $id));
}
else
{
echo $obj->error("delete");
}
}
However, once the result is echoed back, the success function never enters in the Ajax part and I always get the Unexpected error alert.
Any ideas?
I as able to get the error using the callback error: function() and then displaying the response inside console.log. Check the image. response text
I am having issues validating a response from API.
I am using php-crud-api and I am passing the values from my login form to the url filter[], the server responds with a 200 OK and returns the json data from the table. However I don't need the json data just a "success" or "error" response. Any help would be amazing. Thank you in advance for any feedback.
$(document).ready(function() {
$("#login-button").click(function() {
log_email = $("#login_email").val();
log_password = $("#login_password").val();
$.ajax({
type: "GET",
url: "http://www.website.com/api.php/users?",
crossDomain: true,
data: "filter[]=email,eq,email=" + log_email + "&filter[]=password,eq,password=" + log_password,
dataType: 'json',
success: function(data) {
if (data == "null") {
console.log("Email and Password DIDN'T match");
$( "#invalid-login" ).popup( "open" );
}
else if (data == "true") {
console.log("it's a !!MATCH!!");
window.location = "content.html";
}
}
});
return false;
});
});
I've read the documentation of https://github.com/mevdschee/php-crud-api and its written that it will return the output in json format only "Condensed JSON ouput: first row contains field names", so you need to change your code accordingly or you can use some other option.
Luckily the API developer got back to me and he offered the following solution:
in the ajax call add the following line to limit the output:
+"&columns=email"
Replase:
if (data == "null") {
With:
if (data.users.records.length==0) {
In the else clause, just replace:
else if (data == "true") {
with:
else {
RESULT:
$(document).ready(function() {
$("#login-button").click(function() {
log_email = $("#login_email").val();
log_password = $("#login_password").val();
$.ajax({
type: "GET",
url: "http://www.website.com/api.php/users?",
data: "filter[]=email,eq,"+log_email+"&filter[]=password,eq,"+log_password+"&columns=email",
crossDomain: true,
dataType: 'json',
cache: false,
success: function(data) {
if (data.itouchyou.records.length == 0) {
//FAIL
$( "#invalid-login" ).popup( "open" );
console.log("Email and Password DIDN'T match");
}
else {
// SUCCESS
window.location = "content.html";
console.log("it's a !!MATCH!!");
}
}
});
return false;
});
});
I'm having a problem with my ajax code. Its supposed to check a returned value from php, but it's always returning undefined or some other irrelevant value. As i'm quite new to ajax methodologies i can't seem to find a headway around this. I've searched numerous link on stackoverflow and other relevant forums regarding the solution but none helped. The problem remains the same
Here is the ajax code::
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path },
type: 'POST',
dataType: 'json',
success: function(data) {
if (data == 1) {
alert("Value entered successfully" + data);
} else if (data == 0) {
alert("Sorry an error has occured" + data);
}
});
return false;
})
});
The problem lies with outputting the value of data. The php code returns 1 if the value is successfully entered in the database and 0 otherwise. And the ajax snippet is supposed to check the return value and print the appropriate message. But its not doing such.
Here is the php code::
<?php
require './fileAdd.php';
$dir_path = $_POST['path'];
$insVal = new fileAdd($dir_path);
$ret = $insVal->parseDir();
if ($ret ==1 ) {
echo '1';
} else {
echo '0';
}
?>
I can't find a way to solve it. Please help;
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path },
type: 'POST',
//dataType: 'json', Just comment it out and you will see your data
OR
dataType: 'text',
Because closing } brackets not matching try this
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path},
type: 'POST',
dataType: 'text', //<-- the server is returning text, not json
success: function(data) {
if (data == 1) {
alert("Value entered successfully" + data);
} else if (data == 0) {
alert("Sorry an error has occured" + data);
}
} //<-- you forgot to close the 'success' function
});
return false;
});
});
I'm using an autosuggest plugin that allows me to select multiple items from a dropdown menu (demo here). I want a query to be sent to a php file (I will be preoccupied with the query itself later) and get a result back without leaving the page.
The php file is pretty much empty right now:
<?php print_r($_REQUEST); ?>
But I know I made a mistake with my jquery somewhere since the search box is not displaying properly anymore.
Here's the code I built up, I'm not sure what to put in the "data" field.
<script type="text/javascript">
$(document).ready(function(){
$("#select3").fcbkcomplete({
json_url: "data.txt",
addontab: true,
maxitems: 10,
input_min_size: 0,
height: 10,
cache: true,
newel: false,
filter_selected: true,
maxitimes: 5,
// I did this
onselect:"get_venue",
});
// I also did this
function get_venue() {
$("#select3 option:selected").each(function() {
$.ajax({
type: 'POST',
url: 'post.php',
dataType: 'json',
data: {
WHAT DATA GOES HERE?
},
success : function(data){
$('#phpmessage').removeClass().addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true)
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#phpmessage').removeClass().addClass('error')
.text('There was an error.').show(500);
}
});
});
}
});
</script>
Sorry for such a long post everybody :)!! Thanks :))
Error I'm getting:
Is not a function: return func.call(func, _object);
function funCall(func, item) {
var _object = {};
for (i = 0; i < item.get(0).attributes.length; i++) {
if (item.get(0).attributes[i].nodeValue != null) {
_object["_" + item.get(0).attributes[i].nodeName] = item.get(0).attributes[i].nodeValue;
}
}
return func.call(func, _object);
}
function checkFocusOn() {
if (focuson == null || focuson.length == 0) {
return false;
}
return true;
}
You want to loop over each of the items in the search box, these have a class of .bit-box. Create an array of these search terms then send them in as data into the ajax request.
function get_venue() {
var data = [];
$('.bit-box').each(function() {
data.push( $(this).text );
});
$.ajax({
type: 'POST',
url: 'post.php',
dataType: 'json',
data: {
'choices[]': data
},
success : function(data){
$('#phpmessage')
.removeClass()
.addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true){
}
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#phpmessage').removeClass().addClass('error')
.text('There was an error.').show(500);
}
});
}