2

I have the following jQuery:

$(document).ready(function() {
    $('input[type="submit"]').click(function() {
        event.preventDefault();

        var email = $('.email').val();

        $.ajax({
            type: "POST",
            url: "register_email.php",
            data: JSON.stringify({ "email": email }),
            dataType: "json",
            contentType: "application/json",
            success: function(data) {
                alert(data);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                alert(textStatus + " " + errorThrown);
            }
        });
    });
});

The email variable is definitely set, I can alert it out.

However, when I get to the PHP, this is my script:

<?php
    $db = new mysqli("localhost", "...", "...", "...");

    if ($db->connect_error) {
        echo "Could not connect to database.";
        exit;
    }
    else {
        $emerd = json_decode($_POST["email"]);

        $db->query("INSERT INTO emails (email) VALUES (' " . $emerd . "')");

        echo $emerd;
    }
?>

It always alerts "null" back to me. Why won't it understand what I'm POSTing?

Doug Smith
  • 29,668
  • 57
  • 204
  • 388
  • You don't need `JSON.stringify({ "email": email }),`.. just `{'email': email}` should be good enough. – Selvakumar Arumugam Aug 16 '13 at 18:47
  • You don't need the `json_decode()` on the php side either – Gerald Schneider Aug 16 '13 at 18:47
  • See the answers [here](http://stackoverflow.com/questions/4105211/jquery-ajax-post-to-php) for some ways to handle it. – Joe Enos Aug 16 '13 at 18:47
  • what's the output of `json_decode($_POST)`? It seems to me you're trying to access the email post variable which doesn't exist as you decided to post json not urlencoded – Joe Minichino Aug 16 '13 at 18:47
  • @JoeMinichino I get this, oddly enough: http://i.imgur.com/RSUkjhZ.png I don't understand why, http://syllableapp.com/test/register_email.php is accessible. – Doug Smith Aug 16 '13 at 18:51
  • @Vega This guy said I needed to: http://stackoverflow.com/questions/18279472/why-when-i-submit-the-value-of-the-text-box-in-ajax-to-a-php-script-does-it-fail – Doug Smith Aug 16 '13 at 18:51
  • 1
    @DougSmith Just keep in mind that there's more than one way to do a post. If you really need to post JSON, then you need to properly stringify it, and deal with it as JSON on the server. But if you've got simple data like just a single email address, you can post it as traditional form-encoded key-value pairs. Watch your raw request (browser dev tools or Fiddler) to see what your post value really is. Something like `email=abc%40example.com` is probably perfect for your scenario, so you can leave JSON out of the request completely, then reading the post in PHP is much easier. – Joe Enos Aug 16 '13 at 20:10
  • 1
    @DougSmith The default post for URL-encoded would be called like: `jQuery.ajax({type:"post",url:"someurl",data:{email:"abc@example.com"}}` - note that the `data` is not stringified and you're not giving it a JSON content type. This will produce the post value like I have in my previous comment. – Joe Enos Aug 16 '13 at 20:11

3 Answers3

1

Put your email field in a form like this

<form id="myform"><input type="text" name="email"></form>

then use jQuery to serialize it

$('#myform").on('submit', function (e) {
    e.preventDefault();//this keeps the form submission from refreshing the page
   var data = $(this).serialize();
    $.ajax({
      url: '',
      data: data,  //assign the data like this
      type: "post",
      success: function (response){

      },
      ....other params 
   })
})

this is the best way to do this IMHO and I think it is the recommended way for this kind of thing. No need to encode to JSON and then decode the JSON on the server side.

Subtubes
  • 15,851
  • 22
  • 70
  • 105
0

You are not passing a json string back to your JavaScript. You should do:

echo json_encode(array(
   "email" => $emerd
));

Besides that, you don't need to:

  • Use json_decode on your $_POST["email"] in php
  • Set the contentType option or JSON.stringify your data object in your $.ajax request
losnir
  • 1,141
  • 9
  • 14
0

Don't encode it to array, neither the quotes around "email" are needed.

 $.ajax({
        type: "POST",
        url: "register_email.php",
        data: { email: email, contact:$('#contact').val() }, //no problem even if you have more than one variables.
        success: function(data) {
            alert(data);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert(textStatus + " " + errorThrown);
        }
    });

On server side,

$emerd = $_POST["email"];
Optimus Prime
  • 6,817
  • 5
  • 32
  • 60
  • This guy said I needed the quotes and stringify though. http://stackoverflow.com/questions/18279472/why-when-i-submit-the-value-of-the-text-box-in-ajax-to-a-php-script-does-it-fail – Doug Smith Aug 16 '13 at 18:55