4

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.

1 Answer 1

6

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.

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

8 Comments

Well thank you for responding that quickly. I'm already using the parseJSON option just after I declare my success function. But I will try your option of first assigning it as a variable. Thank you again!
No problem. I do this all the time and you have to assign it to a variable, you could even use responsetext still like responsetext = $.parseJSON(responsetext);
If it doesn't work for you there might be a larger issue so leave a comment here if it doesn't work so I can try to help you figure out what else might be the cause of your issue. Thanks. :)
How did that work for you? @RezaM if it was the correct answer can you click the checkmark to the left of my answer to indicate that. Thanks !
I've accepted your answer, as it was right. But the problem still remains. I've used parseJSON as you can see in my code, but I've got multiple data passing trough. So if I do $.parseJSON(responseText), I've got everything in one object. But how can I separate this? If I make a variable out of it, how do I recall it? Is it responsetext.error or how does that work? Thank you again for helping me with 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.