1

I want to get all of array value with ajax which that is coming from MySQL. I can't get all of result. I can get only 1 result.

My JQuery codes are:

$("input.input-search").keyup(function(){
    var name = $(this).val();
    if(name !='')
    {
        $.ajax({
            type: 'post',
            url: 'ajax.php?bol=search',
            data: {'name':name},
            dataType: 'json',
                success: function(val)
                {    
                     x = val.length;
                     for (i = 1; i<=x; i++){
                        $(".search-result").html(val[i].user+' * '+x);
                    }
                },
                error: function(name){
                $(".search-result").html("Nəticə yoxdur...");
                }
            });
    }
});

PHP Codes are:

case "search":
$name = trim($_POST['name']);
$q = mysql_query("SELECT * FROM `users` WHERE `user` LIKE '%".$name."%' ORDER by id;");
if(mysql_affected_rows() > 0){
    while($arr = mysql_fetch_array($q)){
        $array[] = $arr;
}
    echo json_encode($array);
}
break;
4

2 Answers 2

5

It's simple. You are overwriting your elements HTML content every time your loop runs. With the jQuery

.html("...")

method you set a new content for your selected element every time your loop runs.

So use

.append('...')

instead.

Of course at the very beginning of your success - method empty your element with

.html("");
Sign up to request clarification or add additional context in comments.

5 Comments

Ok i got all of result. But when i keyup i get new result under the other.
Yes. Thanks. it was ok about getting all result. But now when i keyup then the result is written until count result. Example: i want to search users Like Togrul name. and i have 2 users like togrul. 1. Togrul. 2 Togrul2. When i write "T" it is written under to other Togrul and Togrul2. so i write "To" and it writes the results again under the result.
Maybe just place the call to .html('') at the very beginning of your .keyup() - method.
.html(""); It did not happen.
Yes. yes. first i used in after $(".search-result").keyup(... so i used in success: like $(".search-result").html('');
4

If your query is only returning 2 rows, the problem lies in your Javascript for loop. You're starting at 1 when the array index starts at 0. Try this:

for (i = 0; i <= x; i++) {...}

1 Comment

first of all i wrote i=0 but when i can't get result i changed that maybe the ptoblem is from this.

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.