0

I'm kinda lost in how to fix a problem of mine. I've got a little code on PHP that's passing data(errors, page(id, name, title etc) trough an array and that array has been set with parseJSON. If I alert the response I will get an array with the correct value. But my problem is, that the response is always different hence it are PHP variables that change.

I've tried something like responseText.pageid or responseText.error[1], but that can't work because it can be different. And I don't know if I need to call it responseText.pageid because in the array it's $pageid or something different...

So alerting responseText is giving me a good result, but separating it won't unfortunately work.

My JS code:

    // Variables
    var content_page = $('#content-page').val();
    var content_url = 'action=chose&page='+content_page;

    /* Starting AJAX post form */
        $.ajax({
            type: 'POST',
            dataType: "JSON",
            url: 'handlers/content.handler.php',
            data: content_url,
            success: function(responseText)
            {
                var obj = $.parseJSON(responseText);
                console.dir(obj.error);

                    if(obj.error[1] > -1)
                    {
                        noty({ text: 'U hebt geen pagina gekozen!' });
                    }
                    else if(obj.error[2] > -1)
                    {
                        noty({ text: 'De gekozen pagina bestaat niet!' });
                    }
                    else if(obj.error[100] > -1)
                    {
                        noty({ text: 'Uw pagina wordt opgehaald...' });
                    }
            }
        });
    return false;
});

My PHP code:

// Storing the variables.
        $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 = false;
                }
                if($intPage == 0)
                {
                    $error[] = 2;
                    $bolean = true;
                }

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

            header('Content-Type: application/json');
            $aVariables = array('error' => $error, 'id' => $pageID, 'name' => $pageName, 'title' => $pageTitle, 'text' => $pageText);
            echo json_encode($aVariables, JSON_FORCE_OBJECT);

I've Googled and came to the conclusion that I need to make a variable out of the parseJSON but then I get no result unfortunately. My current result(http://prntscr.com/72c39h) is working but separating it with responseText.home isn't working.

Thank you in advance, and my apologies for the bad grammar and language!

RezaM
  • 167
  • 1
  • 1
  • 11
  • 1
    The alert in your screenshot shows that you are not dealing with JSON data, but just a string. If you want to separate those values into an array for instance, you could `var separated = responseText.split(','); console.log(separated)` – azium May 06 '15 at 21:21
  • Thank you @azium for helping. I've tried it and have now updated my PHP and JS with working array and parseJSON. But now var obj cannot be read, and gives me null as return. Any thoughts on that? Thank you again for helping! – RezaM May 06 '15 at 22:04

2 Answers2

1

When calling JQuery's parseJSON() you have to both call it properly, e.g. $.parseJSON(), and store it in a variable, e.g. var obj = $.parseJSON(responseText);, as per the documentation.

Adam Ashwal
  • 1,472
  • 1
  • 19
  • 36
  • Thank you for responding that quickly. But how can I now call the error? Is it obj.error or obj.home ? How can I call the variable in the array? Also, I'm getting a 'null' for return when I console.log or alert obj, or obj.error. Thank you for helping! :-) – RezaM May 06 '15 at 21:31
  • 1
    JSON maps a key to a value and it think's you're just passing the keys. Take a look at this [answer](http://stackoverflow.com/questions/13394263/force-php-json-encode-to-encode-indexes-as-strings) for an illustration of the problem/solution – Adam Ashwal May 06 '15 at 21:56
  • Thank you @bipolpants, I've updated the PHP and JS. My PHP now has an working array(http://prntscr.com/72cpda) but when I try to use obj.error or console.dir/log(obj) it gives me the error null(http://prntscr.com/72cpsv). Thank you very much again for helping me out! – RezaM May 06 '15 at 22:03
  • 1
    What does `obj` look like in the console? – Adam Ashwal May 06 '15 at 22:11
  • Thank you for responding. It returns null(alerting it gives undefined). It gives me the cannot read property of null error. This only happens when I make the variable obj = $.parsejson .... Normally the rest of the code would work. – RezaM May 06 '15 at 22:13
  • And what does `responseText` look like? – Adam Ashwal May 06 '15 at 22:17
  • I'm then getting the result of the array: http://prntscr.com/72cy23 if I do console.dir(responseText). So this is without the parseJSON. Thank you again! – RezaM May 06 '15 at 22:24
1

There is no need to var obj = $.parseJSON(responseText);, this responseText is already in json format. If you want to access error then just refer it by simply responseText.error or 'alert(responseText.error);' and there is also no need to set header('Content-Type: application/json');

Varun Naharia
  • 5,318
  • 10
  • 50
  • 84