doutang3760
doutang3760
2017-02-02 09:59

jQuery AJAX和PHP没有获取数据值

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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

4条回答

  • dsilhx5830 dsilhx5830 4年前

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

    data: {
        name: $("#name").val()
    },
    
    点赞 评论 复制链接分享
  • doupuchao4256 doupuchao4256 4年前

    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 ;
    ?>
    
    点赞 评论 复制链接分享
  • dtrotfd1012 dtrotfd1012 4年前

    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.

    点赞 评论 复制链接分享
  • dongzhenbi8919 dongzhenbi8919 4年前

    change data property to

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

    and it would work fine

    点赞 评论 复制链接分享

为你推荐