This is my code so far:
The HTML:
<form>
<label>First Name</label> <input type="text" class="first" /><br />
<label>Last Name</label> <input type="text" class="last" /><br />
<label>Age</label> <input type="text" class="age" /><br />
<input type="button" class="submit" value="Submit" />
</form>
The PHP:
$first = mysql_real_escape_string($_POST['first']);
$last = mysql_real_escape_string($last = $_POST['last']);
$age = mysql_real_escape_string($_POST['age']);
$query = mysql_query( "INSERT INTO people(first, last, age) VALUES ('$first', '$last', '$age')" );
if ($query) {
echo "Success: $first $last has been entered";
} else {
echo "FAIL!!!";
}
The JQuery:
$('.submit').click(function() {
var first = $('.first').val();
var last = $('.last').val();
var age = $('.age').val();
var dataString = 'first=' + first + '&last=' + last + '&age=' + age;
$.ajax({
type: 'post',
url: 'practise_process.php',
data: dataString,
success: function() {
alert('success');
}, error: function() {
alert('error');
}
});
});
Right now I can use the above code to enter form input into a database via the ajax function without refreshing the page. But how can I display something from the PHP script (practise_process.php) to the form page?
this part:
if ($query) {
echo "Success: $first $last has been entered";
} else {
echo "FAIL!!!";
}
EDIT
I made this change to my PHP file:
if ($query) {
$message = "Success: $first $last has been entered";
} else {
$message = "FAIL!!!";
}
echo "
<script type='text/javascript'>
var foo = $message;
</script>
";
and changed the success of the ajax function on my form page to this:
success: function() {
alert(foo);
}
But the var foo which was set on the PHP file isn’t being recognized on the form file.
If you make ‘foo’ the function parameter, it will receive whatever is echo’d out from the PHP file. You can then use JS to alert() it to the user or display it. Additionally, if you use mysqli for your db connection you can echo out m
ysqli_error($dbLink);to alert the SQL error if there is one. The JS variable must be set on the client-side, but it can be fed by your PHP on the server-side.