Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4

Thread: PHP return JSON

  1. #1
    New Coder
    Join Date
    Aug 2008
    Posts
    15
    Thanks
    3
    Thanked 0 Times in 0 Posts

    PHP return JSON

    Hi

    Please take a look at the code section. Does anyone know how to:
    a) Return JSON from the prepared procedure call instead of me using a while loop and a concatenated string?
    b) Given the MySQL query returns these columns: ID, DepartmentName how do I access these in my client-side JavaScript, ie what will the JSON look like ?

    Many thanks.

    PHP Code:
    function fnGetDepartments() {

        require (
    'mysqli_connect.php'); // Connect to the Db.    
        
    $sql "CALL get_departments(?)";
        
    $stmt $dbc->prepare($sql);
        if (
    $dbc->errno) {die($dbc->errno.":: ".$dbc->error);}
        
    $stmt->bind_param("i"$prm);
        
    $stmt->execute( );
        if (
    $dbc->errno) {die($dbc->errno.": ".$dbc->error);}
        
    $stmt->bind_result($id$dept_name);
        
    $buf "";
        while (
    $stmt->fetch( )) {
            
    $buf .= $id '^' $dept_name '|';
        }
        
    $buf substr($buf0strlen($buf)-1);
        echo 
    $buf;    
        
    mysqli_close($dbc);


  • #2
    New Coder
    Join Date
    Feb 2012
    Posts
    40
    Thanks
    0
    Thanked 9 Times in 9 Posts
    well if $buf is the data you want to return to javascript it would be:

    PHP Code:
    echo  json_encode($buf); 

    then to access it in javascript you would just reference it as the same variable name as the php script.
    with jquery you could do something like:
    Code:
    $.post('/YOUR_PHP_SCRIPT.php', $('#YOUR_FORM').serialize(),
    function(buf) {
    	if(buf)
    	{
    		//reutrned true do something good
    	}
    	else
    	{
    		//returned false do somthing evil
    	}
    }, 'json');
    Last edited by cercos; 02-21-2012 at 11:02 PM.

  • #3
    New Coder
    Join Date
    Aug 2008
    Posts
    15
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Thanks for getting back..

    But can I use json_encode directly with $stmt and not have to build up a string, kinda defeats the object ??

    Cheers.

  • #4
    New Coder
    Join Date
    Aug 2008
    Posts
    15
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Just cracked it! Thanks, the method to use an array was useful and I used:
    print_r(json_encode($array));
    to inspect the json.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •