PDA

View Full Version : Resolved Help with passing arguments with AJAX



Schmoopy
03-07-2009, 11:14 PM
Hey there, I have the following javascript code:



function sendRequest() {
new Ajax.Request("appointments.php",
{
method: 'post',
parameters: {
name: $F('name'),
date: $F('date'),
time: $F('time'),
where: $F('where'),
phone_no: $F('phone_no'),
job_desc: $F('job_desc'),
quoted_price: $F('quoted_price')
},
onComplete: showResponse
});
}

function showResponse(req, error){
clearForm();
animatedcollapse.toggle('addapp')
if (error == 0)
$('appdiv').innerHTML= req.responseText;

else{
$('response').innerHTML=req.responseText;
}

}


It's prototype code just in case you were wondering, but basically I want to pass an error value from PHP to this code here and if there are no errors it will respond in one div, and if there are errors, it will respond in a different div.

The thing is I don't know how I can pass this error value to the function, my knowledge on JavaScript is limited so I don't know how you'd do it.

Here is the whole PHP file, you don't need it all just focus on the bits that say $error = 1;



<?php
require_once("includes/connection.php");
require_once("includes/functions.php");
date_default_timezone_set("Europe/London");
$datenow = date("Y-m-d");
$error = 0;
/* Adds new appointments - Checks for valid fields before submitting to database */

// START VALIDATION

$fields = array('name','date','time','where','phone_no','job_desc','quoted_price');

foreach($fields as $field)
{
if(empty($_POST[$field]))
{
die("You must complete all fields");
}
else
{
$$field = mysql_real_escape_string($_POST[$field]); // Variable within a variable, sanitize variable
}
}

$formatdate = explode("/",$date); // Strip slashes from date and put year, month and day into array
$fulldate = $formatdate[2] . "-" . $formatdate[1] . "-" . $formatdate[0]; // Format date from DD/MM/YYYY -> YYYY-MM-DD

if($fulldate < $datenow)
{
$error = 1;
die("You can't enter a date that has already past!");
}

$timenow = strftime("%H:%M");
if($time < $timenow)//If time before time now and date is today -> Delete
{
$error = 1;
die("You can't enter a time that has already past!");
}

// END VALIDATION

$query = "INSERT INTO appointments (`name`, `date`, `time`, `where`, `phone_no`, `job_description`, `quoted_price`)
VALUES('$name', '$fulldate', '$time', '$where', '$phone_no', '$job_desc', '$quoted_price')";

if(!mysql_query($query))
{
die("Failed to create" . mysql_error());
}
else
{
$refresh = mysql_query("SELECT * FROM appointments WHERE date = '$datenow' ORDER BY date, time");

if (mysql_num_rows($refresh))
{
echo "<table id=\"apptable\">\n<tr class=\"headings\"><th class=\"first\">Name</th><th>Time</th><th>Where</th><th>Phone No.</th><th>Job Description</th><th>Quoted Price</th></tr>\n";

while($row = mysql_fetch_array($refresh)) // Go through all records in the database, echo the following code for each record found
{
echo "<tr class=\"data\""; if (AppSoon($row['time'])) { echo "style=\"background-color:#FF7348;\" title=\"This appointment starts within an hour!\""; $appsooncount = true; } echo "><td>" . $row['name'] . "</td><td>";

echo FormatTime($row['time']);

echo "<td>" . $row['where'] . "</td><td>" . $row['phone_no'] . "</td><td>" . $row['job_description'] . "</td><td>&pound;" . $row['quoted_price'] . " </td><td class=\"last\"><a class=\"remove\" onclick=\"RemoveApp("; echo $row['id']; echo ")\" href=\"#\"></a></td></tr>\n";
}
echo "</table>";

if(isset($appsooncount) && ($appsooncount))
echo "<div id=\"appsoon\">Appointments with this background colour start within the hour.</div>";

}
else
{
die("No appointments scheduled.");
}
}

mysql_close($con);

?>


So, basically how could I pass this variable from the PHP to the javascript file? At the moment all it gets is the text, so I need to add this in somehow.

Thanks for any help you guys can come up with :)

Schmoopy
03-08-2009, 07:51 PM
Ok I've added a bit to my code - still not working but I may be going down the right track.

Here's my js file:



function validate() {
new Ajax.Request("validateapp.php",
{
method: 'post',
parameters: {
name: $F('name'),
date: $F('date'),
time: $F('time'),
where: $F('where'),
phone_no: $F('phone_no'),
job_desc: $F('job_desc'),
quoted_price: $F('quoted_price'),
},
onComplete: ShowErrors
});
}

function ShowErrors(req)
{
$('response').innerHTML=req.responseText;
}

function sendRequest() {
new Ajax.Request("appointments.php",
{
method: 'post',
parameters: {
name: $F('name'),
date: $F('date'),
time: $F('time'),
where: $F('where'),
phone_no: $F('phone_no'),
job_desc: $F('job_desc'),
quoted_price: $F('quoted_price'),
},
onComplete: showResponse
});
}

function showResponse(req){
clearForm();
animatedcollapse.toggle('addapp')
$('appdiv').innerHTML= req.responseText;
}

function clearForm()
{
document.getElementById('name').value = "";
document.getElementById('date').value = "";
document.getElementById('time').value = "";
document.getElementById('where').value = "";
document.getElementById('phone_no').value = "";
document.getElementById('job_desc').value = "";
document.getElementById('quoted_price').value = "";
}

function refreshTable(req){
$('appdiv').innerHTML= req.responseText;
}

function RemoveApp(id)
{
var response = confirm('Are you sure you want to delete the appointment?');
if (response == true)
{
new Ajax.Request("removeapp.php",
{
method: 'post',
postBody: 'id=' + id,
onComplete: refreshTable
});
}
else{
return false;
}
}


And relevant HTML:



<div id="addapp">
<form name="appform" id="addappform" onsubmit="return false;"> <!-- Stop the form from being submitted so AJAX code is called instead -->
<label for="name">Name:</label> <input type="text" name="name" id="name"/><br />
<label for="date"><a href="javascript:showCal('appcal')">Select Date:</a> </label> <input type="text" name="date" id="date"/><br />
<label for="time">Time:</label> <input type="text" name="time" id="time"/><br />
<label for="where">Where:</label> <input type="text" name="where" id="where"/><br />
<label for="phone_no">Phone No:</label> <input type="text" name="phone_no" id="phone_no"/><br />
<label for="job_desc">Job Description:</label> <input type="text" name="job_desc" id="job_desc"/><br />
<label for="quoted_price">Quoted Price:</label> <input type="text" name="quoted_price" id="quoted_price"/><br />
<input class="submit" type="submit" name="submit" value="Add Appointment" onclick="validate() && sendRequest();"/>
<div id="response">

</div>
</form>
</div>


So what it does now is send off the form, pass it to "validateapp.php", which then does some checks and then is *supposed* to send it off to the sendRequest function if no errors occurred, otherwise it will echo back an error in another div.

validateapp.php:



<?php
session_start();
require_once("includes/connection.php");
require_once("includes/functions.php");
if(!LoggedIn())
{
$login = "login.php?login=no";
redirect_to($login);
}
date_default_timezone_set("Europe/London");
$datenow = date("Y-m-d");

// START VALIDATION

$fields = array('name','date','time','where','phone_no','job_desc','quoted_price');

foreach($fields as $field)
{
if(empty($_POST[$field]))
{
die("You must complete all fields");
}
else
{
$$field = mysql_real_escape_string($_POST[$field]); // Variable within a variable, sanitize variable
}
}

$formatdate = explode("/",$date); // Strip slashes from date and put year, month and day into array
$fulldate = $formatdate[2] . "-" . $formatdate[1] . "-" . $formatdate[0]; // Format date from DD/MM/YYYY -> YYYY-MM-DD

if($fulldate < $datenow)
{
die("You can't enter a date that has already past!");
}

$timenow = strftime("%H:%M");
if($time < $timenow)//If time before time now and date is today -> Delete
{
die("You can't enter a time that has already past!");
}

// END VALIDATION

return true;
?>


So as you can see at the end I tried returning true, I know it wouldn't really do anything as it has to pass it back through AJAX and echo an error message or it does nothing.

At the moment if no errors occurr then nothing happens, I imagine this is because there is nothing for the ShowErrors function to echo back. Which leads me back to passing arguments to the ShowErrors function, to see if any errors occurred.

This is really integral to my project, please someone help!

Thanks.

Schmoopy
03-09-2009, 07:10 PM
Ok well I've done it now, I just changed the return to say "1" if there wasn't an error and then called another function to add to the database...

Here is the full code just in case anyone wants to know, this is probably really inefficient and could be done in a much simpler way, but with my limited knowledge in JavaScript / AJAX requests it's the best I could do:

addapp.js:



function validate() {
new Ajax.Request("validateapp.php",
{
method: 'post',
parameters: {
name: $F('name'),
date: $F('date'),
time: $F('time'),
where: $F('where'),
phone_no: $F('phone_no'),
job_desc: $F('job_desc'),
quoted_price: $F('quoted_price'),
},
onComplete: ShowErrors
});
}

function ShowErrors(req)
{
if(req.responseText == 1)
{
sendRequest()
}
else
{
$('response').innerHTML=req.responseText;
var disappear = setTimeout("document.getElementById('response').innerHTML=''", 3000);
}
}

function sendRequest() {
new Ajax.Request("appointments.php",
{
method: 'post',
parameters: {
name: $F('name'),
date: $F('date'),
time: $F('time'),
where: $F('where'),
phone_no: $F('phone_no'),
job_desc: $F('job_desc'),
quoted_price: $F('quoted_price'),
},
onComplete: showResponse
});
}

function showResponse(req){
clearForm();
animatedcollapse.toggle('addapp')
$('appdiv').innerHTML= req.responseText;
}

function clearForm()
{
document.getElementById('name').value = "";
document.getElementById('date').value = "";
document.getElementById('time').value = "";
document.getElementById('where').value = "";
document.getElementById('phone_no').value = "";
document.getElementById('job_desc').value = "";
document.getElementById('quoted_price').value = "";
}

function refreshTable(req){
$('appdiv').innerHTML= req.responseText;
}

function RemoveApp(id)
{
var response = confirm('Are you sure you want to delete the appointment?');
if (response == true)
{
new Ajax.Request("removeapp.php",
{
method: 'post',
postBody: 'id=' + id,
onComplete: refreshTable
});
}
else{
return false;
}
}


validateapp.php


<?php
session_start();
require_once("includes/connection.php");
require_once("includes/functions.php");
if(!LoggedIn())
{
$login = "login.php?login=no";
redirect_to($login);
}
date_default_timezone_set("Europe/London");
$datenow = date("Y-m-d");

// START VALIDATION

$fields = array('name','date','time','where','phone_no','job_desc','quoted_price');

foreach($fields as $field)
{
if(empty($_POST[$field]))
{
die("You must complete all fields.");
}
else
{
$$field = mysql_real_escape_string($_POST[$field]); // Variable within a variable, sanitize variable
}
}

$formatdate = explode("/",$date); // Strip slashes from date and put year, month and day into array
$fulldate = $formatdate[2] . "-" . $formatdate[1] . "-" . $formatdate[0]; // Format date from DD/MM/YYYY -> YYYY-MM-DD

if($fulldate < $datenow)
{
die("You can't enter a date that has already passed!");
}

if($time)

$worktime = substr($time, 0, 2) . substr($time, 3, 2); // Strip colon from time

$timenow = strftime("%H%M");
if($worktime < $timenow && $fulldate == $datenow)//If time before time now and date is today -> Do not allow into database
{
die("You can't enter a time that has already passed!");
}

if($worktime > 1800 || $worktime < 800)
{
die("Time is not within working hours.");
}

// END VALIDATION
$valid = 1;
echo $valid;
?>