Kobe Bryan Kobe Bryan - 4 years ago 137
PHP Question

How to catch data sent by Ajax using PHP

Would like to ask for a help. I'm having an issue about getting the right data that I wanted. Maybe there's something lack in my code. I always get null.

I didn't received any error on the console tab.

Here's my ajax



$(document).ready(function() {
$(".fsubmit").click(function() {
var emailval = $("#email").val().trim();

$.ajax({
url: '/test.php',
type: 'POST',
dataType: 'json',
data: 'email='+emailval,
success: function(data) {
console.log(data);
return false;
}
});
});
});





Maybe you could help me fix the PHP. Still learning some stuff. Kindly put some details for lesson please.

Here's my PHP code

<?php

$date = new DateTime();
$datelog = $date->format('d.m.Y h:i:s');
$data = $_POST['data'];

$message = '[' . $datelog . '] - email: ' . json_encode($data);

echo($message);
?>


I appreciate your answer!

Answer Source

Not allowed to comment. Here's a little edit to Mohammad's answer. isset() returns true for blank form fields. Use empty() instead.

this runs in my system ..

ajax call

    $(document).ready(function(e) {
        $(".fsubmit").click(function() {  
            e.preventDefault();
            console.log("whooowww");
            var emailval = $("#email").val().trim();

            $.ajax({
                url: '/arrayfilter.php',
                type: 'POST',
                dataType: 'json',
                data: 'email='+emailval,
                success: function(data) {   
                    console.log(data);
                    return false;
                }
            });
        });
    });

html form

<form>
    <input type="text" name="user-input" id="email"/>
    <button type="submit">Send</button>
</form>

php

if($_POST){
    if(!empty($_POST['email']))
        echo "$_POST[email]";
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download