qadenza
qadenza

Reputation: 9293

Cannot get js variable inside php file

Cannot get a inside msg.php

$('#click01').click(function(){
  var a = 14;
  $.ajax({
    url : 'msg.php',
    type : 'post',
    data : {a:a}
    }).done(function() {
      window.location='msg.php';
    })
});

msg.php

var_dump($_POST['a']); // NULL, but i need `14`

Upvotes: 0

Views: 72

Answers (4)

soni pushkar
soni pushkar

Reputation: 21

// Instead of var_dump($_POST['a']) at msg.php use:- // extract($_POST); echo $a;

$('document').ready(function(){ var a = 14;

    $.ajax({
      url  : "msg.php",
      type : 'post',
      data : {a:a}
      }).done(function(data) {
          alert(data);

      });
});

Upvotes: 0

Dinei
Dinei

Reputation: 5424

Are you sure that you are checking the ajax return, and not the return of the window.location='msg.php'; ?

Try this:

$('#click01').click(function(){
  var a = 14;
  $.ajax({
    url : 'msg.php',
    type : 'POST',
    data : {'a':a},
    success: function(r) { alert(r); }
    });
});

Upvotes: 1

Christian
Christian

Reputation: 504

You have a bad concet of ajax request.

$('#click01').click(function(){
  var a = 14;
  $.ajax({
    url : 'msg.php',
    type : 'post',
    data : {a:a}
    }).done(function(data) {
      // data= var_dump($_POST['a'])
      alert(data)
    })
});

In var data you have the result of ajax request, but if you redirect to msg.php no have the variable

Upvotes: 1

putvande
putvande

Reputation: 15213

You are getting null because after the AJAX call is done you send the user to msg.php where $_POST is empty again.

When you do :

    $('#click01').click(function () {
     var a = 14;
     $.ajax({
         url: 'msg.php',
         type: 'post',
         data: {
             a: a
         }
     }).done(function (data) {
         alert(data);
     })
 });

You will see it works and you get 14.

I see no good reason to first use AJAX to POST something and then on success send the user to that same page.

Upvotes: 4

Related Questions