0

I am creating a simple module for our senior project that checks whether an email already exists in the database. This is the important segment of my php file which displays the formated JSON:

die(json_encode(array(2 => "Email already taken!")));

For that example, that should return = {"2","Email already taken!"}

And here is the javascript code (that's embedded):

$(function() {
   $("#signin").submit(function() {
     // validate and process form here
     $.ajax({
        type: "GET",
        url: "mailcheck.php",
        data: "email="+document.getElementById('email').value,
        success: function(data) {
        var parsed = $.parseJSON(data);
        //display message back to user here
          document.getElementById('msg').innerHTML = parsed.Msg;
          $("input#email").val("");
        },  
     });
   return false;
   });
});

The problem is, I always get 'undefined'. What's the problem?

4
  • echo json_encode not die() Commented Jun 24, 2014 at 3:41
  • Wouldn't die() also echo out the contents? codepad.viper-7.com/w3uR9C Commented Jun 24, 2014 at 4:03
  • the die() function echoes out its contents then it will exit, thus leaving the succeeding echo() or die() statements not displayed. Commented Jun 24, 2014 at 6:01
  • if I could not use die(), could I use exit; instead? I tried exit and it also worked... Commented Jun 24, 2014 at 6:10

1 Answer 1

1

In your PHP file echo json_encode as @pc-shooter has mentioned. And you do not need to parse JSON if you set dataType: 'json', in you ajax call.

You may also need to set to content type in you PHP file.

header('Content-Type: application/json');
echo json_encode(array(2 => "Email already taken!"));
Sign up to request clarification or add additional context in comments.

Comments

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.