I've got an HTML form that uses jQuery serialize method and ajax to post results using PHP into a sqlite database. I've set the jQuery to run every minute to act as an autosave feature so users can return later to finish what they started. Because of the autosave, I can't force all inputs be required.
It works 99% of the time. However, in a few cases, the application sometimes posts blank data to the database even though there is data in the input fields. I've checked to make sure all the HTML input fields have name attributes. Any ideas why it works most of the time but in a few random cases, it doesn't?
I wish I had more to report why it doesn't work all the time. I haven't been able to replicate the bug myself, I'm just going on reports of users. But I know the form is posting blanks into the database because when I go into the database, it says " " instead of "null". So I know the database is receiving something, but it isn't receiving the data the user typed.
HTML
<form action="" method="post" id="evaluationForm">
<!-- this input is disabled since this user can't edit it -->
<label for="FirstName">First Name</label>
<input type="text" name="FirstName" value="<?php echo htmlspecialchars($data['FirstName']);?>" disabled >
<label for="WorkHabitsCommentsSuper">Comments </label><br>
<textarea name="WorkHabitsCommentsSuper" placeholder="Comments are optional">
<?php echo htmlspecialchars($data['WorkHabitsCommentsSuper']);?>
</textarea>
<label for="GoalsSuper">More Comments</label>
<textarea name="GoalsSuper" required>
<?php echo htmlspecialchars($data['GoalsSuper']);?>
</textarea>
<!-- and a whole bunch more fields but you get the idea -->
</form>
JavaScript
function saveEval() {
var datastring = $("form").serialize();
$.ajax({
type: "POST",
url: "autosave-s.php",
data: datastring,
success: function(text) {
if (text == "success") {
alert('It saved. Hooray!');
} else {
alert('Oh no. Something went wrong.');
}
}
});
}
window.onload = function() {
setInterval("saveEval()", 60000)
}
PHP
$db = new PDO('sqlite:evals.sqlite');
$sql = "UPDATE table SET
WorkHabitsCommentsSuper = :WorkHabitsCommentsSuper,
GoalsSuper = :GoalsSuper";
$query = $db->prepare($sql);
$query->execute(array(
':WorkHabitsCommentsSuper' => $_POST['WorkHabitsCommentsSuper'],
':GoalsSuper' => $_POST['GoalsSuper']
));
echo "success";
if(!in_array("",$_POST)){
$db = new PDO('sqlite:evals.sqlite');
$sql = "UPDATE table SET
WorkHabitsCommentsSuper = :WorkHabitsCommentsSuper,
GoalsSuper = :GoalsSuper";
$query = $db->prepare($sql);
$query->execute(array(
':WorkHabitsCommentsSuper' => $_POST['WorkHabitsCommentsSuper'],
':GoalsSuper' => $_POST['GoalsSuper']
));
echo "success";
}else{
echo "Empty";
}
This will check if the posting data is not empty if empty any of the field it will not update and will send 'Empty' response so alert on empty data posting.
Related
I am creating a page for blog posts and I am having some trouble with getting my 'Like' (Heart) function to work using AJAX.
It needs to submit when the heart is clicked which should submit a new row into my PHP database without page refresh, but the form submission is not working/posting.
This is my first time submitting form using AJAX so sorry if I'm being a noob.
My PHP table has 5 columns - id, content, userID, username & date.
$(document).ready(function() {
$("#heart").click(function() {
if ($("#heart").hasClass("liked")) {
$("#heart").html('<i class="fa fa-heart-o" aria-hidden="true"></i>');
$("#heart").removeClass("liked");
} else {
$("#heart").html('<i class="fa fa-heart" aria-hidden="true"></i>');
$("#heart").addClass("liked");
$("form#myform").submit(function(event) {
event.preventDefault();
var title = $("#title").val();
var user = $("#user").val();
var userID = $("#userID").val();
var dte = $("#dte").val();
$.ajax({
type: "POST",
url: "../PHP/user_functions.php",
data: "title=" + content + "&user=" + user + "&dte=" + dte + "&userID=" + userID,
success: function(){alert('success');}
});
});
}
});
});
.fa-heart-o {
font-size:24px;
color:black;
cursor: pointer;
}
.fa-heart {
font-size:24px;
color: red;
cursor: pointer;
}
.ggg{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<form id="myform" action="../PHP/user_functions.php" method="post">
<span class="" id="heart"><i class="fa fa-heart-o" aria-hidden="true"></i></span>
<input type="hidden" id="title" value="How To Guide Title Example" name="content">
<input type="hidden" id="user" value="TestBot" name="username">
<input type="hidden" id="userID" value="<?php echo $userID ?>" name="sessionID">
<input type="hidden" id="dte" value="<?php echo date('Y/m/d H:i:s'); ?>" name="date">
<input class="ggg" type="submit" id="submitButton" name="submitButton" value="Submit">
</form>
and my PHP page..
<?php
if (isset($_POST['submitButton'])) {
$username = $_POST['username'];
$userID = $_POST['userID'];
$date = $_POST['date'];
$content = $_POST['content'];
$sql = 'INSERT INTO `likes-blog` (username, userID, date, content) VALUES (:username, :userID, :date, :content)';
$stmt = $dbh->prepare($sql);
$stmt->execute(['username' => $username, 'userID' => $userID, 'date' => $date, 'content' => $content]);
?>
<?php
}
?>
In your backend/PHP file, treat it as if the POST data is always getting passed into it.
Think about this: You're only going to run the code that's controlling the data to be sent to your database when $_POST['submitButton'] is passed to the page. When you're sending your data to your PHP file, it does nothing because you're telling it to only run that code if $_POST['submitButton'] is set (has a value).
Secondly, I want to mention that in your ajax, it's much easier to structure the POST data like this, and also cleaning up the success function to look a little better; you can also pass through a response like I've shown here, that the PHP file will send back in case of an error or you can have your PHP file send back a custom string with a success message:
$.ajax({
type: "POST",
url: "../PHP/user_functions.php",
data: {
title: content,
user: user,
dte: dte,
userID: userID
},
success: function(response) {
alert(response);
}
})
I would also definitely look into MySQLi prepared statements and looking at how to better protect against SQL injection.
Take a look at these PHP functions and how to use them, I've written up a very basic example of something you could use, but you can also change it to fit your needs, just make sure you use the functions properly:
// Data:
$dataOne = 5; // <-- integer
$dataTwo = "Hello, world" // <-- string
// in the ...bind_param() function, where "is" is located, in order, you'd use i for integer and s for string, there are others but these are the basic ones, you can find more documentation online for this.
// For example if you passed through the $dataTwo variable and then the $dataOne variable, it would be "si" because the variable with string content gets passed first and the variable with an integer passed second.
// For the ? marks in the $sql string, those directly relate to how many values you're going to pass through. In the computer, ? will be translated to each value passed through in the ...bind_param() function, in order, and insert them into the selected table/columns, in order. Basically, the code below will insert $dataOne into the "column1Name" column and will insert $dataTwo into the "column2Name" column in the "tableName" table.
$sql = "INSERT INTO "tableName" ("column1Name", "column2Name") VALUES (?, ?);";
$stmt = mysqli_stmt_init($conn)
or die("Could not initiate a connection.");
mysqli_stmt_prepare($stmt, $sql)
or die("Could not prepare SQL statement.");
mysqli_stmt_bind_param($stmt, "is", $dataOne, $dataTwo)
or die("Could not bind SQL parameters.");
mysqli_stmt_execute($stmt)
or die("Could not execute SQL sequence.");
mysqli_stmt_close($stmt)
or die("Could not close SQL connection.");
Seems complicated and there is more to learn, but instead of being like everyone else on here that just expects you to figure it out yourself, I figured I'd give you an example. I'd also recommend learning how to wash your POST data once your AJAX sends it to your PHP file. You can also use the above method for securely deleting and updating rows/columns/values in your database. (If you're not actually inserting data, for example if you're using a delete statement, you can simply not use the ...bind_param() function since it would serve no purpose there.
Also, I believe part of your issue is that you're also submitting the form itself and I don't think even executing the Ajax code. Part of the reason why ajax is useful is because it allows you to submit POST and GET data to an external handler file (your PHP/backend code/file) without having to have the page reload, which has many other benefits, there are only some cases where you'd actually HAVE to submit the form like would be done by default without ajax. Technically, you don't even need to use a form if you're using ajax, in most cases. (but not all). For example you could get rid of the tags altogether, and just have your inputs stay as normal; you can use JS to grab the values. Set your submit button to type="button" (if it's set to submit, the page will reload, which kind of defeats the purpose; type="button" will not reload the page).
So, here's a rough example of what I'm talking about:
HTML:
<input type="text" id="firstName" name="firstName" placeholder="What's your first name?"/>
<input type="text" id="lastName" name="lastName" placeholder="What's your last name?"/>
<button type="button" id="submit">Submit</button>
And your JavaScript w/ ajax:
$("#submit").on("click", () => {
// Get the current value of the input textbox:
let first = document.querySelector("#firstName").value;
let last = document.querySelector("#lastName").value;
if (firstName !== null) {
// Send data to PHP file:
// Keep in mind when only sending single data values, you can do it like shown here:
$.ajax({
type: "POST",
url: "path to php file here",
data: {
firstName: first,
lastName: last
}
success: function(response) {
// The following is an example of something you can use to error handle. Have the PHP file handle all the errors and simply make the PHP code respond with 1/true if the code was executed correctly, or if there was an issue, have it respond with false/0:
if (response == 1) {
alert("You've successfully submitted the form.");
} else if (response == 0) {
alert("Sorry, there was an error submitting the form.");
}
}
})
}
})
PHP example:
<?php
require("path_to_database_connect_file"); // I never recommend creating a connection inside another file, so do something like this instead. Have a separate PHP file where its sole purpose is creating and starting a connection with your database. I used the connection variable as $conn, it seems in your original question you were using $dbh. The variable name doesn't really matter I just prefer $conn.
$data = array_filter($_POST);
$first = $data['firstName'];
$last = $data['lastName'];
$sql = "INSERT INTO names (firstName, lastName) VALUES (?, ?);";
$stmt = mysqli_stmt_init($conn)
or exit(false);
mysqli_stmt_prepare($stmt, $sql)
or exit(false);
mysqli_stmt_bind_param($stmt, "ss", $first, $last)
or exit(false); // Both $first and $last have type "string", so the passthrough right after $stmt in this function is "ss" for string-string. If $last was an integer, it would be "si" for string-integer, in that order. Though, if you don't mind everything in your database being string types, which is usually fine for basic stuff, you can still just use "s" for everything. So if you're passing 5 variables into 5 different table columns, you could just do "sssss" there.
mysqli_stmt_execute($stmt)
or exit(false);
mysqli_stmt_close($stmt)
or exit(false);
echo true; // If any of the above code fails, it will return false back to ajax in the response callback and exit the script, ajax will see the returned value of "response" as "0" and you will receive the alert message of "Sorry, there was an error submitting the form.". If everything works smoothly with no errors, this script will echo or "return" true back to ajax, and ajax will read "true" as "1", therefore in the success method as shown above, you should get the alert message: "You've successfully submitted the form."
Try this
<script>
$(document).ready(function() {
$("#heart").click(function() {
if ($("#heart").hasClass("liked")) {
$("#heart").html('<i class="fa fa-heart-o" aria-hidden="true"></i>');
$("#heart").removeClass("liked");
} else {
$("#heart").html('<i class="fa fa-heart" aria-hidden="true"></i>');
$("#heart").addClass("liked");
let title = $("#title").val();
let user = $("#user").val();
let userID = $("#userID").val();
let dte = $("#dte").val();
//Ajax
$.ajax({
url: "../backend.php", //This your backend file PHP
data: {
"title": title,
"user" : user,
"userID" : userID,
"dte" : dte
},
dataType: "JSON",
type: "POST",
beforeSend: function() {
//Function for sweetalert like loading or any
},
success: function(data) {
//if succes
console.log(data);
},
complete: function() {
//Function while ajax complete
},
error: function(data) {
//if error
console.log("ERROR");
console.log(data);
}
});
}
});
});
</script>
I've been searching for this kind of problem and I couldn't find one. I am using ajax to solve this problem but it didn't work out. I really want to have this scenario where after the user scanned his/her QR code, its data (account ID) will be in the input field. Then the other input field will automatically show its corresponding data from the database based on the data from QR code. This is so far my code.
This is from the main page:
<label id="acc">Account ID
<input type="text" name="accId" id="accID" class="idnum" required="" value="">
</label>
<label id="label">QR ID
<input type="text" readonly=" " name="qrId" id="qrId" style="width: 108px;margin-right: 15px;" value="" >
</label>
Ajax:
<script>
$("#accID").change(function() {
var accID = $(this).val();
$.ajax({
url: 'loadata.php',
type: 'POST',
data: 'accID='+accID,
success: function(html) {
$("#qrId").html(html);
}
});
});
</script>
this is the loadata.php:
<?php
session_start();
include ('connection.php');
if(isset($_POST['accID']))
{
$accID = $_POST['accID'];
$sel = "SELECT * FROM qrcode WHERE Cus_IDNum = '$accID'";
$sel_run = $conn->query($sel);
if($sel_run->num_rows>0)
{
while($rows = $sel_run->fetch_assoc())
{
?>
<input type="text" readonly=" "id="qrId" name="qrId" style="width: 108px;margin-right: 15px;" value="" >
<?php
}
}
}
?>
Thank you very much for your time! :)
Are you getting any data to return? Have you tried changing your input field in loadata.php to a div with the same ID? Right now you're trying to place an input within an input.
Also, you don't need to wrap your inputs within the label. As long as the label and input share the same ID, they will always be together. Currently, you are not doing that.
Setting $("#qrId").html(html); will do nothing, as #qrId is an input field. I think, what you want to do is to set the value of the input field.
This should work like this: $("#qrId").val(html);
Then, there is a second problem as your PHP script returns HTML of an input field rather than just the value to set. Also, it may return multiple values as you loop through the database results.
You could try to change your script to something like this to just return the value of the first selected database record. Replace qrCodeValue with the real column name to use:
<?php
session_start();
include ('connection.php');
if(isset($_POST['accID']))
{
$accID = $_POST['accID'];
$sel = "SELECT * FROM qrcode WHERE Cus_IDNum = '$accID'";
$sel_run = $conn->query($sel);
if($sel_run->num_rows>0)
{
$row = $sel_run->fetch_assoc();
print $row['qrCodeValue'];
exit;
}
}
?>
I've got some code that works nicely for saving to the database etc. What i'd like to do now is after the fields are saved, i want the echoed last id to be populated to a hidden field so i can use that to determine any future insert/update queries.
My form is:
<div id="formHolder">
<form type="post" action="add_room.php" id="mainForm">
<label for="itemName[]">Item</label>
<input type="text" name="itemName[]">
<label for="itemPhoto[]">Item</label>
<input type="text" name="itemPhoto[]">
<input type="hidden" name="hiddenId[]" value="">
<div class="save">Save Item</div>
</form>
</div>
my jQuery is:
<script>
$(document).ready(function() {
$('body').on('click', '.save', function(e) {
var string = $(this).closest('form').serialize();
$.ajax({
type: "POST",
url: "add_room.php",
data: string,
cache: false,
success: function(data){
$('#message').text('The id of the inserted information is ' + data);
}
});
});
});
$(document).ready(function(){
$('#addForm').on('click', function(){
$('<form><label for="itemName[]">Item</label><input type="text" name="itemName[]"><label for="itemPhoto[]">Photo</label><input type="text" name="itemPhoto[]"><input type="hidden" name="hiddenId[]" value=""><div class="save">Save Item</div></form>').fadeIn(500).appendTo('#formHolder');
});
});
</script>
and finally my php is:
<?PHP
include('dbConfig.php');
$item = $_POST['itemName'];
$photo = $_POST['itemPhoto'];
foreach($item as $key => $val) {
if ($stmt = $db->prepare("INSERT test (test_title, test_desc) VALUES (?, ?)"))
{
// Use an s per variable passed to the string, example - "ss", $firstname, $lastname
$stmt->bind_param("ss", $val, $photo[$key]);
$stmt->execute();
$stmt->close();
echo $db->insert_id;
//echo "success";
}
// show an error if the query has an error
else
{
echo "ERROR: Could not prepare SQL statement.";
}
}
?>
Everything works nicely for adding field data to the database, adding extra fields etc. I just cannot get it to save the echoed id of each ajax post to save to the hidden field, yet it saves it to the #message div no problem. Any ideas? I have tried using .val(); but it didn't work, i'm stumped
Andy
try this within success function
$("[type=hidden]").val(data);
or if you able to set the hidden field id thats much better like this
<input type="hidden" name="hiddenId[]" id="hiddenId" value="">
code will be like this
$("#hiddenID").val(data);
Hope it will help
You can use the following code
$("[type=hidden").val(data);
or
$("#hiddenId").attr("value",data);
Your data variable in the ajax success function contains all output from your php file so if you are adding multiple items, it will be a string with all newly added ID's concatenated together.
What I would do is something like:
use a counter in the html form-fields so that you know exactly what fields to address, something like: <input type="text" name="itemName[1]">;
add this key and the value to an array in your php instead of echoing it out: $array[$key] = $db->insert_id;;
after your php insert loop, echo out the data you need on the javascript side: echo json_encode($array);
loop through your data in the ajax success function to assign the right values to the right elements.
You'd probably need to change your ajax call a bit to accept json.
I want to make a form submit without refreshing page in jquery.
But I have no idea why the data didn't insert into the database. Are there any problems in the code below?
Before that, I had referred to here, I hope I didn't write it wrong.
HTML
<form id="submit">
<fieldset><legend>Enter Information</legend> <label for="fname">Client First Name:</label>
<input id="vName" class="text" type="text" name="vName" size="20" />
<label for="lname">Client Last Name:</label>
<input id="vLat" class="text" type="text" name="vLat" size="20" />
<input id="vLng" class="text" type="text" name="vLng" size="20" />
<input id="Add" class="text" type="text" name="Add" size="20" />
<button class="button positive"> <img src="../images/icons/tick.png" alt="" /> Add Client </button></fieldset>
</form>
Javascript
$("form#submit").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var vName = $('#vName').val();
var vLat = $('#vLat').val();
var vLng = $('#vLng').val();
var Add = $('#Add').val();
$.ajax({
type: "POST",
url: "ajax.php",
data: "vName="+ vName +"& vLat="+ vLat +"& vLng="+ vLng +"& Add="+ Add,
success: function(){
$('form#submit').hide(function(){$('div.success').fadeIn();});
}
});
return false;
});
dbtools.inc.php
<?php
function create_connection()
{
$link = mysql_connect("localhost", "root", "52082475");
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
mysql_query("SET NAMES utf8");
}
function execute_sql($database, $sql, $link)
{
$db_selected = mysql_select_db($database, $link)
or die("Fail <br><br>" . mysql_error($link));
$result = mysql_query($sql, $link);
return $result;
}
?>
ajax.php
<?php
include ("dbtools.inc.php");
$link = create_connection();
// CLIENT INFORMATION
$vName = htmlspecialchars(trim($_POST['vName']));
$vLat = htmlspecialchars(trim($_POST['vLat']));
$vLng = htmlspecialchars(trim($_POST['vLng']));
$Add = htmlspecialchars(trim($_POST['Add']));
$sql = "INSERT INTO map_db (vName,vLat,vLng,add) VALUES ('$vName','$vLat','$vLng','$Add')";
$result = execute_sql("map",$sql,$link);
mysql_close($link);
header("location:add.html");
exit();
?>
For starters your PHP code is not safe (look up sql injection and prepared statements). Next make your PHP code echo/print something- the result of the query. For example, you may want to use JSON or XML to print the result of the query (good||bad). That way the ajax can use this in the success function to determine if the query was successful or not and can thus display an error or success message appropriately.
Also respond to errors in the ajax request (Reference here). For example:
ajax.({
url:..,
....
error: function() {
...
}
});
By interpreting the response from your PHP you should be able to determine what the cause of the error is (bad mysql connection, query, syntax, url, data, etc).
Goodluck.
i think there is a syntax error in data field of your ajax post method...
if you want to post entire form, then use...
var formData= $('form').serialize();
data: formData
or use below code to send individual parameters...
data: { 'vName' : vName, 'vLat' : vLat, 'vLng' : vLng}
i'm not familiar with php style of coding... but this works well with c# method signatures... change your code in php according to the posted data fields
NOTE: use preventDefault() in your submit method, for not to redirect/refresh your page
If you want to submit form data there is no need to use form tags instead use a button like this
<input type = 'image' src ='blah blah' id = 'submit'>
Also i see here you are using submit event instead use click event.
You should not close the connection in create_connection() I guess. That function exists to open a new one :)
Oh, and it seems that you want to return the $link from the same method too, even if you don't really need all that code (neither an explicit mysql_close() nor using the $link, unless you happen to connect to two or more different databases in the same script).
The server side code seems very weak and insecure. If it's a pet project it's ok, but if can become anything serious, you should watch out for sql injections and PHP vulnerabilities, or use a PHP framework which usually handles this for you
I'm quite new to PHP & MySQL and at the minute I have a web page with several text boxes that displays data that is in my database. I would like to know how I would go about updating the data by making changes to the textboxes so that when the user clicks 'update' these changes are then implemented in the database.
Currently I have the following code:
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("booking", $con);
$result = mysql_query("SELECT * FROM tblcompany");
$compDetails = mysql_fetch_array($result);
?>
And here is some of the HTML:
<div class="cp-controls-lrg left">
<p class="controls-margin">Company Name</p>
<input type="text" class="input-txt-med" value="<?php echo $compDetails['CompName'] ?>" id="txt-config-fax" value="" size="20">
</div>
<div class="cp-controls-lrg left">
<p class="controls-margin">Company URL</p>
<input type="text" class="input-txt-med button-space2" value="<?php echo $compDetails['CompURL'] ?>" id="txt-config-email" value="" size="50">
</div>
<div class="cp-button2 config-but-space right">
<button name="btn-config-done" id="btn-config-done" class="btn-sml ui-button ui-state-default ui-button-text-only ui-corner-all btn-hover-anim btn-row-wrapper right cp-btn-margin">Done</button>
<button name="btn-config-update" id="btn-config-update" class="btn-sml ui-button ui-state-default ui-button-text-only ui-corner-all btn-hover-anim btn-row-wrapper right cp-btn-margin">Update</button>
</div>
Any help would be much appreciated!
I assume from the tag that you want to use AJAX to achieve this.
I would first try to do the update by posting the form back using POST.
Put your HTML code into a form tag and try to POST data back to PHP page.
Here's just one example on how to do it (Google/Bing is your friend):
http://www.tizag.com/phpT/forms.php
http://www.freewebmasterhelp.com/tutorials/phpmysql/4
Then look up Insert and Update statements as suggested above and try to do the same with your data.
AJAX works in a similar way, there is a processor on the server side and the only difference is that the form doesn't get submitted via POST (page reload) but it's submitted using JavaScript.
I would also look into jQuery library to do the AJAX postbacks for you.
HTH
jQuery is excellent for ajax. You can use something like this in your javascript file whatever.js.
$('#btn-config-update').click(function () {
$.ajax({
type : 'POST',
url : 'http://whatever.com/handler.php',
dataType : 'json',
data: {
companyname : $('#companyFieldID').val(),
url : $('#companyURLID').val(),
},
success: function (data) {
if (data.status == "Success") {
$('#id_of_div_to_replace_markup').html(data.markup);
} else if (data.status == "Error"){
$('#optional_error_markup_container_div').html(data.markup);
} else {
$('#optional_error_markup_container_div').html("<span id=formError>Unexpected Error</span>");
}
}
});
return false;
});
Things to note here. Use id='whateverid" not class="whateverclass" inside of your input markup fields, so that you can get the data out of the input fields using the .val() statements that you see above. the # references in jQuery refer to a unique id.
Also the return false prevents the page from refreshing.
now for the PHP side.
$sql_error_markup = "<h1>An unexpected error has occured. Please try again later.</h1>";
$success_markup = "<h2><p>Database has been updated!</p></h2>";
$companyname = mysql_real_escape_string($_POST["companyname"]);
$url = mysql_real_escape_string($_POST["url"]);
//use your connection logic to get $con
$sql="INSERT INTO tablename (company_field_name, url_field_name)";
$sql.= " VALUES('$companyname','$lastname','$email')";
if (!mysql_query($sql,$con)) {
$return['markup'] = $sql_error_markup;
$return['status'] = "Error";
echo json_encode($return);
die('Error: ' . mysql_error());
}
mysql_close($con);
$return['status'] = "Success";
$return['markup'] = $success_markup;
echo json_encode($return);
?>
Things to note echo json_encode(array) will respond to the ajax call properly. This ajax example can swap out markup using the html method of anything with an id (not class in this example). mysql_real_escape_string will help prevent injection attacks. Extrememly necessary for this sort of form. Don't forget to include jquery.versionwhatever.js to use the $ references that you see above.
Good luck.