1

I am trying for the first time to make a POST response in a sample using search suggestions. Here is what I have so far:

$('#search').keyup(function() {
    var searchField = $('#search').val();
    if (searchField.length > 1) {

        $.ajax({
            url : "search_query.php",
            type : "POST",
            dataType: "json",  
            data : {
                query : searchField
            },
            success : function(data) {
                var output = '<div>';
                $.each(data, function(key, val) {
                    if (val.item.search(searchField) != -1) {
                        output += '<p><a href="#">' + val.item + '</a></p>';
                    };
                });
                $('#search_results').html(output);          
            }
        })
    };
});

Can anyone show me how to properly parse a JSON response?

5
  • There is no "in" in this code. Is there other code that uses "in", or is that in fact the response from the POST? Commented Jul 28, 2013 at 20:08
  • @Paul Sorry, I had written the wrong error message down. Commented Jul 28, 2013 at 20:11
  • OK. Can you click "edit" and post the correct error messages? Commented Jul 28, 2013 at 20:12
  • I deleted it several minutes back. The error message was output is not defined - which was the issue. Commented Jul 28, 2013 at 20:14
  • OK. guess you solved it then. Commented Jul 28, 2013 at 20:15

1 Answer 1

4

You haven't defined output as a variable, the below should work.

$('#search').keyup(function() {
    var searchField = $('#search').val();
    if (searchField.length > 1) {

        $.ajax({
            url : "search_query.php",
                    dataType : "json",
            type : "POST",
            data : {
                query : searchField
            },
            success : function(data) {
                var output = '';
                $.each(data, function(key, val) {
                    if (val.item.search(searchField) != -1) {
                        output += '<p><a href="#">' + val.item + '</a></p>';
                    };
                });

            }
        })
    };
});
Sign up to request clarification or add additional context in comments.

Comments

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.