1

I have created a registration system that uses AJAX to process the form so that I can return false. The relevant js is the top block of code. I pass this data to join.php, which sends it to the database. I run a check in join.php to make sure that nobody with a duplicate email has already signed up. As you can see, if the email already exists, I want to insert a message using javascript. Instead of reading the script tags, it simply pastes them into my alert in plaintext...so my alert has the datastring and then actually says the code <script>...</script>. How can I get this js to process instead?

Javascript:

$(".submit").click(function() {  
        var dataString = {
            school : $("#school").val(),
            studentEmail : $("#studentEmail").val(),
            studentPassword : $("#studentPassword").val(),
            parentEmail : $("#parentEmail").val(),
            parentPassword : $("#parentPassword").val(),
            studentFirstName : $("#studentFirstName").val(),
            studentLastName : $("#studentLastName").val(),
            studentPhone : $("#studentPhone").val(),
            parentFirstName : $("#parentFirstName").val(),
            parentLastName : $("#parentLastName").val(),
            parentPhone : $("#parentPhone").val()
        };
        $.ajax({
            type: "POST",
            url: "join.php",
            data: dataString,
            success: function(data) {
                alert ("data sent: "+ data);
            }
        });
        return false;
    }
});

join.php

if($_POST) {
    $school             = mysql_real_escape_string($_POST['school']);
    $studentEmail       = mysql_real_escape_string($_POST['studentEmail']);
    $parentEmail        = mysql_real_escape_string($_POST['parentEmail']);
    $studentFirstName   = mysql_real_escape_string($_POST['studentFirstName']);
    $studentLastName    = mysql_real_escape_string($_POST['studentLastName']);
    $studentPhone       = mysql_real_escape_string($_POST['studentPhone']);
    $parentFirstName    = mysql_real_escape_string($_POST['parentFirstName']);
    $parentLastName     = mysql_real_escape_string($_POST['parentLastName']);
    $parentPhone        = mysql_real_escape_string($_POST['parentPhone']);

    $check = mysql_query("SELECT studentEmail FROM clients WHERE  studentEmail = '{$studentEmail}';");
    $num = mysql_num_rows($check);


    if (($num) == 0) {

        $sql = "INSERT INTO clients ".
            "(`studentEmail`, `studentPassword`, `parentEmail`, `parentPassword`, ".
            "`studentFirstName`, `studentLastName`, `studentPhone`, `parentFirstName`, ".
            "`parentLastName`, `parentPhone`, `school`) ".
            " VALUES ('$studentEmail', '$studentPassword', '$parentEmail', ".
            "'$parentPassword', '$studentFirstName', '$studentLastName', ".
            "'$studentPhone', '$parentFirstName', '$parentLastName', '$parentPhone', '$school')";

        $result = mysql_query($sql);
        if ($result) { 
            echo "Database query successful!";
        }
        else {
            die("Database query failed: " . mysql_error()); 
        }

        include "emails/signUp.php";
    }
    else {
        echo 'FAIL

        <script>
            $(".formErrorMessage").html("Email already exists");
        </script>';
    }
}
6
  • alert is not going to evaluate your JavaScript. Commented Dec 19, 2011 at 21:27
  • right, that is exactly the problem I am having. The alert calls the data in join.php, which includes the js that I need to process. How can I process this js instead of it appearing in the alert? Commented Dec 19, 2011 at 21:27
  • I think what @AndrewWhitaker means is that of course an alert will show the plain text; what other methods have you tried to actually execute the script, whether they have failed or not... appending to the DOM? Running an EVAL (not recommended; just throwing an example out there)? Commented Dec 19, 2011 at 21:30
  • Sorry I'm still somewhat of a beginner. I don't know how I would try another method exactly. I am only alerting so that I know the query went through without having to check the database. The success seems to happen when the data is sent, so even if $num == 0, the query still is successful. So, I have to include the js right there in that statement. Commented Dec 19, 2011 at 21:37
  • @radleybobins: Apologies for the curt response--I should have elaborated Commented Dec 19, 2011 at 21:44

3 Answers 3

2

The alert shows your script block because you've got this in your success handler:

alert ("data sent: "+ data);

Data is going to be whatever text you output in your PHP. If you want to have variable behavior based on whether your request was successful or not, I'd recommend that your PHP returns JSON containing a success flag and the message. Your JavaScript callback would then look like this:

function(data) {
    if (data.success) {
        alert ("data sent: "+ data.message);
    } else {
        $(".formErrorMessage").text(data.message);
    }
}

Your PHP should then change your content-type to JSON:

header('Content-Type: application/json');

... and your echos would change to something like this:

echo '{"success": false, "message": "Email already exists."}';
Sign up to request clarification or add additional context in comments.

9 Comments

But it always returns success because the data is always sent even if it is not posted join.php. so even if the user exists, AJAX sends me the alert saying data sent. How do I tell join.php to return a failure?
That's why the data you send back needs to indicate true or false for the success flag. The success callback in your Ajax call only indicates that a non-HTTP-error response was returned. You would use the flag to control whether your page treats the result as successful or not.
Yes, that's what I'm looking for. How would I indicate true or false?
With the echo statement; change false to true in the JSON.
Your alert shows up because that's the only thing your JavaScript callback does. If you want your JavaScript to do more (i.e. handle errors), you need to add that code in your callback, and you need a way to distinguish between success and failure (which is what sending JSON results from the server can help you do).
|
0

Your server call shouldn't be returning raw HTML. Should return JSON that contains all the status information the server needs to handle things. i.e. in the usual case:

{'success': true}

or

{'success': false, 'emailAlreadyExists': true, 'msg': 'Email Already Exists'}

of

{'success': false, 'msg': 'Database query failed: blahblahMySqlError'}

Then your client JS should handle it...

$.ajax({
    type: "POST",
    url: "join.php",
    data: dataString,
    success: function(data) {
        if(data.success) {
            alert ("success!");
        }
        else{
            alert("error: " + data.msg);
            if(data.emailAlreadyExists){
                $(".formErrorMessage").html("Email already exists");
            }
        }
    }
});

1 Comment

I am using the same comment as the answer below: "But it always returns success because the data is always sent even if it is not posted join.php. so even if the user exists, AJAX sends me the alert saying data sent. How do I tell join.php to return a failure? –"
0

from php, you have give formatted status responses

on success:

echo '{"status":"success", message:"Database query successful!"}';

if account already exists:

echo '{"status":"failed", message:"Email already exists"}';

So you will be able to identify this in JavaScript callback function

$.ajax({
        type: "POST",
        url: "join.php",
        data: dataString,
        success: function(data) {
            if(status.error == "failed"){
                $(".formErrorMessage").html(data.message);
            }
        }
    });

This is the best way to do it. Or if you just want to execute a string received from php, you can use eval

        success: function(data) {
            eval(data);
        }

In that case there is no need of script tags in response, only the Javascript statement that has to be executed.

3 Comments

Hmm, this doesn't seem to work for me. It is not returning the form false (I added that in, both here and after an "else"). Hmm, actually this caused all my js to stop.
Hope you are talking about eval. It should be given like this in php echo '$(".formErrorMessage").html("Success")'; for success and echo '$(".formErrorMessage").html("Email already exists")'; for error and in javascript it should be success: function(data) { eval(data); }
but its not at all recommended like Greg Pettit said. The right way is to send formatted response objects from PHP.

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.