使用AJAX将输入表单值发送到PHP

时间:2016-07-28 19:48:48

标签: php ajax

经过多次尝试,我仍然遇到严重问题,使Ajax Post Method正常工作。

<form id="search_box" method="POST" action="" >
<input class="SEARCH" type="text" name="search_name" id="search_name" placeholder="Search product by name" /></form>

$(document).ready(function(e) {
$( "#search_box" ).submit(function() {
var search_name = $("#search_name").val();  
$.ajax({  
      type: "GET",
      url: "shop/pages/fetch_name.php",  
      data: "search_name=" + search_name,
      dataType: "html",
      success: function(risposta) {  
        $("#results").html(risposta);  
      },
      error: function(){
        alert("No results.");
      } 
}); 
e.preventDefault();

if(isset($_POST["search_name"])){$item_name_fetch = $_POST['search_name'];}

寻求帮助..

1 个答案:

答案 0 :(得分:1)

这有点奇怪

因为你没有在你的ajax电话中使用请求的答案.... 您需要定义“成功与错误”。

另一件事对我来说很奇怪是你的dataType,你应该选择其中一个: xml,json,script或html

你应该使用preventDefault()
https://api.jquery.com/event.preventdefault/preventDefault

json中带有asw的Ajax之一的示例:

的index.html:

<!DOCTYPE HTML>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

<div id="myform">
    <input type="text" name="search_name" id="search_name" />
    <button id="btn-send">Send</button>
</div>

<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {


        $(document).ready(function() {
            $( "#btn-send" ).bind( "click", function() {
                $.ajax({
                     url: 'myjson.php'
                    ,data: $('#search_name').serialize()
                    ,type:'POST'
                    ,dataType: 'json'
                    ,success: function(json){
                        console.log(json);
                    }
                    ,error: function(json){
                        console.log(json);
                    }
                });
            });
        });
    });
</script>

</body>
</html>

检查此页面: http://api.jquery.com/jquery.ajax/

myjson.php

<?php

print json_encode($_POST['search_name']);
相关问题