2

i know that this question is a bit childish but i am unable to find the correct solution to this problem...

i am using jquery and ajax call to user search functionality in website with php returning json objects...

when i search users using php file, if the json return is only one array, the jquery prints it on the screen, but when multiple results are returned, i don't know to print them out....

here are the results returned from the php:

{"search":"10 
junaid 
saleem 
[email protected] 

"}{"search":"13 
zzz 
aaa 
[email protected] 

"}

and here is the jquery webpage:

<?php 
session_start();
require("secure_scripts/getusers.php");
require("secure_scripts/getdp.php");
require("secure_scripts/getusersinfo.php");
if(!isset($_SESSION['id'])){
    header("location: index.php");
}else{
    $zxcv_lgn = base64_encode($_SESSION['id']);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Welcome <?php echo getusers("first_name"); ?> | Addressbook.com</title>
    <script src="jquery.js" type="text/javascript" ></script>
    <link rel="stylesheet" href="style.css">
    <script type="text/javascript">
         $(document).ready(function(){
                $("#search_button").click(function(){
                    $("#search_button").click(function(){ $("#console_loader").hide(); });
                    $("#console_loader").fadeIn("slow").html("<img src='images/ajax-loader.gif' id='ajax-loader' />");
                    var send = $("#search").val();
                    $.ajax({
                        type: "POST",
                        url: "secure_scripts/search_users.php",
                        data: {search: send},
                        dataType: "json",
                        success: function(msg){
                            $("#ajax-loader").fadeOut("slow", function(){
                                $("#console_loader img").remove();
                                $("#console_loader").fadeIn("slow").html(msg.search);
                            });
                        }
                    });

                });
            });

    </script>

</head>
<body>
    <div id="header">
        <p><a href="index.php"><img src="images/header_logo.png" /><span>AddressBook™</span></a></p>


    </div>

    <div id="wrapper" align="center">

        <div id="main">
            <div id="content">
                <div id="top_nav">
                    <div class="userinfo"><span class="user_title">Welcome <?php echo getusers("first_name")." ".getusers("last_name"); ?></span></div>
                    <div class="search">
                        <form onsubmit="return false" id="search_form">
                            <input type="text" name="search" class="search_box" id="search" placeholder="Type in to search...">
                            <input type="button" id="search_button" class="sea" name="search_submit"value="search">
                        </form>
                    </div>
                </div>
                <div id="left_nav">
                    <div id="dp"><img src="<?php echo getdp(); ?>"></div>
                    <div class="left_nav_links">Profile</div>
                    <div class="left_nav_links">Contacts</div>
                    <div class="left_nav_links">Settings</div>
                    <div class="left_nav_links">privacy</div>
                    <div class="left_nav_links">logout</div>
                </div>
                <div id="console">
                    <div id="console_top_nav">Your Contacts:</div>
                    <div id="console_content">
                        <div id="console_loader" style="display: none;"></div>
                    </div>
                    </div>
                </div>
            </div>

        </div>

        <div id="footer">
            <div id="links"><ul><li><a href="index.php">Home</a></li><li><a href="about">About</a></li><li><a href="contact">Contact</a></li></ul></div>
            <div id="copyrights">&copy; 2014 Addressbook.com All Rights Reserved</div>
        </div>  

    </div>
</body>
</html>

whenevery only one object is returned from php, like:

{"search":"13 
zzz 
aaa 
[email protected] 

"}

it works perfectly, but not with multiple json objects....

thanks in advance!

3
  • Are you sure you are returning valid json? You should json_encode() and echo your results at the end once (for example an array that contains everything you want to return), not do that multiple times. Commented Oct 8, 2014 at 14:23
  • 2
    In your success function, try putting then entire response inside of $.each so you'll run the function for each response, not just the first. Something like this Commented Oct 8, 2014 at 14:25
  • +1 @CodyReichert - $.each() will cycle through your json objects and allow you to work with each one instead of just returning the first one. Commented Oct 8, 2014 at 14:30

2 Answers 2

1

You need to use jQuery's .each() method, like this:

$(document).ready(function(){
    $("#search_button").click(function(){
        $("#search_button").click(function(){ $("#console_loader").hide(); });
        $("#console_loader").fadeIn("slow").html("<img src='images/ajax-loader.gif' id='ajax-loader' />");
        var send = $("#search").val();
        $.ajax({
            type: "POST",
            url: "secure_scripts/search_users.php",
            data: {search: send},
            dataType: "json",
            success: function (msg) {
                $.each(function (index, item) {
                    $("#ajax-loader").fadeOut("slow", function () {
                        $("#console_loader img").remove();
                        $("#console_loader").fadeIn("slow").html(item.search);
                    });
                });
            }
        });
    });
});

When your json is received, it is more than likely an array of objects

[{"search":"10 
    junaid 
    saleem 
    [email protected] 

    "}{"search":"13 
    zzz 
    aaa 
    [email protected] 
"}]

Therefore, by using $.each() to loop through the collection and return the value (index, item) you can get the object's value by referencing it like so:

$("#console_loader").fadeIn("slow").html(item.search);

since json is returning a JavaScript object literal.

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

Comments

0

Something like this should work:

$.ajax({
  type: "POST",
  url: "secure_scripts/search_users.php",
  data: {search: send},
  dataType: "json",
  success: function(msg){
    $.each(function() {
      $("#ajax-loader").fadeOut("slow", function(){
        $("#console_loader img").remove();
        $("#console_loader").fadeIn("slow").html(msg.search);
      });
    });
  }
});

We're adding $.each() method to the success function in order to run it for each JSON object that gets returned, not just the first.

Here's the jQuery.each() doc for further reading.

edited for clarity

5 Comments

if the json is received as an array of objects, i would recommending using $.each(function (index, item){} and access the object via item.search instead using msg.search
i don't know to use that, can you please guide me @HowardRenollet
@JunaidSaleem - I've posted a more detailed explanation as an answer. Please let me know if you have any other questions or need further assistance.
okay, i've tried the link that you posted and applied that method on my script, but i got error: Uncaught TypeError: Cannot read property 'length' of undefined..... on this line: $.each(results['Users'], function(key, val) {
okay, mr @CodyReichert thanks for showing me the right way and i've found the error, the error was: this ->: $.each(results['Users'], function(key, val),,,, should be like this ->: $.each(results.Users, function(key, val), thanks for help again :)

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.