Murphy1976
Murphy1976

Reputation: 1475

Ajax and MySql inserting, checking and retrieving

I have two database tables, guestlist and attendance

On one HTML page, I have a window.onload script that I want to check the guestlist via AJAX. If the firstname AND lastname in the url query appear in the guestlist table, then load the page. If not, load an error message.

When the page is properly loaded, the firstname and lastname are pre-populated in two input fields. The user completes the rest of the form and clicks submit, inserting their firstname and lastname into the attendance table.

If the firstname and lastname already appear in the attendance table, load an error message. If the firstname AND lastname to not appear in the attendance table, submit the form information to the attendance table.

When it comes to Ajax, I am not the bright bulb in the pack. This is the code I currently have:

HTML

<body>
<div id="formDiv">
<form id="partyForm" name="party" action="party_insert" method="post">
<h1>Welcome to The Party</h1>
    <input name="first_name" id="firstname" class="input" type="text" maxlength="99" placeholder="First Name"><br/>
    <input name="last_name" id="lastname" class="input" type="text" maxlength="99" placeholder="Last Name"><br/>
    <input name="costume" id="costume" class="input" type="text" maxlength="999" placeholder="What are you supposed to be?"><br/>
    <div id="buttonDiv">
        <a class="button" id="submit" style="cursor:pointer;">SUBMIT</a>
    </div>
</form>
</div>

<script>
window.onload = function () {
    var fname_init = decodeURIComponent(getUrlVars()["fname"]);
    var lname_init = decodeURIComponent(getUrlVars()["lname"]);

    if(fname_init !== "undefined" && lname_init !== "undefined"){
        var newString = 'fname='+encodeURIComponent(fname_init)+'&lname='+encodeURIComponent(lname_init);
        $.ajax({
            type: "GET",
            url: "guestList.php",
            data: newString,
            success: function(){
                alert("ON THE LIST");
                $('#firstname').val(fname_init);
                $('#lastname').val(lname_init);
            },
            error: function(){
                alert("NOT ON THE LIST");
                window.location = 'error1.html?fname='+encodeURIComponent(fname_init)+'lname='+encodeURIComponent(lname_init);
            }
        })
    }
}

$("#submit").click(function() {
    validate();
});

function submit(){
    var fname = $("#firstname").val();
    var lname = $("#lastname").val();
    var cost = $("#costume").val();
    var dataString = 'fname='+encodeURIComponent(fname)+'&lname='+encodeURIComponent(lname)+'&cost='+encodeURIComponent(cost);
    $.ajax({  
        type: "POST",  
        url: "partyEntry.php",  
        data: dataString,  
        success: function() {  
            alert("ENJOY THE PARTY");
            clearForms();
        }
    });
}

function validate(){
    if ($("#firstname").val() == ""){
        alert("Please Enter your First Name");
    } else {
        if ($("#lastname").val() == ""){
            alert("Please Enter your Last Name");
        }else{
            if ($("#costume").val() == ""){
                alert("You have to have a costume to be eligible for this raffle");
            }else{
                submit();
            }
        }
    }
}

function clearForms() {
    $('#partyForm')[0].reset();

}

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

</script>
</body>

guestList.php

<?php

    $host = "localhost";
    $user = "root";
    $password = "";
    $database = "party";

    $link = mysql_connect($host, $user, $password);
    mysql_select_db($database);

    //SURVEY INFORMATION
    $fname = mysql_real_escape_string($_REQUEST['fname']);
    $lname = mysql_real_escape_string($_REQUEST['lname']);

    $checkClient  = "SELECT * FROM guestlist WHERE first_name = ".$fname." AND last_name = ".$lname;
    mysql_query($checkClient) or die(mysql_error());

    mysql_close($link);

?>

partyEntry.php

<?php

    $host = "localhost";
    $user = "root";
    $password = "";
    $database = "party";

    $link = mysql_connect($host, $user, $password);
    mysql_select_db($database);

    //SURVEY INFORMATION
    $fname = mysql_real_escape_string($_REQUEST['fname']);
    $lname = mysql_real_escape_string($_REQUEST['lname']);
    $cost = mysql_real_escape_string($_REQUEST['cost']);

    $addClient  = "INSERT INTO attendance (first_name, last_name, costume) VALUES ('$fname','$lname', '$cost')";
    mysql_query($addClient) or die(mysql_error());

    mysql_close($link);

?>

The error I am getting is that even though a name is not on the guestlist, it will still show that they are ON THE LIST. So I must be doing something wrong in the Ajax call to guestlist.php, but I have no idea what. I also am having problems scripting out an ajax call to check if the guest has already been put into the attendance table.

Upvotes: 2

Views: 1800

Answers (3)

Cyclonecode
Cyclonecode

Reputation: 30051

Like I said in my comment you will have to return a value from the guestList.php, something like this should work:

$checkClient  = "SELECT * FROM guestlist 
                 WHERE first_name = ".$fname." AND 
                       last_name = ".$lname;
$result = mysql_query($checkClient);
$count = mysql_num_rows($result);
mysql_close($link);
// output 1 or 0 stating if the user is on the list or not
echo ($count ? 1 : 0);
exit();

Then in your ajax callback you would do a check like:

success:function(e) {
   alert((e == 1 ? "User is on list" : "User isn't on list"));

Upvotes: 1

verheesj
verheesj

Reputation: 1458

According to the REST principle, responding to a POST request with HTTP 200 means that the resource is successfully created. You can respond with a HTTP 400 and also provide detailed information about the error in text/html/json/xml format.

Try doing this,

Add the folowing code,

$query = mysql_query($addClient) or die(mysql_error());

if(mysql_num_rows($query) > 0)
{
     header('HTTP/1.1 500 Internal Server Error');
     echo 'this is an error message';
}

Upvotes: 1

jtello
jtello

Reputation: 451

The php script will never throw an error at least you try to execute an invalid query. The query is executed without any error because it is well formatted so and error won't be throw because you are not getting rows from the database.

Upvotes: 0

Related Questions