Zip
Zip

Reputation: 5592

jQuery JSON returned from PHP

I have a simple HTML form where user can search a word from database and PHP return result as a JSON object if the word is in database.

Strange thing is that a JSON object is returned for a word that is in database when user searches by clicking on a button instead of pressing enter key. I have the following two functions to deal with either when user press enter key or click on the button to search. How to improve my code to get the JSON object from PHP when user searches by pressing enter key after they have typed the word in text field?

$('#word-submit').on('click', function() {
  var word = $('#word').val();
  $.post('ajax/name.php', {word: word}, function(data) {
    var obj = jQuery.parseJSON(data);
    console.log(obj); //I see the object in Chrome console log.
  });

});

$('#word').keypress(function(e) {
  if (e.which == 13) {
    var word = $('#word').val();
    $.post('ajax/name.php', {word: word}, function(data) {
      var obj = jQuery.parseJSON(data);
      console.log(obj); //No object is return here. Why? May be something is wrong in my code.
    });
  }
});
<html>

<head>
  <title>Welcome</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>
  <div id="container">
    <form>
      <input type="text" id="word">
      <input type="button" id="word-submit" value="Search">

    </form>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script src="js/global.js" charset="UTF-8"></script>
</body>

</html>

PHP script works just fine. So I am not pasting it here.

Upvotes: 1

Views: 66

Answers (2)

Phil
Phil

Reputation: 165068

The problem is most likely that your form is submitting. I would just add one listener on the form's submit event which should handle clicking the button and hitting Enter, eg

$(form).on('submit', function(e) {
    e.preventDefault(); // don't submit
    var word = $('#word').val();
    $.post('ajax/name.php', {word: word}, function(data) {
        console.log(data);
    }, 'json');
});

Ideally, you shouldn't have to parse the JSON or even tell jQuery the response data type (see 'json' arg above). Make sure your PHP script has something like this...

header('Content-type: application/json');
echo json_encode($someDataArrayOrObject);
exit;

In order to make the button work with the above, change its type to submit, ie

<input type="submit" id="word-submit" value="Search">

Upvotes: 1

rezashamdani
rezashamdani

Reputation: 577

button work because it prevent the form auto submit / reload it self.

pressing enter key on that textbox causing the form to submit and then reload it self without even triggering the $('#word').keypress(function(e)).

Upvotes: 0

Related Questions