AJAX发布到PHP文件不成功返回数据

时间:2017-09-23 19:32:55

标签: php ajax forms

这是我想要完成的流程:

表格已完成 - >使用数据发送到PHP文件的数据 - > PHP文件采用数据,查询API - > PHP文件然后将查询结果作为echo返回到原始页面。

此往返时间应为10秒左右。这是我的表单AJAXPHP文件。

表格

<form id="query_form">
    <input type="text" id="query_input" name="query_input"  required>
    <button id="send_btn" type="submit" name="send_query" value="Submit Request">
</form>

AJAX

<script type="text/javascript">
$(document).on("click", "button[id='send_btn']", function(e){ 
    e.preventDefault(); // Prevents any default actions by clicking submit in a form.

    var query = $("#query_input").val(); // Gets the value of an input


    $.ajax({
                type: "POST",
                url: "run.php",
                data: {query:query},
                success: function(r){ alert(r); }
            });

});
</script>

PHP

<?php

require('RestClient.php');
$term = "";

    if(isset($_POST['query'])){
        $term = $_POST['query']
        try {

        $client = new RestClient('https://api.dataforseo.com/', null, '#########', '###########');

        $post_array = array("language" => "en","key" => $term); // This is the term to search, correct?

        $sv_post_result = $client->post('v2/kwrd_sv', array('data' => $post_array));

        $search_volume = $sv_post_result["results"][0]['sv'];

         echo "<div id='results_div'>
            <table id='results_table'>
                <tr class='results_table_row'>
                    <td id='SEO_Search_Volume_Cell'>
                       $search_volume <span>Approximate Number Of Searches Per Month</span>
                    </td>
                </tr>
            </table>
       </div>";

    } catch (RestClientException $e) {
        echo "\n";
        print "HTTP code: {$e->getHttpCode()}\n";
        print "Error code: {$e->getCode()}\n";
        print "Message: {$e->getMessage()}\n";
        print  $e->getTraceAsString();
        echo "\n";
        echo "An Error Has Occured, Please Try Again Later";
        exit();
        }
    }

&GT;

显然,数据echo'返回需要与表单显示在同一页面上,但没有任何内容返回。为什么会这样?

1 个答案:

答案 0 :(得分:0)

尝试以“字符串”格式发布数据,例如

var query = $("#query_input").val(); //获取输入值

var queryString = 'query='+ query;然后在您的$ .ajax调用中使用它:data: queryString,

使用$ _POST ['query']

获取值