【问题标题】:How To Preserve Webpage Styling After PHP Function Returns ValuesPHP函数返回值后如何保留网页样式
【发布时间】:2018-03-04 16:08:23
【问题描述】:

当我提交表单时,我的信息被传递到一个 PHP 函数中,该函数查询外部数据库并返回一组结果。表单完成后,我运行以下函数:

<script>
function transitions(){
$("#form_holder").fadeToggle();
$("#Analyzing").fadeToggle();
}
</script>

这会隐藏表单并显示另一个表示查询已提交并将很快返回的 div。当它返回时,分析 div 应该隐藏,结果 div 应该出现。但是,当函数确实返回值时,页面似乎会刷新。结果,我留下了所有可见的东西,而不仅仅是结果 div。

我的最佳猜测是,这是由于表单实际已完成,因此 PHP 页面刷新,这将导致问题。

我已经研究过阻止 php 页面在通过 AJAX 提交时刷新的方法,但这种潜在的解决方案对我来说是无效的。

有什么想法吗?

更多代码

<form id="query_form" name="query_form" method="POST" onsubmit="transitions()">
    <input type="text" id="query_input" name="query_input"  required><br>
    <input type="number" min="0" step="1" name="profit_input" id="profit_input" required><br>
    <input id="send_btn" type="submit" name="send_query" value="Submit Request">
</form>

     <script>
     $("#query_form").ajaxForm({url: 'run.php', type: 'post',data: {query: '#query_input'},success: function(output) {
                      alert(output);
                  }});
    </script>

run.php中需要带参数调用的函数称为QueryData($term)

Run.php

<?php
require('RestClient.php');
$term = $_POST['qi'];
$profit = $_POST['pi'];
    try {

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

    $post_array[] = array(
    "language" => "en",
    "key" => $test
    );



    $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>
";


} 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();
}

    $client = null;
}




  ?>

【问题讨论】:

  • 您能介绍一下您的 AJAX 代码吗?
  • @shanechiu 请检查上面的新信息。
  • 尝试从您的表单标签中删除method="post"
  • @GoogleMac 没有骰子。
  • 尝试使用type="button" 代替submit 然后在onClick 事件中处理onSubmit

标签: javascript php jquery html


【解决方案1】:

把它改成一个按钮:

<button id="send_btn" type="submit" name="send_query">Submit</button>

然后将其用作您的 jQuery/JavaScript 代码:

$(document).on("click", "button[id='send_btn']", function(e){ 
    e.preventDefault(); // Prevents any default actions by clicking submit in a form, e.g. page reloading, etc.
    $("#form_holder").fadeOut(); // Fades out the form.
    var qi = $("#query_input").val(); // Gets the value of an input
    var pi = $("#profit_input").val(); // Gets the value of an input 
    $.post( "https://www.yourwebsite.com/run.php", {qi:qi,pi:pi}) // Posts the values
        .done(function(data) { // if function is successful, it will take the data, add it to the analysis div, and fade it in.
            $("#Analyzing").html(data).fadeIn(); // Be sure the css for this div is set to display:none initially when the page is loaded.
        })
        .fail(function() {
             alert("The connection could not be established. Please try again.");
             $("#form_holder").fadeIn(); // in case connection failure, form is reloaded back in to view.
        });
});

PHP 代码:

<?php

    require('RestClient.php');

    // Get query input. If it is empty, echo an error.

    if (empty($_POST['qi'])) {

         echo "<p>No term was given. Please try again.</p>";

         echo "<button id='gobacktoform'>Try again</button>";

         exit;  

    } else {

        $term = $_POST['qi'];

    }

 // Get profit input. If it is empty, echo an error.

 if (empty($_POST['pi'])) {

     echo "No profit was given. Please try again.";

     echo "<button id='gobacktoform'>Try again</button>";

     exit;  

 } else {

     $profit = $_POST['pi'];

}

// If both $term and $profit are NOT empty, fetch API results.

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'>";
        echo "<table id='results_table'>";
            echo "<tr class='results_table_row'>";
                echo "<td id='SEO_Search_Volume_Cell'>";
                    echo "$search_volume <span>Approximate Number Of Searches Per Month</span>";
                echo "</td>";
            echo "</tr>";
        echo "</table>";
    echo "</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();
} 

?>

【讨论】:

  • 此时的问题是让 PHP 文件实际发回数据——即使变量正确传递为 echoPHP 侧,我也无法检查不工作
  • @Ethan - 你有 PHP 文件吗?类似于:
  • 将文件添加到问题中,供您参考文件结构的文档可以在这里找到:docs.dataforseo.com/#search-volume-for-keyword
  • 谢谢。我添加了 PHP 代码。现在试一试?
  • 我看到了 $_POST['qi'] 的来源,但没有看到 $_POST['pi']。你不是简单地使用API​​根据搜索词返回结果吗?如果是这样,那么我们只需要将一个变量发布到 php 文件中,就我所见...
猜你喜欢
  • 2020-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多