0

I am making a search engine.I want to post the data from jquery to php.

Here is my code of jQuery

<script>
$(document).keypress(function(e) {
    if(e.which == 13 && $('#textfield').val()) {
        $.post("search_result.php",
        {
          wording: $('#textfield').val()              
        }, function() {
        window.location = "search_result.php";        
        }
        );
    }
});
</script>

Here is my code of php to get the wording:

<?php include('../include/common_top.php');


        $key_word = $_POST["wording"];
        var_dump($key_word);
?>

But what I get is a null value.Please help.

4
  • If you run $('#textfield').val() in the console, what do you see? Commented Oct 3, 2017 at 6:35
  • I see the wording that I have typed. Commented Oct 3, 2017 at 6:35
  • in the php page can you check var_dump($_POST) ? Commented Oct 3, 2017 at 6:36
  • It is an empty array. Commented Oct 3, 2017 at 6:37

1 Answer 1

3

You shouldn't redirect to the PHP script. That runs it a second time, but this time with no POST parameters.

The output of the PHP script from the AJAX request will be the argument to the callback function, you can display it from there.

$(document).keypress(function(e) {
    if(e.which == 13 && $('#textfield').val()) {
        $.post("search_result.php",
            {
              wording: $('#textfield').val()              
            }, function(result) {
                $("#somediv").text(result);   
            }
        );
    }
})
Sign up to request clarification or add additional context in comments.

5 Comments

Do you mean I should use the post function to change the div content of the php file?
Yes. The point of using AJAX is so that you don't reload the page.
Thanks. What if I want to open a new php page not changing the div content?
You could just submit the form.
Thank you very much. Really appreciate your solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.