Dawid Wiewiór
Dawid Wiewiór

Reputation: 41

Ajax + Json + PHP $_POST don't return values

I am trying to get values from my register() function. I have used var_dump($_POST['nick']); in ajax/register.php, but it shows null

<section id=signup>
  <label>Nick:</label> 
  <input id=nick maxlength=20><br>

  <label>Email:</label> 
  <input id=email maxlength=40><br>

  <label>Hasło:</label> 
  <input id=pass  maxlength=20 type=password><br>

  <label>Potwierdź hasło:</label> 
  <input id=pass2  maxlength=20 type=password><br>

  <button onclick="register()">Załóż konto</button>
</section>
function register() {
  if ($('#pass').val() != $('#pass2').val()) 
    myAlert('Niepoprawne hasło'); 
  else
    $.ajax({
      type: "POST",
      dataType: "JSON",
      url: "/ajax/register.php",
      data: { 
        n: $('#nick').val(), 
        e: $('#email').val(), 
        p: sha1(SALT + $('#pass').val()) 
      },
      headers: { 
        "cache-control": "no-cache"
      }
    }).done(function(d) {
      if (d.e != 'ok') 
        myAlert(d.e);      
      else
        window.location.href = "/";
    });
}

Upvotes: 1

Views: 245

Answers (3)

RiggsFolly
RiggsFolly

Reputation: 94682

You are telling the AJAX call you are going to get JSON back from the PHP, but you are not sending JSON back from the PHP when you use var_dump($_POST['nick']); Also you are passing the value on a key of n: and not nick

So in PHP replace this

var_dump($_POST['nick']);

with

echo json_encode($_POST);

This will return all the $_POST array back to the javascript

And in the javascript replace

.done(function(d) {
  if (d.e != 'ok') 
    myAlert(d.e);      
  else
    window.location.href = "/";

with

.done(function(d) {
    // I dont think you set e to 'ok' anywhere
  //if (d.e != 'ok') 
    myAlert(d.e);
    myAlert(d.n);
    myAlert(d.p);
}

Upvotes: 3

Jouby
Jouby

Reputation: 2471

You haven't any data named "nick":

data: { n: $('#nick').val(), e:$('#email').val(), p:sha1(SALT+$('#pass').val()) }

In $_POST, you got n, e and p only.

Use var_dump($_POST['n']) in ajax/register.php, to get your #nick element value.

Upvotes: 3

B. Desai
B. Desai

Reputation: 16436

You are passing value of nick in n so you have to get value from n

In ajax/register.php do

var_dump($_POST['n']);

Upvotes: 3

Related Questions