Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP JSON Encoded Object causes Ajax Error

This has been bugging me for the last few hours, and I've tried various searches but never found exactly this issue with an answer. Maybe asking and showing some code will help me get this figured out.

I am using ajax to do a post to PHP, which I want to just give a notification so that I may update a div on the page. In this case, I just need the PHP to say something like "Cfail" which the javascript would use to update page content.

Originally, I was going to try just text responses. So, my PHP for example would be like this:

<?php
session_start(); //Because have an encoded captcha answer.
if(empty($_POST['captinput']) || md5($_POST['captinput']) !== $_SESSION['captchacode']){
    echo 'Cfail';
}
?>

The Javascript would be:

$(document).ready(function(){

    $('form#Contact').submit(function(e){
        e.preventDefault();
        var $form = $(this); 
        var formdata = $form.serialize();
        var myurl = $form.attr('action');
        $('#loader').stop(true).fadeTo(300,1);

        $.ajax({
            url: myurl,
            dataType: 'text',
            cache: 'false',
            type: 'POST',
            data: formdata,
            success: function(returned){
                $('#loader').stop(true).fadeTo(300,0);
                if(returned=='Cfail'){
                    alert("I read it right!");
                }
            }
        });
    });
});

It would run through the script just fine, but the result never would be what I was asking for. Alert showed the corrct text, however, research indicated that the issue with this was PHP apparently adding white space. The common answer was the encode a JSON response instead. So, I tried that.

Updated PHP:

<?php
    sesson_start(); // Captcha Stored in Session
    header('Content-type: application/json');
    if(empty($_POST['captinput']) || md5($_POST['captinput']) !== $_SESSION['captchacode']){
        $result = array('result' => 'Cfail');
        echo json_encode($result);
        exit;
     }
?>

Updated Javascript:

$(document).ready(function(){

    $('form#Contact').submit(function(e){
        e.preventDefault();
        var $form = $(this); 
        var formdata = $form.serialize();
        var myurl = $form.attr('action');
        $('#loader').stop(true).fadeTo(300,1);

        $.ajax({
            url: myurl,
            dataType: 'json',
            cache: 'false',
            type: 'POST',
            data: formdata,
            success: function(returned){
                $('#loader').stop(true).fadeTo(300,0);
                if(returned.result=='Cfail'){
                    alert("I read it right!");
                }
            }
        });
    });
});

Which now no longer runs successfully. The alert doesn't come up, and the loader object remains visible(indicating the success never goes through). I tried putting an error section to the ajax, and it indeed fired that. However, I had no idea how to parse or even figure out what the error was exactly. The most I got in trying to get it was what PHP was outputting, which was {"result":"Cfail"} .... Which is what I would EXPECT PHP to give me.

I can work around this, I've done a similar set-up with just echoing a number instead of words and it used to work just fine as far as I knew. I'd just like to figure out what I am doing wrong here.

EDIT:

I managed to figure out what the issue was in my case. I had a require('config.php'); between the session start and the json_encode if statement. For some reason having the external file added, which was just me setting a couple variables for the code further down, some hidden character was added before the first { of the JSON object.

No idea why. As I said, it was just a $var='stuff'; situation in the require, but apparently it caused the issues. :/

like image 613
ABarr Avatar asked Apr 28 '26 13:04

ABarr


2 Answers

Use this like

    <?php
        sesson_start(); // Captcha Stored in Session
        header('Content-type: application/json');
        if(empty($_POST['captinput']) || md5($_POST['captinput']) !== $_SESSION['captchacode']){
            //$result = array('result' => 'Cfail');
            $data['result'] = 'Cfail';
            echo json_encode($data);
            exit;
         }
    ?>

This works for your javascript

like image 96
codex Avatar answered Apr 30 '26 02:04

codex


use the below code, in your success call back, first parse the encoded json object that you are recieving from the back end and access the object property result to check it's value

success: function(returned){
                returned = JSON.parse(returned);
                $('#loader').stop(true).fadeTo(300,0);
                if(returned.result=='Cfail'){
                    alert("I read it right!");
                }
like image 23
Sourabh Kumar Sharma Avatar answered Apr 30 '26 02:04

Sourabh Kumar Sharma