Andy
Andy

Reputation: 35

A part of AJAX response storing in PHP variable

I need to store a piece of data, into PHP variable, which is received through AJAX response in an input box. How can I do this?

<script type="text/javascript">
  $(document).ready(function() {

    $("#user_id").change(function() {
      var id = $(this).val();
      var dataString = 'user_id='+ id;

      $.ajax({
        type: "POST",
        url: "wmat_details.php",
        data: dataString,
        cache: false,
        success: function(result) {
          var data = result.split(",");

          $('#name').val(data[0]);
          $('#email').val(data[1]);
          $('#ref_id').val(data[2]);
          $('#candidature_start').val(data[3]);
          $('#candidature_end').val(data[4]);
          $('#default_attempts').val(data[5]);
          $('#existing_complimentary').val(data[6]);
          $('#wmat_start').val(data[9]);
          $('#wmat_end').val(data[10]);
          $('#attempts_taken').val(data[11]);
        }
      });
    });
  });
</script>

As shown in above code, I want to store $('#attempts_taken').val(data[11]); this value to a PHP variable. Any insight is appreciated.

Upvotes: 1

Views: 106

Answers (2)

Ramki
Ramki

Reputation: 472

You cannot store ajax response into a php variable.

way 1 :

You can make another ajax call.

way 2 :

you can set session.

Upvotes: 0

Bruno Pinna
Bruno Pinna

Reputation: 11

Unfortunately you can't.

PHP is server side while jQuery (JS) is client side. They are two separate layers of abstraction that interact only when the client call the server.

I don't have enough informations about what you need to do with data[11] but it seems that you have only one option: make a consecutive AJAX call to the php file that will manipulate data[11].

The consecutive AJAX call must be executed from inside the first call success callback; something like this:

success: function(result){
     // Your on success logic
     // ...
     // Prepare the object to send to the server
     var objData = {};
     objData.attemptsTaken = data[11];
     // Execute the second AJAX call to the server
     $.ajax({
         type: "POST",
         url: "second_call_destination_file.php",
         data: objData,
         success: function(result){
             // Do something on success
         },
         error: function(){
             // Do something on error
         },
         complete: function(){
             // Do something on complete (executed after success and error)
         }
}

Upvotes: 1

Related Questions