PHP JSON encoded object throws Ajax error

This has been bugging me for the last few hours and I've tried various searches but haven't found exactly this problem with an answer. Maybe asking and showing some code will help me figure this out.

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

Originally, I was going to try text-only responses. So my PHP, for example, would look like this:

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

      

Javascript will:

$(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 will work through the script just fine, but the result will never be what I asked for. The warning showed corrective text, however research showed that the problem with this was apparently the addition of white space. The common answer was to encode the JSON response. So I tried this.

PHP updated:

<?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;
     }
?>

      

Javascript updated:

$(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!");
                }
            }
        });
    });
});

      

Now it doesn't work anymore. The warning does not appear and the loader object remains visible (indicating that success never passes). I tried putting an error block in ajax and it really fired that. However, I had no idea how to disassemble or even figure out what the error was. The most I was trying to get was what PHP output, which was {"result": "Cfail"} .... This is what I will EXPECT PHP to give me.

I can get around this, I made a similar setup just repeating the number, not the words, and it worked very well as far as I know. I just would like to find out what I am doing wrong here.

EDIT:

I managed to figure out what was the matter in my case. I had a requirement ("config.php"); between the start of the session and the json_encode if statement. For some reason with the addition of an external file that just set me a couple of variables for the code below, some hidden character was added before the first {JSON object.

I do not know why. As I said, this is just $ var = 'stuff'; the situation is in the requirement, but apparently it caused problems.: /

+3


source to share


2 answers


Use it 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

+2


source


use the below code, in your successful callback, first parse the json encoded object you are receiving from the back end and access the property of the object result

to check its value



success: function(returned){
                returned = JSON.parse(returned);
                $('#loader').stop(true).fadeTo(300,0);
                if(returned.result=='Cfail'){
                    alert("I read it right!");
                }

      

+1


source







All Articles