Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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. :/

share|improve this question
    
what is the response you got in networks option of your debugger? – Sourabh Kumar Sharma May 30 '15 at 5:28
    
Looking at the javascript console in Chrome, the only direct responses I can see are the xhr response from the php, giving what I would expect: {"result":"Cfail"} ... Unless I am missing a tab to look at? – ABarr May 30 '15 at 5:41
    
just look at the output response when you click on the network url that is showen when you make an ajax call – Sourabh Kumar Sharma May 30 '15 at 5:42
    
Yeah, the only response I see from the mailprocess.php is {"result":"Cfail"} The console shows a red dot in front of it, however... I'm guessing that means it's inserting something ahead of the JSON object when echoing? – ABarr May 30 '15 at 5:48
    
i added an answer below please check that, it will most probably solve your problem – Sourabh Kumar Sharma May 30 '15 at 5:52

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

share|improve this answer
    
This specifically did not work, but I just managed to solve it trying something at random. Apparently because I was requiring a 'config' php file to set some variables before doing the json encode, php was putting "something" before the first bracket. A blank-space object or whatever. Really odd. :/ Gonna update my original question to point out. – ABarr May 30 '15 at 6:05

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!");
                }
share|improve this answer
    
This does not solve the issue at all, as the "success" aspect never fires. It doesn't get to the point of returned = JSON.parse(returned); ... JSON is causing ajax to respond in error, which adding the error option to the call does indeed fire there. However, the only response error gives is the {"result":"Cfail"}, which is what should be called form a successful PHP call. As I pointed out above, looking at the response in the console had a red 'bullet point' or 'dot' before the first {. Is that normal, or is PHP inserting more than it should in the response? – ABarr May 30 '15 at 5:57
    
ok, so at the console do you see any jquery error, there are chances that before the success callback fires some jquery error stops the code from going further. {} that you see is normal that is the json encoded notation – Sourabh Kumar Sharma May 30 '15 at 6:00
    
I updated my question to show I got it solved. PHP was, for some reason, putting an empty space / hidden character before the first bracket. I just moved my config requirement further down into the code and it is fine. – ABarr May 30 '15 at 6:10
    
Ok, great you solved the issue :) – Sourabh Kumar Sharma May 30 '15 at 6:11

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.