0

this is the flow I am trying to accomplish:

Form completed -> Data Sent to PHP File With Data -> PHP File Takes Data, Queries API -> PHP File Then Returns Query Results back to Original Page as an echo.

The round trip time for this should be around 10 seconds. Here is my form, AJAX, and PHP file.

Form

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

?>

Obviously the data echo'd back needs to appear on the same page as the form, yet nothing comes back. Why would this be?

Ethan
  • 1,905
  • 2
  • 21
  • 50
  • `header('Content-Type: application/json');` needs to be before your output – Jaquarh Sep 23 '17 at 19:34
  • Can you demonstrate how? Also I have just determined that the values in the form are either a) not being submitted through ajax or b) not being received on the php file. – Ethan Sep 23 '17 at 19:36
  • You need to `json_encode()` the output for javascript to understand it and return it as a content type `application/json` - [see this example](https://3v4l.org/N6leg) – Jaquarh Sep 23 '17 at 19:38
  • @KDOT You're assuming the OP is sending a JSON. His code seems to be sending back HTML or plain text -- which is also ok. And the `header()` is not necessarily mandatory. – Mikey Sep 23 '17 at 19:39
  • @Mikey I suppose I am, `data: {query:query},`, I suspect the main issue here is the PHP file is not able to actually access the `$_POST` data, as there is no indication of an actual query being made to the API. – Ethan Sep 23 '17 at 19:46
  • Don't suspect :) Put some debug statements e.g. `console.log()` or `alert()` in your code. Open your browser's developer tool, check if there are any errors, and monitor the request with e.g. [Chrome's Network Tab](https://developers.google.com/web/tools/chrome-devtools/network-performance/reference) that gets sent when you click on the button. Also turn on [PHP error reporting](https://stackoverflow.com/a/5438125/1022914). – Mikey Sep 23 '17 at 19:49
  • @Mikey No errors in console at any point, alert indicates the values from the form are being pulled and submitted, but when I check my API I can see that no requests from the `PHP` file have been made, and if I was to put `echo "RUNNING";` as the first line in the PHP file nothing comes back. No problems with permissions on any of the files. – Ethan Sep 23 '17 at 19:56
  • You turned on error reporting right? Start simple. Comment out everything in your PHP and just leave an `echo` statement. If you submit and get back something, then your problem has something to do with your PHP. Then start uncommenting things one by one. Otherwise, it has something to do with your JS. You're positive that a POST request with status 200 is being sent to `run.php`? An entry should show in your browser's developer tool. There's not much anyone can help as it comes down to debugging and finding where it is failing. I don't see anything in your code that stands out as wrong. – Mikey Sep 23 '17 at 20:09
  • @Mikey leaving the `echo` statement results in an alert indicating the php has been called and is running. I am positive a code 200 is being sent to `run.php`. Maybe `success:` isn't the right choice? After all, it does take some time for the PHP file to query the api. Could a `success:` timeout come into play? That would make sense that nothing is returned because the API hasn't even had the chance to respond yet... hmm – Ethan Sep 23 '17 at 20:29

1 Answers1

0

try posting the data in a 'string' format, e.g.

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

var queryString = 'query='+ query; and then use it in your $.ajax call with: data: queryString,

pick-up the value with $_POST['query']

lovelace
  • 1,195
  • 1
  • 7
  • 10