how to pass ajax response value to another page? - javascript

I'm trying to send an AJAX response to a PHP file. Based on the response I would like to redirect to another page. If the response is success I would like to redirect to a 'thank you' page along with the parameter data.
How can I pass this transactionId to another page?
if ($result->success)
{
print_r("success!: " .$result->transaction->id);
}
else if ($result->transaction) {
print_r("Error processing transaction:");
print_r("\n code: " .$result->transaction->processorResponseCode);
print_r("\n text: " .$result->transaction->processorResponseText);
}
else
{
print_r("Validation errors: \n");
print_r($result->errors->deepAll());
}
$('#paymentForm').submit(function() {
var serializedData = $(this).serialize();
$.post('card.php', serializedData, function(response) {
// Log the response to the console
console.log("Response: "+response);
alert(response);
if (response == "success") {
window.location.href = 'http://www.google.com';
}
});
});
});

change your php output from
if ($result->success)
{
print_r("success!: " .$result->transaction->id);
}
else if ($result->transaction) {
print_r("Error processing transaction:");
print_r("\n code: " .$result->transaction->processorResponseCode);
print_r("\n text: " .$result->transaction->processorResponseText);
}
else
{
print_r("Validation errors: \n");
print_r($result->errors->deepAll());
}
to
if ($result->success)
{
echo json_encode(array('status'=>'success','id'=>$result->transaction->id));
}
else if ($result->transaction) {
echo json_encode(array('status'=>'error','code'=>$result->transaction->processorResponseCode, 'text'=> $result->transaction->processorResponseText)));
}
else
{
echo json_encode(array('status'=>'error','text'=>$result->errors->deepAll()));
}
and change your js to the following
$('#paymentForm').submit(function() {
var serializedData = $(this).serialize();
$.post('card.php', serializedData, function(response) {
// Log the response to the console
console.log("Response: "+response);
alert(response);
var data= $.parseJSON(response);
if (data.status == "success") {
window.location.replace('http://www.google.com?id='+data.id)‌​;
}else{
alert('Operation Failed');
if(data.code){
console.log('response code: '+data.code);
}
console.log('response text: '+data.text);
}
});
});
});

looking at your php code - it never returns success, it will return success!: somthing so this condition if (response == "success") is never true
you could use
if(response.indexOf("success") == 0)
or change the response in the php file

You can send the response variables you'd like by incorporating them into a query on the redirect.
For instance if you wanted to pass on foo to your redirected php domain.com/bar.php:
var url = 'domain.com/bar.php?foo=' + foo
window.location.href = url;
And then on the PHP page, you can use this data:
$bits = parse_url($url);
parse_str($bits['query'], $query);
echo $query['foo']

Related

How to stop a ajax request properly

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();
}

ajax data isn't the same in chrome vs firefox

Some reason I can return data fine from a POST in Chrome. The data returned looks like this when using Chrome:
{"email":"account#bytestand.com","customer_id":20413,"credit_amount":50.0,"currency_symbol":"$"}
But then when the same POST is completed on FireFox I get the following error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
Somehow the data isn't being handled the same and I don't know why.
Here is the code that generates the ajax request
function getCustomerAndCredit() {
console.log("getCustomerAndCredit");
$(function() {
$("form[action='" + shopAddress + "/account/login']").submit(function(event){
console.log("this is past the submit event in Firefox");
var custEmail = $("form[action='" + shopAddress + "/account/login'] input[type=email]").val();
var pass = $("form[action='" + shopAddress + "/account/login'] input[type=password]").val();
sessionStorage.setItem('custEmail', custEmail);
sessionStorage.setItem('pass', pass);
sessionStorage.setItem('loggedIn', true);
debugger;
$.ajax({
url: "/apps/proxy/return_customer",
data: {email: custEmail},
type: "POST",
dataType: "js",
complete: function(data) {
debugger;
if(noCustomerInDB(data)){
if(data.responseJSON == undefined){
sessionStorage.setItem('customer_id', JSON.parse(data.responseText).customer_id);
sessionStorage.setItem('creditAmount', JSON.parse(data.responseText).credit_amount);
sessionStorage.setItem('currency', JSON.parse(data.responseText).currency_symbol);
}
else {
sessionStorage.setItem('customer_id', data.responseJSON.customer_id);
sessionStorage.setItem('creditAmount', data.responseJSON.credit_amount);
sessionStorage.setItem('currency', data.responseJSON.currency_symbol);
}
}
// console.log("What is the credit_amount here in getCustomerAndCredit " + sessionStorage.getItem('creditAmount'));
},
});
});
});
}
And then this is where the data is going:
function noCustomerInDB(data){
console.log("this is the todd variable " + data);
console.log("stringify data " + JSON.stringify(data));
console.log("what about just data?? " + JSON.parse(data));
console.log("this is the response down here in the no customer function" + data.responseText);
if(data.responseText == ""){
return false;
}
else{
if (JSON.parse(data.responseText).customer_id == "no_customer"){
sessionStorage.setItem('creditAmount', "null");
return false;
}
else{
return true;
}
}
}
I did some more digging and now its looking like the ajax isn't being called on FireFox. Because the data returned from the POST looks like this:
{"readyState":0,"status":0,"statusText":"error"}
This cannot be - dataType: "js"
Use dataType: "json" instead. Also make sure that "/apps/proxy/return_customer" has the proper header configured to deploy JSON:
"Content-Type: application/json"

wordpress ajax returning zero instead of string message

My ajax call is returning zero even though I wrote die() at the end of my PHP function.
I looked over the other questions here and did not figure it out, please take a look at my code
I make an ajax call using this function:
$('.aramex-pickup').click(function() {
var button = $(this);
var pickupDateDate = $('.pickup_date').val();
var pickupDateHour = $('.pickup_date_hour').val();
var pickupDateMinute = $('.pickup_date_minute').val();
var pickupDate = pickupDateDate + ' ' + pickupDateHour + ':' + pickupDateMinute;
var orderId = button.data('id');
if (pickupDate) {
//show loader img
button.next('.ajax-loader').show();
var data = {
'action': 'aramex_pickup',
'order_id': orderId,
'pickup_date': encodeURIComponent(pickupDate)
};
$.ajax({
url: ajaxurl,
data: data,
type: 'POST',
success: function(msg) {
console.log(msg);
if (msg === 'done') {
location.reload(true);
} else {
var messages = $.parseJSON(msg);
var ul = $("<ul>");
$.each(messages, function(key, value) {
ul.append("<li>" + value + "</li>");
});
$('.pickup_errors').html(ul);
}
}, complete: function() {
//hide loader img
$('.ajax-loader').hide();
}
});
} else {
alert("Add pickup date");
}
return false;
});
in the back-end I wrote this function just to test the ajax is working ok:
public function ajax_pickup_callback() {
echo 'ajax done';
die();
}
I registered the action by:
add_action('wp_ajax_aramex_pickup', array($this, 'ajax_pickup_callback'));
all of this returns 0 instead of "ajax done".
Any help please?
Actually your hook is not get executed. You have to pass the action in the ajax request as you can see here.
jQuery.post(
ajaxurl,
{
'action': 'add_foobar',
'data': 'foobarid'
},
function(response){
alert('The server responded: ' + response);
}
);

unable to redirect after successfully inserted data into mysql via Ajax

I use ajax, php to insert data into mysql database. However after finished executing all queries, it doesn't do anything. I mean, when I click submit button in the form, as a user I don't see anything happening even though I set my Ajax function to alert the data. But in the backend all data are inserted properly into the database.
So, I'm not sure how to notify user of a successful form submission. Could anyone help please? Thank you in advance.
I referred here, but it doesn't help:Page redirect with successful Ajax request
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
var xmlhttp = false;
try
{
xmlhttp = new ActiveXObject(Msxml2.XMLHTTP);
//alert("javascript version greater than 5!");
}
catch(e)
{
try
{
xmlhttp = new ActiveXObject(Microsoft.XMLHTTP);
// alert("you're using IE!");
}
catch(E)
{
xmlhttp = new XMLHttpRequest();
//alert("non IE!");
}
}
//Ajax function for some other element before submitting form
function sendtobox(param,param2)
{
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if (this.responseText !== null) {
var ajaxElm = document.getElementById('boxA');
ajaxElm.innerHTML = this.responseText + ajaxElm.innerHTML; // append in front
}
}
}
xmlhttp.open("GET","getsubjects.php?q="+param+"&r="+param2,true);
xmlhttp.send();
}
//Ajax after submit button clicked
$("document").ready(function(){
$(".form").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$(".the-return").html("<br />JSON: " + data["json"] );
//alert("Form submitted successfully.\nReturned json: " + data["json"]);
window.location='tutor-profile.php'
//header('Location:tutor-profile.php');
}
});
return false;
});
});
</script>
response.php
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "test": test_function(); break;
}
}
}
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test_function(){
include('inc/config.php');
$return = $_POST;
//$return ='{"slider1":"150","level":{"Upper Secondary":"2"},"sub":{"8":""},"rate2":{"7":"89","8":"150","9":"150","10":"150","11":"150","12":"150","13":"150","14":"150"},"a_end":"on","e_week":"on","e_end":"on","name":"ting1","phone":"098-098-0980","email":"ting1#Gmail.com","postcode":"56547","gender":"on","password":"nk","action":"test"}';
$return["json"] = json_encode($return);
// json_encode($return);
//
//below code to store in database
$data = json_decode($return["json"], true);
//var_dump($data); // Dump all data of the Array
>>>>>>INSERT QUERIES GO HERE>>>>>>>>>>>>>>>>
echo"form submitted ";
}
The code for redirect to another page in Javascript is
window.location.href ='tutor-profile.php'
Anyway they do not understand your previous roles and XMLHttpRequest your statements, that is ajax, but you simplify everything using only the last function $.ajax of jQuery.
The other correction is that you're saying that the server response will be of type "Json" but you just give back a string through a miss. What you can do is change it to this:
exit( json_encode( array('response'=>'put your text here') ) );
And then in JS instead of
$(".the-return").html("<br />JSON: " + data["json"] );
place this:
$(".the-return").html("<br />JSON: " + data.response );

jquery ajax always results in 'error' even when it works

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;
}

Categories