Search code examples
phpjqueryjsonajax

sending back json string with echo problem


i use json_encode to send back data from php to jquery through ajax.

and i have noticed that jquery just allow us to use ONE echo in php.

if i use echo json_encode($array);.... and then one more echo json_encode($array2); in the same php file, then it would not work.

or if i use echo json_encode($array); and then another echo "hello"; then it stops working too.

am i correct?

the problem is that when i use

$users = mysqli_fetch_assoc($login_user_result);

in the ajax called php file together with

echo json_encode($array);

it doesnt work. it sends the $array correctly but together with a bunch of other code because of the line above it.

but i have to use mysqli_fetch_assoc to get the data from the database.

what is the work around for this?

EDIT: here is the ajax call i used:

        $.ajax({
            url: "static/js/ajaxcall_login.php",
            type: "POST",
            data:
            {
                username:       $("#login_box .username").val(),
                password:       $("#login_box .password").val()
            },
            dataType: "json",
            success: function(data)
            {
                 ................
            }
        )};

Solution

  • I didn't see anything wrong with your Ajax Request.

    Here is the test code and it worked perfectly...

    Request:

    $(document).ready(function() {
        $.ajax({
            url: "json.php",
            type: "POST",
            dataType: "json",
            success: function(data) {
                alert(data);
            }
        });
    
    });
    

    Source:

    $arr1 = array(3.14, 123, "foo");
    $arr2 = array("one", "two", "three");
    
    $arr = array_merge($arr1, $arr2);
    
    echo json_encode($arr);
    

    Only one thing to note...

    If you set dataType to json in jQuery Ajax Request, the respnse (echo) must be qualified JSON. That is why you can't echo another string along with JSON.