How to Convert Jquery Ajax Success Data to a PHP Variable

How to Convert jQuery ajax success data to a PHP variable

PHP scripts execute when you open a file and before everything else.
Ajax calls exectue when the Javascript is completely loaded. (After php).

So you cant do it.
could you give me more detail about what do you want to do?

How to return PHP variables on success AJAX/jQuery POST

Well.. One option would be to return a JSON object. To create a JSON object in PHP, you start with an array of values and you execute json_encode($arr). This will return a JSON string.

$arr = array(
echo json_encode($arr);


Now in your jQuery, you'll have to tell your $.ajax call that you are expecting some JSON return values, so you specify another parameter - dataType : 'json'. Now your returned values in the success function will be a normal JavaScript object.

type: "POST",
url: "...",
data: query,
dataType: 'json',
success: function(data){
console.log(data.stack); // overflow
console.log(data.key); // value

Update PHP Variable after Ajax call

You don't want to do the live updating with PHP variables, since those are only refreshed when the page is reloaded. Instead, you want to update an element's value via AJAX. As far as I can tell, you want to update the expiration date. If you don't, just let me know and I can change the code to whatever it's supposed to do.

Here's the "control flow" of this functionality:

  1. (Entry point) User clicks 'Submit', jQuery event handler fires
  2. jQuery AJAX function is called and sends the promo code to a PHP script
  3. In the PHP script, the database is updated with the promo code.
  4. The PHP script returns the new expiry date (I'll assume that it's in the d/m/Y format you wanted)
  5. The callback in the jQuery AJAX function receives the data from the script.
  6. The callback's function body updates the "Expiry" element on the page with the value from the PHP call.

Here's how to put that into HTML / JavaScript:

<h4 class="sbText mt-10" id="expiry_label">
Trial End Date: <?php echo date("d/m/Y",
strtotime($trialExpiry)); // The initial value can be displayed as normal. ?>

<form id='promocode'>
<input type='text' class='sbInput' placeholder='Promo Code' name='promocode'>
<input type='hidden' name='userid' value='<?php echo $userID; ?>'>
<button class='btn sbSubmit'>Submit</button>

$(function () {
$('#promocode').on('submit', function (e) {
type: 'post',
url: '../model/process-promo-code.php',
data: $('#promocode').serialize(),
success: function (result) {
'transition-duration': '1000ms',
'opacity': '0.5'
document.getElementById("expiry_label").innerHTML = "Trial End Date: " + result;

As you can see, I only added an "id" attribute to the element, a parameter to the "success" property of the AJAX call, and a line of code to update the element.

Hope I helped!

Related Topics

Leave a reply