0

When I submit a form my information is passed into a PHP function that queries an external database and returns a set of results. When the form is completed, I have the following function run:

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

This hides the form and displays another div that indicated the query has been submitted and will return shortly. When it does return, the analysis div is supposed to hide, and the results div is supposed to appear. However, when the function actually DOES return the values, the page seems to refresh. As a result I am left with everything visible, instead of the results div only.

My best guess is this is caused by the form actually being completed and, as a result, the PHP page refreshes, which would cause the issue.

I have looked into methods of stopping php pages from refreshing on submit via AJAX, but this potential solution has proved ineffective for me.

Any ideas?

More Code

<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>

The function in run.php that needs to be called with an argument is called 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;
}




  ?>
Ethan
  • 1,905
  • 2
  • 21
  • 50
  • 1
    Could you show something about your AJAX code ? – shanechiu Sep 23 '17 at 03:04
  • @shanechiu Please check new info above. – Ethan Sep 23 '17 at 03:40
  • Try removing the `method="post"` from your form tag. – parker_codes Sep 23 '17 at 03:42
  • @GoogleMac no dice. – Ethan Sep 23 '17 at 03:46
  • Try using `type="button"` instead of `submit` then handle the `onSubmit` within `onClick` event. – FrozenFire Sep 23 '17 at 03:47
  • Change the input `type="submit"` to `type="button"`. – parker_codes Sep 23 '17 at 03:49
  • The biggest issue I am having is getting the returned data back from the PHP function, I can build the workaround where I pull the value of the form when the button is submitted, but I will still be stuck exactly where I am now. – Ethan Sep 23 '17 at 03:54
  • then you need to handle the AJAX response on success. https://stackoverflow.com/questions/1218245/jquery-submit-form-and-then-show-results-in-an-existing-div – FrozenFire Sep 23 '17 at 04:00
  • Does AJAX success have a timeout? It can take around 10 seconds before the data can be echoed back. Not sure why nothing is coming back to the AJAX function – Ethan Sep 23 '17 at 04:41
  • Yes, it does. One way is to use web sockets (best but hardest and then you wouldn't need ajax), or have an ajax function that repeats every few seconds until it returns true/ready. Then you stop the timer loop and call your main ajax function. – parker_codes Sep 23 '17 at 13:13

1 Answers1

0

Change this to a button:

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

And then use this as your jQuery/JavaScript code:

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

The PHP code:

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

?>
  • The problem at this point is getting the PHP file to actually send data back--I have no way of checking even if the variables are passed correctly as `echo` on the `PHP` side isn't working – Ethan Sep 23 '17 at 04:54
  • @Ethan - Do you have the PHP file? Something like: – Bradly Hale Sep 23 '17 at 04:57
  • Added the file to the question, for your reference the documentation for the structure of the file can be found here: https://docs.dataforseo.com/#search-volume-for-keyword – Ethan Sep 23 '17 at 05:01
  • Thanks for that. I added the PHP code. Now give it a shot? – Bradly Hale Sep 23 '17 at 05:23
  • I see where the $_POST['qi'] comes in, but not $_POST['pi']. Aren't you simply using the API to return the results based on the search term? If so, then we'd only need one variable posted to the php file, as far as I am seeing... – Bradly Hale Sep 23 '17 at 05:25
  • I tried this code and nothing is being echoed back, I'm almost certain it is because the AJAX `success` function times out before the data can be returned – Ethan Sep 23 '17 at 18:07
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/155165/discussion-between-bradly-hale-and-ethan). – Bradly Hale Sep 23 '17 at 18:22