0

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?

2
  • What is the error in console?? Commented Feb 2, 2017 at 10:01
  • Undefined index: name in E:\xampp\htdocs\demo\jquery-ajax-hello.php on line 2 Hello , How are you ? Commented Feb 2, 2017 at 10:02

4 Answers 4

2

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

data: {
    name: $("#name").val()
},
Sign up to request clarification or add additional context in comments.

3 Comments

try removing contentType, it should really just pass as a www/encode thing.
thanks, i removed contentType and that solved my problem. Thank you.
jQuery's ajax doesn't actually pass it as a json object (as one might infer), it passes it as a query string. See more on their website.
1

JQuery Ajax

Form data

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

Jquery section

$(function() {
$("#submit").click(function() {
  var name = $('#name').val();
 $.ajax({
  url : 'success.php',
  method: 'POST',
  data : {name:name},
  success : function(res) {
     $('#message').append(res);
   }
});
});
});

success.php

<?php 
 $name =  $_POST['name'];
 echo "Hello Mr ".$name ;
?>

Comments

0

change data property to

 data: {name: $("#name").val() }

and it would work fine

Comments

0

change data to:

data: { name: $("#name").val() }

because data must be an object having key : value pair in it

In your case:

data: '{"name":"' + $("#name").val() + '"}'

{} is wrapped with single quotes. Remove them.

2 Comments

the php page is not able to fetch the "name" value, that's the problem?
In that case data : name do no have the value in it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.