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>
Related
I have searched exhaustively on ways to accomplish this task. I am having issues in turning content within a div into a variable that is able to be processed into a php statement. I have tried using AjaxForm I have tried AJax.
Here is my form code which is under the title "library.php". Here I have a div with the ID "input". I Am trying to get the data in this div which will either be the option "Public" or "Private". I will then proceed to use the button create to submit the data to the database.php
<form method="post" action="library.php" id="form3">
<a id="libOptPP" class="select">
**<div id="input" class="input" name="Privacy">
</div>**
<div id="libOptPP2" class="select-options">
<ul>
<li id="pub" value="1"><span>Public</span> (logo) </li>
<li id="priv" value="2" class="selected"><span>Private</span></li>
</ul>
</div>
</a>
<div class="libOptCS">
<span class="bbCT">
<button type="submit" name="create"> Create </button>
</span>
</div>
</form>
Here is the script that lies within the head of the Library.php where I will try and use ajax to send the variable "privacy" to the Database.php. This variable will contain the text of the div that is stated in the previous block of code. This will either be the option "Public" or "Private". Instead of using the ID name of the div I went ahead and used the classes to select it which is ".select .input".
<script>
$(document).ready(function main() {
$("create").click(function() {
var privacy = $(.select .input).text();
.ajax({
type: "POST",
url: ../../database/database.php,
data: "privacy="+privacy,
dataType: "html",
async: false,
success: function(data) {
alert(data);
}
});
});
});
</script>
Here is the php code for entering the form data into my database. Once we click the create button as stated in the previous code this will activate the transferring of data into its proper table and subsequent rows.
if (isset($_POST["create"])) {
$Privacy = mysqli_real_escape_string($db, $_POST['privacy']);
$ETH = mysqli_real_escape_string($db, $_POST['ETH']);
$Email_Phone_Number = $_SESSION['Email_Phone_Number'];
if ($Privacy === "Public") {
$sql = "INSERT INTO library (Title, Privacy, Bio, User_iD)
VALUES ('$ETH', '$Privacy', 'testbio', (SELECT User_iD FROM logstart WHERE Email_Phone_Number='$Email_Phone_Number'))";
mysqli_query($db, $sql);
}
if ($Privacy === "Private") {
$sql = "INSERT INTO library (Title, Privacy, Bio, User_iD)
VALUES ('$ETH', '$Privacy', 'testbio', (SELECT User_iD FROM logstart WHERE Email_Phone_Number='$Email_Phone_Number'))";
mysqli_query($db, $sql);
}
if (mysqli_query($db, $sql)) {
echo "YES!";
} else {
echo "No!";
}
}
Somewhere along The variable is not being identified. When I press the "create" button A pop up of "unidentified Index: privacy" is created. In other words $_POST['privacy'] does not contain the data that I need it to, which should be Public or Private so that I can identify that and further use the rest of the code.
Your form is posting back the normal way rather than using ajax because of two things:
1) You aren't binding the click event to the button properly - your selector is looking for elements like <create> which of course don't exist.
2) Once that's solved, you forgot to prevent the default postback behaviour of the button. You can sort this either using markup or code. Markup is simpler:
<button id="create" type="button" name="create"> Create </button>
Note the id attribute to uniquely identify the button, and the the type="button" attribute - unless the type is "submit", then it won't cause the form to do a normal postback. Then your event handler should be:
$("#create").click(function() {
Note the # which tells jQuery to look for an element with the id "create".
Another problem: Your PHP contains a logical error. You are calling mysqli_query multiple times for the same query, instead of checking the result of the earlier query. Your if statements to do with the Privacy value also seem to be redundant - you don't change the query as a result. This is how you need to do it:
if (isset($_POST["create"])) {
$Privacy = mysqli_real_escape_string($db, $_POST['privacy']);
$ETH = mysqli_real_escape_string($db, $_POST['ETH']);
$Email_Phone_Number = $_SESSION['Email_Phone_Number'];
$sql = "INSERT INTO library (Title, Privacy, Bio, User_iD)
VALUES ('$ETH', '$Privacy', 'testbio', (SELECT User_iD FROM logstart WHERE Email_Phone_Number='$Email_Phone_Number'))";
$result = mysqli_query($db, $sql); //return the result of the query for checking
if ($result === true) {
echo "YES!";
} else {
echo "No!";
}
}
See also my comment above re SQL Injection vulnerabilities, which is not directly related to your question but does require your urgent attention.
EDIT
There are also a number of other issues with your script, including syntax errors, which are likely to be stopping it from working. Here's a fixed / improved version:
$(document).ready(function() {
$("#create").click(function() {
var privacy = $(".select .input").text();
$.ajax({
type: "POST",
url: "../../database/database.php",
data: { "privacy": privacy },
dataType: "html",
success: function(data) {
alert(data);
}
});
});
});
There were missing speech marks round variables, manual creation of data string (risking encoding issues, which jQuery can take care of for you if you pass it an object), closure which doesn't need a name, and unnecessary use of async: false (it just locks the browser for no good reason).
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.
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 am attempting to send different error messages back to an HTML DIV depending on the PHP outcome. I have searched through here and other place but have been unable to locate an answer that seems to work for my situation... hopefully someone else can help me with this.
My HTML page includes a form that a user is asked to enter a reservation ID # (unique), once the user does this and presses "Search Reservation" a Jquery script is called to send the ID to a PHP script via AJAX. The Data is returned and then is populated into a form using a jquery plugin called, "populate".
Here is the script:
<script type="text/javascript">
$(document).ready(function(){
resetForms('reservation');
$('#form-reservation').submit(function(event){
event.preventDefault(); //the page will no longer refresh on form submit.
var resCheck = $(this).find('input[class="reservationid"]').val(); //now we have the reservation ID, let's perform our check.
$.ajax({
url: 'inc/searchres.php',
type: 'POST',
data: 'resid='+resCheck,
success: function(data){ //data is all the info being returned from the php file
resetForms('reservation'); //clear forms
$('#reservation-id').val(resCheck); //add res ID back into text box
var jsonData = $.parseJSON(data); //parse returned JSON data so we can use it like data.name, data.whatever
$("#res-message").html('<a>Reservation ID Located, Information is displayed below</a>');
$('#json-reservation').populate({personal_first_name:jsonData['element_1_1'],personal_last_name:jsonData['element_1_2'],personal_phone_1:jsonData['element_7'],personal_email:jsonData['element_2'],reservation_status:jsonData['ADD THIS CELL'],reservation_date:jsonData['element_3'],reservation_time:jsonData['element_4'],reservation_party:jsonData['element_5'],reservation_special_request:jsonData['element_6'],reservation_using_coupon:jsonData['element_9'],reservation_coupon_code:jsonData['element_10'],reservation_status:jsonData['element_11']});
},
error: function(){
$("#res-message").html('<a>There was an error with your request</a>');
}
});
});
});
</script>
This was called from the following form (which also includes the DIV in which I would like to populate my error messages, res-message):
<form name="form_reservation" id="form-reservation">
<div style="padding:10px 20px 10px 10px;">
<label for="reservation-id">Reservation ID</label>
<input name="reservation_id" id="reservation-id" class="reservationid" style="width:120px !important"/>
<div class="res_message" id="res-message"> </div>
<input type="submit" class="button" value="Search Reservation" style="width:150px !important; margin:10px 0px 0px 5px;"/>
<input type="button" class="button" value="Clear" style="width:150px !important; margin:10px 0px 0px 5px;" onclick="resetForms('reservation')" />
</div>
</form>
The form that is populated should not be important for this question. Finally the PHP looks like such:
<?php
include('config-searchres.php');
$term = $_POST['resid'];
$sql = mysql_query("SELECT * FROM ap_form_8 WHERE id = '$term'"); //select first name (element_1_1) from form #8
//$sql = mysql_query("SELECT * FROM ap_form_8 WHERE element_12 = '$term'"); //real selector will look for unique number that has not been added to table yet
if ($row = mysql_fetch_array($sql)){ //if reservation number exists
if ($row['element_11'] != 'Cancelled'){ //if reservation has not already been cancelled
if (strtotime($row['element_3']) >= strtotime(date("Y-m-d"))){ //if reservation has not already passed date
echo json_encode($row);
}
else //Reservation already passed (old reservation)
{
echo $error = "Passed";
//echo 'passed';
}
}
else //Reservation already cancelled
{
echo 'cancelled';
}
}
else //Reservation not found
{
echo 'not found';
}
mysql_close();
?>
I know next to nothing about PHP, but I do know that this script seems to work for populating my tables... just not displaying errors for other situations. 3 different errors, 'passed', 'cancelled', and 'not found' need to be passed back during their respective situations. Anyone have an idea?
The quick and dirty solution is to test the returned result to see if it is a string or an array. On your javascript:
(...)
var jsonData = $.parseJSON(data); //parse returned JSON data so we can use it like data.name, data.whatever
if (typeof(jsonData)=='object'&&(jsonData instanceof Array)) {
// jsonData is an array, populate success div
$("#res-message").html('<a>Reservation ID Located, Information is displayed below</a>');
$('#json-reservation').populate({personal_first_name:jsonData['element_1_1'],personal_last_name:jsonData['element_1_2'],personal_phone_1:jsonData['element_7'],personal_email:jsonData['element_2'],reservation_status:jsonData['ADD THIS CELL'],reservation_date:jsonData['element_3'],reservation_time:jsonData['element_4'],reservation_party:jsonData['element_5'],reservation_special_request:jsonData['element_6'],reservation_using_coupon:jsonData['element_9'],reservation_coupon_code:jsonData['element_10'],reservation_status:jsonData['element_11']});
} else {
// jsonData is a simple string, so PHP returned an error. populate error div
$("#res-message").html('<a>There was an error with your request</a>');
}
(...)
Naturally, when handling the error, you can switch on jsonData contents to provide a specific error message if needed.
It seems the issue is that the different error messages from the PHP code are not send as JSON string. So when using 'jsonData = $.parseJSON(data);' it gives and exception.
May be you can try using the below code.
<script type="text/javascript">
$(document).ready(function(){
resetForms('reservation');
$('#form-reservation').submit(function(event){
event.preventDefault(); //the page will no longer refresh on form submit.
var resCheck = $(this).find('input[class="reservationid"]').val(); //now we have the reservation ID, let's perform our check.
$.ajax({
url: 'inc/searchres.php',
type: 'POST',
data: 'resid='+resCheck,
success: function(data){ //data is all the info being returned from the php file
resetForms('reservation'); //clear forms
$('#reservation-id').val(resCheck); //add res ID back into text box
try
{
var jsonData = $.parseJSON(data); //parse returned JSON data so we can use it like data.name, data.whatever
$("#res-message").html('<a>Reservation ID Located, Information is displayed below</a>');
$('#json-reservation').populate({personal_first_name:jsonData['element_1_1'],personal_last_name:jsonData['element_1_2'],personal_phone_1:jsonData['element_7'],personal_email:jsonData['element_2'],reservation_status:jsonData['ADD THIS CELL'],reservation_date:jsonData['element_3'],reservation_time:jsonData['element_4'],reservation_party:jsonData['element_5'],reservation_special_request:jsonData['element_6'],reservation_using_coupon:jsonData['element_9'],reservation_coupon_code:jsonData['element_10'],reservation_status:jsonData['element_11']});
}
catch
{
$("#res-message").html('<a>There was an error with your request</a>');
$('#json-reservation').populate({status:data});
}
}
});
});
});
</script>
I have not tested this code but atleast the logic should work.
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