RezaM
RezaM

Reputation: 167

Passing multiple variables through json_encode

I'm kinda making a mess now with my code, usually I'd make a PHP-AJAX script and pass one variable back to the JS script with json_encode. This time I would like to pass a few variables with json_encode, unfortunately I don't know how to separate the value in JS.

My JS code:

$('#submit').click(function(){

    // Storing the value into variables
    var content_page = $('#content-page').val();
    var content_url = 'action=saving&page='+content_page;

        // Starting the AJAX post form
        $.ajax({
                type: 'POST',
                url: 'handlers/content.handler.php',
                data: content_url,
                success: function(responseText)
                {
                    $.parseJSON(responseText); // Making the return value of the PHP handler reedable

                    alert(responseText.pageid)

                        if(responseText.indexOf(1) > -1)
                        {
                            noty({ text: 'U heeft geen pagina gekozen om te bewerken!' });
                        }
                        else if(responseText.indexOf(2) > -1)
                        {
                            noty({ text: 'U heeft geen geldige pagina gekozen!' }); 
                        }
                        else if(reponseText.indexOf(100) > -1)
                        {
                            noty({ text: 'Pagina is opgehaald' });
                        }
                }
            });
    return false;
});

My PHP code:

<?php
/* Dit bestand handeld gegevens af voor het bestand content in de map panel. Gegevens komen hier door heen via een JS bestand(content.handler.js...) en worden ook weer terug gestuurd. */
include_once '../includes/config.php';

    // Controleren of server contact maakt en geen persoon.
    if(isset($_POST['action']) && $_POST['action'] == 'saving')
    {
        $stringPage = trim($_POST['page']);
        $error = array();
        $bolean = false;

            # Prepared statement.
            $stmt = $mysqli->prepare('SELECT id,name,title,text FROM pages WHERE name = ?');
            $stmt->bind_param('s', $stringPage);
            $stmt->execute();
            $stmt->store_result();
            $stmt->bind_result($pageID, $pageName, $pageTitle, $pageText);
            $stmt->fetch();
            $intPage = $stmt->num_rows();
            $stmt->close();

    /* Controle */
        if(empty($stringPage))
        {
            $error[] = 1;
            $bolean = true;
        }
        if($intPage == 0)
        {
            $error[] = 2;
            $bolean = true;
        }

            if($bolean == false)
            {
                $error[] = 100;

            }


            header('Content-Type: application/json');
            $array = array($error, $pageID, $pageName, $pageTitle, $pageText);
            echo json_encode($array, JSON_FORCE_OBJECT);
    }
?>

So all the value is coming back just fine, so there's no problem with that. My problem is that I put everything that I wanted in an array(not the best solution) and don't know how to separate in JS. I suggest it would be something like response.pageid but that didn't work.

Upvotes: 4

Views: 15466

Answers (1)

Tech Savant
Tech Savant

Reputation: 3766

You need to parse the JSON first and assign to an object variable. That's the only step you missed I think.

Also, returning a json encoded array is just fine. I do it all the time. You can add things like "status=success" and "errormessage=someerror" so it comes in really handy.

var obj = $.parseJSON(response);

So in your case, you have the values in an array in php .. so lets say for example...

$myarray['fullname'] = 'john doe';
$myarray['userid'] = 777;
$myarray['isadmin'] = false;
$myarray['email'] = [email protected];

your ajax script then sends the response back to javascript ...

echo json_encode($myarray);

javascript gets it in your ajax success function ...

success: function (data) {
    var responsedata = $.parseJSON(data);

    alert('Fullname: '+responsedata.fullname+' userid: '+responsedata.userid+' isadmin: '+responsedata.isadmin);  //etc etc

}

FROM CHAT

I looked at your code on paste bin

use this to see the response btw

console.dir(responsetext); //instead of alert

or try firefox to do

alert(responsetext.toSource());

responsetext itself is an object and wont alert anything

think of response text as an array like in php, but instead of using myarray['somekey'] you do myobj.somekey

change your error assignments to

error[1] , error[2], error[100]

instead of error[]

You are passing error to it, so that's an array, which you could access with indexOf() like you did, or you could use textresponse.error[1]

but your problem was the keys for the error array were just being assigned as 0, 1, 2 etc..

but you were trying to call them as 1,2,100 ...

so by adding those numbers instead of just using error[] it will now find the correct value when checking the error response.

Upvotes: 6

Related Questions