PHP & Javascript: Dynamic search with 2 textbox - javascript

Is there any way to have a dynamic search with 2 textbox to filter 2 different fields?
for example i have a table like:
and i have created somethin like this:
it already works in the LASTNAME textbox.
i want is that when i enter a lastname with same lastnames like this:
i want to add another filter by firstname, so that when i enter a firstname on the FIRSTNAME textbox example i enter PEDRO in the FIRSTNAME textbox only PEDRO A. Dela Cruz will show up.
This is my Codes
Index.php
<script type="text/javascript">
$(function(){
$(".lname").keyup(function()
{
var value = $(this).val();
var dataString = 'lname='+ value;
if(searchlname!='')
{
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}return false;
});
jQuery("#result").live("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("<div/>").html($name).text();
$('#searchlname').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#result").fadeOut();
}
});
$('#searchlname').click(function(){
jQuery("#result").fadeIn();
});
});
</script>
<div class="content">
Lastname:
<input type="text" class="lname" id="searchlname" placeholder="Search for people" /><br />
Firstname:
<input type="text" class="search" id="" placeholder="Search for people" /><br />
<div id="result">
</div>
search.php
<table width="80%">
<th width="5%">ID</th>
<th width="40%">Name</th>
<th width="10%">Action</th>
</table>
<?php
$connection = mysql_connect('localhost','root','admin') or die(mysql_error());
$database = mysql_select_db('dbvincent') or die(mysql_error());
if($_POST)
{
$search_name=$_POST['lname'];
$sql_res=mysql_query("SELECT * FROM `tblpatients` WHERE `lname` LIKE '%$search_name%' order by `patient_id` LIMIT 15");
while($row=mysql_fetch_array($sql_res))
{
$id = $row['patient_id'];
$fname = $row['fname'];
$mname = $row['mname'];
$lname = $row['lname'];
?>
<table width="80%">
<td width="5%"><?php echo $id ; ?></td>
<td width="40%"><?php echo $fname.' '.$mname.' '.$lname; ?></td>
<td width="10%"><button formaction="echoid.php?id=<?php echo $id ?>">Add</button></td>
</table>
<?php
thanks you.

There are cleaner ways of doing this, but instead if changing all your code, I've updated it to fit your needs. I've already nagged about the security aspect and about not using those old, deprecated mysql_*-functions, but rather Prepared Statements with MySQLi or PDO.
It just needs to be pointed out in case someone else comes here later.
First, I would give both input fields a new extra css class, example: people-search-filter,
I'm also giving the field for last name an ID :
<input type="text" class="lname people-search-filter" id="searchlname" ...
<input type="text" class="search people-search-filter" id="searchfname" ...
This allowes us the create the same event on both input fields:
$(function(){
// We add the event on the class, which both inputs have
$(".people-search-filter").keyup(function() {
// Now we get the values from both inputs, using their ID's
var lname = $("#searchlname").val();
var fname = $("#searchfname").val();
// Add both to the dataString (and URI encode the strings)
var dataString = {lname: lname, fname: fname}
// Check that at least one has any content
if(lname != '' || fname != '')
// Your ajax query
In your PHP code, you just add the new parameter into your query:
$lname = $_POST['lname'];
$fname = $_POST['fname'];
// Now we will build the search string
$search_str = '';
if ($lname) {
$search_str = "WHERE lname LIKE '%" . mysql_real_escape_string($lname) . "%'";
}
if ($fname) {
// Check if we have something in the search string,
// if we do, add an AND to the statement.
// If we don't have one, we'll add the WHERE instead.
$search_str .= $search_str ? ' AND ' : 'WHERE ';
$search_str .= "fname LIKE '%" . mysql_real_escape_string($fname) . "%'";
}
// If neither $lname or $fname contains any data, the query will return all patiens
$sql_res = mysql_query("SELECT * FROM `tblpatients` {$search_str} order by `patient_id` LIMIT 15");
// ... the rest of your code.

You could try something like this perhaps where you build the query based upon the existence of first/lastnames - not tested but might give an idea
$search_name = !empty( $_POST['lname'] ) ? $_POST['lname'] : false;
$firstname = !empty( $_POST['fname'] ) ? $_POST['fname'] : false;
if( $search_name ){
$clauses=array();
$clauses[]="`lname` like '%$search_name%'";
if( $firstname ) $clauses[]="`fname` like '%$firstname%'";
$search = implode( ' AND ', $clauses );
$sql_res=mysql_query("SELECT * FROM `tblpatients` WHERE {$search} order by `patient_id` LIMIT 15");
/* rest of the commands...*/
}

Related

How to pass the radio button value to other program and insert value into database using php and jquery

I have a form with multiple radio buttons. What i want to store the radio button values in database like 1 for "Yes" and 0 for "No". I am using couple of script a.php, b.php for the same, a.php will get the radio button values and pass to b.php as parameter. Then b.php insert into the database. The problem here is database field for button value always updating with 0. I tried to implement with javascript and some other php logic. But no luck. Also I have created other small script to test the radio value is printing properly which is working fine. The problem is I am not aware how to get proper value in "recommend" in b.php
I really appreciate your help.
a.php is like below:
<div id="result">
<label for="sel1">Would You recomend</label>
<div class="pull-left">
<input name='recommend' type='radio' value=1>Yes
<input name='recommend' type='radio' value=0>No
<button class="btn btn-primary btn-sm" id="submit" type="submit" value="submit">submit</button>
b.php
<?php
require_once './config.php';
$pid = intval($_POST["pid"]);
$uid = intval($_POST["uid"]);
$score = intval($_POST["score"]);
$recommend = intval($_POST["recommend"]);
$aResponse['error'] = FALSE;
$aResponse['message'] = '';
$aResponse['updated_rating'] = '';
$return_message = "";
$success = FALSE;
$sql = "INSERT INTO `tbl_product_rating` (`product_id`, `user_id`, `ratings_score`, `recommend_score`) VALUES "
. "( :pid, :uid, :score, :recommend)";
$stmt = $DB->prepare($sql);
try {
$stmt->bindValue(":pid", $pid);
$stmt->bindValue(":uid", $uid);
$stmt->bindValue(":score", $score);
$stmt->bindValue(":recommend", $recommend);
//$stmt->execute(':pid' => $pid, ':uid' => $uid, ':score' => $score, ':recommend' => $recommend));
$stmt->execute();
$result = $stmt->rowCount();
if ($result > 0) {
$aResponse['message'] = "Your rating has been added successfully";
} else {
$aResponse['error'] = TRUE;
$aResponse['message'] = "There was a problem updating your rating. Try again later";
}
} catch (Exception $ex) {
$aResponse['error'] = TRUE;
$aResponse['message'] = $ex->getMessage();
}
if ($aResponse['error'] === FALSE) {
// now fetch the latest ratings for the product.
$sql = "SELECT count(*) as count, AVG(ratings_score) as score FROM `tbl_products_ratings` WHERE 1 AND product_id = :pid";
try {
$stmt = $DB->prepare($sql);
$stmt->bindValue(":pid", $pid);
$stmt->execute();
$products = $stmt->fetchAll();
if ($products[0]["count"] > 0) {
// update ratings
$aResponse['updated_rating'] = "Average rating <strong>" . round($products[0]["score"], 2) . "</strong> based on <strong>" . $products[0]["count"] . "</strong> users";
} else {
$aResponse['updated_rating'] = '<strong>Ratings: </strong>No ratings for this product';
}
} catch (Exception $ex) {
#echo $ex->getMessage();
}
}
echo json_encode($aResponse);
?>
Jquery which I am using in a.php to send radio button value to b.php:
<script>
$document.ready(function(){
$('input[type="radio"]').click(function(){
var recommend = $(this).val();
$.ajax({
url:"b.php",
method:"POST",
data:{recommend:recommend},
// data:{recommend:$('#recommend').val($("[type='radio'] :checked").val())},
success: function(data){
$('#result').html(data);
}
});
});
});
</script>
jquery to fetch pid,uid,score..
<script>
$(document).on('click', '#submit', function() {
<?php
if (!isset($USER_ID)) {
?>
alert("You need to have a account to rate?");
return false;
<?php } else { ?>
var score = $("#score").val();
if (score.length > 0) {
$("#rating_zone").html('processing...');
$.post("update_ratings.php", {
pid: "<?php echo $_GET["pid"]; ?>",
uid: "<?php echo $USER_ID; ?>",
score: score
}, function(data) {
if (!data.error) {
// success message
$("#avg_ratings").html(data.updated_rating);
$("#rating_zone").html(data.message).show();
} else {
// failure message
$("#rating_zone").html(data.message).show();
}
}, 'json'
);
} else {
alert("select the ratings.");
}
<?php } ?>
});
</script>
I can insert the value 1 if "YES" for radio button with the mentioned jquery but it's inserting 0 for other fields like product_id..etc.I want just one entry to be inserted in db with proper value of radio button along with other fields.I have provided the full code for insert (b.php) with ajax which passing value to b.php from a.php. Kindly suggest.
I want output in mysql like below:
ratings_id product_id user_id ratings_score recommend_score
1 17637 1 4 0
2 17638 2 2 1
How it's happening now:
ratings_id product_id user_id ratings_score recommend_score
3 0 0 0 1
6 17639 2 4 0
In your ajax that fires once a user clicks on a radio-button you are not sending the other values needed for insert (pid, uid, score). I suppose they are included in the half-shown form.
Assuming you have those inputs in your form
<input name="pid" id="pid">
<input name="uid" id="uid">
<input name="score" id="score">
EDIT: since you've now shown more code I updated the code below (to match how you send pid & uid in the normal form-submit).
you can add them to the data object with something like this:
data:{
recommend:recommend,
pid: "<?php echo $_GET["pid"]; ?>",
uid: "<?php echo $USER_ID; ?>",
score: $('#score').val(),
},
Also change the double-ids of #newsletter as the others have suggested.
Change id to class attribute.
<script type="text/javascript">
$(document).ready(function() {
$("input[type=radio]").click(function () {
var recommend = $(this).val();
console.log(recommend);
$.ajax({
url:"b.php",
method:"POST",
data:{
recommend:recommend
},
success: function(data){
//your code here
},
error: function (error) {
console.log(error);
}
});
});
});
</script>
<input name="recommend" class='newsletter' type='radio' value=1>Yes
<input name="recommend" class='newsletter' type='radio' value=0>No
Sample HTML:
<input type="radio" name="color" id="rdoColor" value="green" />Green<br />
<input type="radio" name="color" id="rdoColor" value="Blue" />Blue<br />
Sample JQuery Code:
$(document).on("click", "input[id=rdoColor]", function(){
$.post(serverPath+"/colorHandler.php", {action: "saveColor", color: $(this).val()}, function(data){
var response = $.parseJSON(data);
// use this response as u need
});
});
Sample PHP (colorHandler.php):
$jsonStr = "";
define('DB_SERVER', 'DBserver:port');
define('DB_NAME', 'DBName');
define('DB_USER', 'dbUser');
define('DB_PASS', 'dbPass');
try {
$dbCon = new PDO("mysql:host=".DB_SERVER.";dbname=".DB_NAME, DB_USER, DB_PASS);
$dbCon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO colorTable (colorName) VALUES (?)";
$stmt= $dbCon->prepare($sql);
$stmt->execute(array($_POST["color"]));
if( $dbCon->lastInsertId() ){
$jsonStr = '{
"status":"Success",
"Message":"Color Saved"
}';
echo $jsonStr;
}else{
$jsonStr = '{
"status":"Failure",
"Message":"Color was not Saved"
}';
echo $jsonStr;
}
}catch(PDOException $e){
$jsonStr = '{
"status":"Failure",
"Message":"Database server not found!"
}';
echo $jsonStr;
}

How, Right Click a <tr>, run php to retrieve data, display result in an alert?

I've read and tried many solutions, none are working. Here is my latest. As you can see all I'm trying to do is display an alert box on screen with the data retrieved from the MySQL using PHP.
My HTML looks like this:
...
<td $brbCols class=\"editCS1\" oncontextmenu=\"getLastLogin('$row[callsign]');return false;\" id=\"callsign:$row[recordID]\" style=\'text-transform:uppercase\'> $row[callsign] </td>
...
Right clicking on the above code runs this,
The getLastLogin javascript looks like this:
function getLastLogin() {
$('tr').on('contextmenu', 'td', function(e) { //Get td under tr and invoke on contextmenu
e.preventDefault(); //Prevent defaults'
var idparm = $(this).attr('id');
var arparm = idparm.split(":");
var id = arparm[1];
id = id.replace(/\s+/g, '');
var call = $(this).html();
call = call.replace(/\s+/g, '');
$.ajax({
type: "GET",
url: "getLastLogIn.php",
data: {call : call, id : id},
success: function(response) {
alert(response);
},
error: function() {
alert('Not OKay');
}
});
});
}
The PHP:
<?php
ini_set('display_errors',1);
error_reporting (E_ALL ^ E_NOTICE);
require_once "creddtls.php";
$call = $_POST['call'];
$id = $_POST['id'];
$sql2 = "SELECT recordID, id, Fname, Lname, grid, creds,
email, latitude, longitude, tactical, callsign, logdate, netID, activity
FROM NetLog
WHERE callsign = '$call'
ORDER BY netID DESC
LIMIT 1,1 " ;
$stmt2 = $db_found->prepare($sql2);
$stmt2->execute();
$result = $stmt2->fetch();
$recordID = $result[0]; $email = $result[6];
$id = $result[1]; $latitude = $result[7];
$Fname = $result[2]; $longitude = $result[8];
$Lname = $result[3]; $creds = $result[5];
$tactical = $result[9]; $grid = $result[4];
$callsign = $result[10]; $netID = $result[12];
$logdate = $result[11]; $activity = $result[13];
$msg = "<b>Last Check-in::</b>
<br>$callsign, $Fname $Lname
<br><b>eMail::</b>$email
<br><b>Was on::</b> $logdate
<br><b>Net ID::</b> $netID, $activity
<br><br>
$recordID
";
echo "$msg";
?>
You are trying to access the data passed via ajax with the wrong superglobal.
You are looking at POST data, but your ajax call is using GET
Change $_POST to $_GET
Wrong or not the code writes to the lli DIV. So I added $("#lli").modal(); to the Javascript to open it in a modal dialog.
All is now well.

Submit and fetch data without refreshing the page

I'm new to php and mySQL. I've created a webpage, it's essentially a noticeboard. The page has a form to submit content and the content is shown below instantaneously. The content appears when the submit button is pressed, but now if I wanted to submit content immediately after the form still displays the echo that says submission was successful. Could someone point me in right direction to get the page functioning in a way that users can submit content one after the other without refreshing the page? Any help is greatly appreciated. Apologies for the messy code.
This is my input code:
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() ) {
$name = addslashes ($_POST['name']);
$proposal = addslashes ($_POST['proposal']);
}else {
$name = $_POST['name'];
$proposal = $_POST['proposal'];
}
$email = $_POST['email'];
$sql = "INSERT INTO db3". "(name, proposal, email, join_date )
VALUES('$name','$proposal','$email', NOW())";
mysql_select_db('_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "<div class='msg-box' id='msg-box'>Entered data successfully</div>\n";
mysql_close($conn);
This is my form:
<form name="submission" method = "post" action = "<?php $_PHP_SELF ?>" >
<fieldset>
<input name = "name" type = "text"
id = "name" placeholder="Name..." required autocomplete="off">
<input name = "email" type = "text"
id = "email" placeholder="example#gmail.com..." autocomplete="off">
<textarea name = "proposal" type = "textarea" maxlength="1000"
id = "proposal" placeholder="Your proposal goes here..." required autocomplete="off"></textarea>
</fieldset>
<fieldset>
<input name = "add" type = "submit" id = "add" value = "Submit">
</fieldset>
</form>
This is my retrieval code:
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT id, name, proposal FROM db3 ORDER BY ID DESC ';
mysql_select_db('_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo
"<article>".
" <div class='id'> ID :{$row['id']} </div> ".
" <section> <p> {$row['proposal']} </p></section> ".
" <section class='name'><h3> {$row['name']} </h3></section> ".
"</article>"
;
}
mysql_close($conn);
?>
Use this code:
<script>
submitHandler: function(form) {
$.ajax({
url: '',
type: 'POST',
data: $("#submission").serialize(),
success: function() {
alert('submitted data: '$("#submission").serialize());
return false;
}
});
}
</script>
Please change the form line with this one:
<form name="submission" id="submission" method = "post" action = "<?php $_PHP_SELF ?>" >
You can do this using AJAX
You will use javascript to send the data to a PHP script which will process it. The same script will return the new data that was just submitted so you can display it on the page.
An example would be
HTML
<form id="comment">
<input type="text" id="userInput" name="comment" placeholder="Tell us what you feel about this" />
<input type="submit" value="Submit" />
</form>
jQuery
<script>
$("#comment").on('submit', function(e) {
// Stop the form from being submitted the standard way
e.preventDefault();
// Put the user's input into a variable
var userInput = $('#userInput').val();
// Do some validation of the data if needed
// ...
// ...
// Perform AJAX request (a.k.a send the data to the server)
$.ajax({
// There are many parameters one can use here
// Browse the documentation to get familiar with the most useful ones
url: 'proccess.php', // The PHP script that will handle the request
type: 'POST', // This can be set to GET, but in this case we'd use POST
data: { comment: userInput }, // "comment" will result in $_POST['comment'], and userInput is the value of it
// If the script returns a 200 status (meaning the request was successful)
success: function(data) {
// The data variable will be the response from the PHP script
// Depending on what you are going to do with the data returned,
// you may want to ensure it is returned as valid JSON
},
error: function() {
// The request failed - So something here
// ...
// ...
}
});
});
</script>
PHP (process.php)
<?php
$data = $_POST['comment'];
// Do all you would normally do when submitting a post
// ...
// ...
// Now, upon successfully storing the data in your database,
// you can return something to the 'data' variable in the AJAX.success function
?>
Do some research on AJAX and jQuery. It's really fun to work with

php search function dynamically show results with javascript

I have the following php script which works fine, it uses the search term and compares it with a few different fields, then prints out the each record that matches:
<?php
mysql_connect ("localhost", "root","") or die (mysql_error());
mysql_select_db ("table");
$search = isset($_POST['search']) ? $_POST['search'] : '';
$sql = mysql_query("select * from asset where
name like '%$search%' or
barcode like '%$search%' or
serial like '%$search%' ");
while ($row = mysql_fetch_array($sql)){
echo '<br/> Name: '.$row['name'];
echo '<br/> Barcode: '.$row['barcode'];
echo '<br/> Serial: '.$row['serial'];
}
?>
And this is the form that links to it:
<form action="http://localhost/test/search.php" method="post">
Search: <input type="text" name="search" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
I need to some how encode the results of the search so I can use them in a javascript function, then I can display them on the same html page below the form.
For that you have to use AJAX. You can send data back to the same page using JSON.
Advice - Don't use mysql_* functions since they are deprecated. Learn mysqli_* and try using that.
<script>
$(function(ev){
ev.preventDefault();
$("form").on('submit', function(){
var form = $(this);
var url = form.attr('action');
var data = form.serialize();
$.post(url, data)
.done(function(response){
if(response.success == TRUE)
{
// Search result found from json
// You have to loop through response.data to display it in your page
// Your single loop will have something like below -
var name = response.data.name;
var barcode = response.data.barcode;
var serial = response.data.serial;
$("#name").html(name);
$("#barcode").html(barcode);
$("#serial").html(serial);
}
else
{
// search result not found
}
});
});
});
</script>
On search.php
<?php
mysql_connect ("localhost", "root","") or die (mysql_error());
mysql_select_db ("table");
$search = isset($_POST['search']) ? $_POST['search'] : '';
$sql = mysql_query("select * from asset where
name like '%$search%' or
barcode like '%$search%' or
serial like '%$search%' ");
$num = mysql_rows_nums($sql);
$json = array();
if($num > 0)
{
$json['success'] = TRUE;
while ($row = mysql_fetch_array($sql)){
$json['data']['name'] = $row['name'];
$json['data']['barcode'] = $row['barcode'];
$json['data']['serial'] = $row['serial'];
}
}
else
{
$json['success'] = FALSE;
}
return json_encode($json);
?>

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.
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"));
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';
}
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.

Categories