yogihosting yogihosting - 4 years ago 158
Ajax Question

The jQuery AJAX and PHP not fetching data values

I am trying to fetch the values of the data variable passed with jQuery AJAX to a php page. How to solve it?

Below is the HTML page code:

<input id="name" placeholder="Enter your name." />
<button id="submit">Submit</button>
<div id="message"></div>


On the button click this jQuery AJAX calls a php page:

$.ajax({
type: "POST",
url: "jquery-ajax-hello.php",
contentType: "application/json; charset=utf-8",
data: '{"name":"' + $("#name").val() + '"}',
success: function (result, status, xhr) {
$("#message").html(result);
},
error: function (xhr, status, error) {
$("#message").html("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
}
});


The PHP Page code is:

<?php
$name = $_POST['name'];
echo "Hello ".$name.", How are you ?";
?>


In the php page I am not able to fetch the data varaible 'name' value?

Please help?

Answer Source

Your data should be an object, what you're passing is a string, so it should be

data: {
    name: $("#name").val()
},
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download