0

I'm trying to echo a php variable from an Ajax request but the data is being returned as "null" and im not sure why. Here is my post request:

    jQuery.ajax({
        url:'/api/registerLoginViaFacebook.php',
        data: {'test1':'test1','test2':'test2'},
        type:'POST',
        success: function(result) {
            jQuery('header').html(result);
        }
    })   

The data i'm posting here is just test data. As i'm having the same problem posting the real data. Here is the registerLoginViaFacebook.php file:

<?php

   echo "<p>hey</p>";
   echo "<p>".json_encode($data)."</p>";

?>

the html thats getting inserted in the <header> is

hey

null

suggesting that the data i specified was never sent - at least that's what I make of it. I tried including $_REQUEST['data']; at the start of the file as per some suggestions I found on here but still no joy. Where have I gone wrong?
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
  • What is populating `$data`? Just for grins set `$data = 'foo';` in your PHP script and run again. – Jay Blanchard Nov 22 '16 at 17:58
  • 1
    Have you watched the AJAX request / response in the browser's developer tools? Have you included the jQuery library in the project? Are there any errors reported? Are you running this on a web-server? – Jay Blanchard Nov 22 '16 at 17:59
  • `$data` isn't being initialised in your PHP code. Try to echo `$_POST['test1']` or `$_POST['test2']` – Jordi Nebot Nov 22 '16 at 18:01
  • Possible duplicate of [receive json post with php](http://stackoverflow.com/questions/18866571/receive-json-post-with-php) – Joao Polo Nov 22 '16 at 18:03
  • I thought you had to use a variable in the post? `data:{test1:'test1', test2:'test2'}` – ntgCleaner Nov 22 '16 at 18:04
  • Do yourself a favor, simply place a `print_r($_POST)` or `var_dump($_POST)` in the PHP page which receives the form submission. Fill out your form, submit and look closely at the data printed to the screen. Familiarize yourself with how form data is posted to scripts, including what gets passed and what doesn't. – Jay Blanchard Nov 22 '16 at 18:04
  • Php requires an extra step to read json value. Take a look at referenced article – Joao Polo Nov 22 '16 at 18:04
  • Hey Jay print_r revealed what I wanted! i think setting $data= $_POST would be the correct answer if you wanted to post that mate? – Benjamin Liger Nov 22 '16 at 18:12

2 Answers2

0

On the PHP end, try using $_POST['test1'] and $_POST['test2']. This should contain the data you sent via jQuery.

NikxDa
  • 4,137
  • 1
  • 26
  • 48
0

You need to set $data in your PHP script. Since you are sending the information via POST you can do this:

$data = $_POST;
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119