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
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'm a AngularJS and PHP newbie and I'm trying to add some data into MySQL. But MySQL table shows empty value instead of the data I want to insert.
HTML:
<form data-ng-controller="myCtrl">
<label for="roomName">Room Name: </label>
<input type="text" name="roomName" data-ng-model="roomName" id="roomName" />
<br />
<label for="maxPerson">Maximum Person: </label>
<input type="text" name="maxPerson" data-ng-model="maxPerson" id="maxPerson" />
<button type="submit" class="btn btn-default" data-ng-click="addRoom()">Add</button>
</form>
app.js (Controller)
app.controller("myCtrl", function ($scope, $http) {
"use strict";
$scope.addRoom = function () {
$http.post("add_library_room.php", {'roomName': $scope.roomName, 'maxPax': $scope.maxPerson})
.then(function (response) {
$scope.msg = "Room is inserted into database.";
});
};
});
add_library_room.php (Insert data)
<?php
define("HOSTNAME","localhost");
define("USERNAME","root");
define("PASSWORD","");
define("DATABASE", "booking_db");
$dbhandle=new mysqli(HOSTNAME, USERNAME, PASSWORD, DATABASE) or die ("Unable to Connect to the Database");
$data=json_decode(file_get_contents("php://input"));
$room_Name=$dbhandle->real_escape_string($data->roomName);
$max_Pax=$dbhandle->real_escape_string($data->maxPax);
$query="INSERT INTO library_discussion_room (room_name, max_pax) VALUES ('$room_Name', '$max_Pax')";
$dbhandle->query($query);
?>
phpMyAdmin MySQL database (The value that I had inserted is empty):
Image Link
I don't know what I'm doing wrong. Hope you guys can help me to solve this problem. Thanks.
It's because you are directly trying to write the data on the scope.
Angular JS often creates childscopes inside of directives to avoid messing up with higher level datas.
So if you directly write ng-model="something", then it will become only a distinct, and not a reference.
In order to make it work, you'll need to make an object, and refer to it's properties, since angular will search for that object in parent scopes too.
So the solution will be sth like this:
ng-model="object.property"
and then in your controller
$scope.object = {};
$scope.addRoom = function () {
$http.post("add_library_room.php", {'roomName': $scope.object.roomName, 'maxPax': $scope.object.maxPerson})
.then(function (response) {
$scope.msg = "Room is inserted into database.";
});
};
Are you sure instead of using
$data=json_decode(file_get_contents("php://input"));
you cannot simple use
$data=$_POST;
Just print your $data variable by doing a
print_r($data);
You must be getting $data as empty.
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 have a PHP script that does the insertion part as follows(I know, no PDO or mysqli, this is just for my personal testing):
<?php
$user = $_POST['user'];
$comments = $_POST['comment'];
$con = mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db('localh',$con);
$query = mysql_query("INSERT INTO content (Title, Article)
VALUES('$user', '$comments')");
if(!$query){die(mysql_error());}
mysql_close($con);
?>
If I use this script in a form action it will work fine, the input values will be added to the database.
Here's the form:
<form>
<p>User: <input type="text" id="user" /></p>
<p>Comment:<input type="text" id="comment" /></p>
<input type="button" id="submit" onClick="insertData();" />
</form>
And the AJAX part, located between the head tags:
function insertData(){
var ajaxRequest = new XMLHttpRequest();
var usr = document.getElementById("user").value;
var cmnt = document.getElementById("comment").value;
ajaxRequest.open("POST", "insert.php", true);
ajaxRequest.send(usr, cmnt);
}
The result will be an empty row in the database. I don't know why that is, I'm clueless.
Actually, this is one of the only very specific cases where I actually recommend someone to use jQuery.
AJAX is probably the most ambiguously implemented feature. Each browser has its quirks regarding its implementation. jQuery can be used to iron out those cross-browser incompatibility.
jQuery $.ajax documentation page
You are not actually sending the keys of your variables to your script:
ajaxRequest.send(usr, cmnt);
so your $_POST array will not contain user nor comment.
Although a switch to jQuery is probably a good idea, you can send your variables like:
var vars = encodeURI("user="+usr+"&comment="+cmnt);
ajaxRequest.send(vars);
But you would have to test that as I normally use jQuery for my ajax requests.
Check if you recive in $_POST veriable user and comments data, just add in your php file something like that
print_r($_POST); exit();
if you will havent them at server side check your ajax
if allright check your mysql query:
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.