Record data to a database using AJAX - php

I need to use AJAX to save user input comments instantly to the database.
This is the comment box.
<div class="comment">
<form action="comment.php">
<textarea cols="35" name="comments"> Give us comment </textarea>
<input type="button" value="comment" onclick="ajaxFunction()">
</form>
</div>
This is the php code
<?php
$link = mysql_connect("localhost","root","");
mysql_select_db("continental_tourism");
$comments = $_POST['comments'];
if($comments == "")
echo "Please type your comment";
else
{
$query = "insert into comment(comment) values('$comments') ";
mysql_query($query);
}
return;
?>
I need to know how this should be changed.
Thank You

I would chnage your HTML like this
<textarea cols="35" id="comments"> Give us comment </textarea>
<input type="button" value="comment" id="btnSave" />
And the script
$(function(){
$("#btnSave").click(function(e){
e.preventDefault();
$.post("yourphpfile.php", { comments : $("#comments").val() } ,function(data){
alert(data);
});
});
});
The above script will send an ajax request to yourphpfile.php with the value present in the textarea with id comment. Then once it gets some data back from the server page. it justs alerts it ( you may show this in a seperate div if you want ). You should echo the response from your php file after saving the data to database.
As bracketworks already mentioned, you should be careful about SQL injections while saving data which is being read from the querystring value. do proper sanitization before putting it in a query. Sorry i am not a php guy. so not sure how to do that.
Don't forget to include the jQuery library to your page.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
You may use firebug console for debugging your script error if you run into any.

Related

Echo form data without sending to server

I have a tiny form on a page where I ask for the users name, the form sends the data to name.php and echos back the users name for example "Hello Steven" Steven being the name entered into the form.
Now that the name has been echoed to that form, I would like to echo that same data again elsewhere on the page. This is where I've run into a wall.
I would rather not send the names entered into the form to a server or database, but simply keep them for a session and then lose them.
The issue now is echoing the form data multiple times on one page.
The code I am using right now for the tiny form is as follows:
<form role="form" id="inviteform3" class="form-inline" action="name.php" method="POST">
<div class="form-group">
<input type="text" class="form-control input-sm" name="name" placeholder="Your Name"
id="hello" autocomplete="off" style="margin-top:10px">
</div>
<center>
<span id="result"></span>
<button class="btn btn-brand btn-sm next-screen animated bounceInUp"
id="go" style="margin-top:5px; display:none" href="#services" data-animation-delay=".5s">
Let's Go!</button></center>
<button class="btn btn-block btn-brand btn-xs invitebtn3" id="casi" type="submit"
style="margin-top:5px"><i class="fa fa-thumbs-o-up"></i> Submit</button>
</form>
My php form (name.php) is as follows:
<html>
<body>
Let's get started, <?php echo $_POST["name"]; ?>
</body>
</html>
and my js code is:
<script>
$(document).on("ready", function(){
//Form action
$("#inviteform3").on("submit", function(event){
// Stop submit event
event.preventDefault();
$.ajax({
type:'POST',
url: 'name.php',
data:$('#inviteform3').serialize(),
success: function(response)
{
$('#inviteform3').find('#result').html(response);
}});
});
});
</script>
We need to get a few things straight:
I would rather not send the names entered into the form to a server or database, but simply keep them for a session and then lose them.
You ARE sending that data to the server, you have used jQuery and AJAX to POST your form to name.php (php works on the server) from which you receive the response and add it your page with the line:
$('#inviteform3').find('#result').html(response);
If you want to KEEP that data stored (for example in a session), you can use the PHP suggested by Antony D'Andrea in name.php. When the browser is closed, the session is destroyed. Untill then you can use the session variable where ever you want.
Now that the name has been echoed to that form, I would like to echo
that same data again elsewhere on the page. This is where I've run
into a wall.
You are echoing the name in name.php, your AJAX call then retrieves the whole page (including the html and body tags) and adds it to #result. If you want to show the name mulitple times, just append it multiple times with the line above.
$("#inviteform3").on("submit", function(event) {
var name = $("form input['name']").val();
// Here is the interesting part
sessionStorage.setItem("name", name);
}
// Get that name
var access_name = sessionStorage.getItem("name");
$("#some_id").html(access_name); // Inserts the name where you want it.
sessionStorage is wiped every time the tab/window is closed.
You could use PHP instead of Javascript.
session_start();
$_SESSION['name'] = $_POST['name'];
The $_SESSION variable is cleared when the browser is closed and is global so can be accessed anywhere. session_start has to be the very first thing you do though on line 1 of the first page that is run.
More info about sessions in PHP can be found here and the about $_SESSION here.
For example:
You are posting to name.php. So on line 1 of name.php do
<?php session_start(); ?>
Then do
<?php
if (isset($_POST['name'])) {
$_SESSION['name'] = $_POST['name'];
}
?>
Then wherever you want to use it, just do echo $_SESSION['name'];
If you want to echo in other files. Then in line 1 of the other file do
<?php session_start(); ?>
Then:
<?php
if (isset($_SESSION['name'])) {
echo $_SESSION['name'];
}
?>
The if statement is just there for checking, but you don't need it if you are confident it is set.

PHP Bypass jQuery Codes

I use this codes to save my contacts information into MySQL Database and apply JQuery Confirm Function for confirmation of data submitting, but when confirmation dialog open PHP Scripts can't stop, or Php bypass JQuery confirm codes and submit data into database, any idea regarding this issue.
<?php
//Database connection.
include'connect.php';
if(isset($_POST['name'])&&isset($_POST['email'])&&isset($_POST['contact'])){
$name = $_POST['name'];
$email = $_POST['email'];
$contact = $_POST['contact'];
if(empty($name)&&empty($email)&&empty($contact)){
echo'
<script>
$(document).ready(function(){
alert("Please fill all fields.");
});
</script>
';
}else{
if($sql = mysql_query("INSERT INTO contact_list VALUES ('', '".mysql_real_escape_string($name)."', '".mysql_real_escape_string($email)."', '".mysql_real_escape_string($contact)."')")){
echo'
<script>
$(document).ready(function(){
confirm("Are you sure to Saved Contact?");
});
</script>
';
}else{
echo'
<script>
$(document).ready(function(){
alert("Something is wrong, Please check");
});
</script>
';
}
}
}
?>
<html>
<form action="#" method="POST">
Full name:<input type="text" name="name">
Email:<input type="text" name="email">
Contact:<input type="text" name="contact">
</form>
</html>
PHP is executed by the server while javascript is executed by the client. And you want the server to "wait" or "stop execution" until some js code is executed by the client. Well, it's not possible.
You have to split your PHP code in two different PHP scripts: one for confirmation and one for data saving. For example, with pseudocode:
confirm.php
Hey, are you sure you want to save the data?
Yes, I'm sure
save.php
INSERT INTO 'blablabla' VALUES bla bla bla bla bla
Of course you don't really have to split it into two scripts. You can add one more $_POST parameter like "confirmed=true/false" and instead of two scripts just have one with one more if () {} else {} block.
But the idea is that you have to separate the two actions, cause you can't do both the confirmation and the saving at once with PHP.
There are also a few more options:
Use ajax to run the "saving script" once user confirms the operation
Use javascript to prevent the "saving script" from running without confirmation, something like: <input type="submit" onclick="return confirm('Sure?');" value="Save"/>

How to have user submit text in form and AJAX it to enter to db and show up on same page?

I want the user to fill it out. Submit it, have it store into the database and then use jquery to have it show up on the same page in front of them. Right now I can get it to send to the database but it opens up in another page (/data.php) on submit. Also I have it set to random because I don't know how to get the exact post just sent by the user back to display.
Here is my data.php file:
<?php
$con = mysql_connect("*****", "******", "******");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("textwall", $con);
$sql="INSERT INTO textwalltable (story)
VALUES
('$_POST[story]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
$sql = "SELECT * FROM textwalltable ORDER BY RAND() LIMIT 1;";
$query = mysql_query( $sql );
while($row = mysql_fetch_array($query)) {
echo $row['story'];
}
mysql_close($con);
?>
and my HTML page:
<html>
<head>
<title>testing</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="jquery.js"><\/script>')</script>
<script type="text/javascript">
function loadData()
{
$("#txtHint").load("data.php");
}
</script>
</head>
<body>
<form action="data.php" method="post" onsubmit="loadData()">
<div>
<label for="comment">Type here:</label>
<textarea id="story" name="story" rows="2" cols="20">
</textarea>
<div id="txtHint"></div>
</div>
<div>
<div><input type="submit" value="Submit" class="submit"/></div>
</form>
</body>
Here is work flow:
1) User hits form submit.
2) You gather necessary information from DOM. You AJAX the information to a server-side script that enters that info into the database.
3) You use JQuery to insert the information however you want to display it into the DOM.
4) Remove whatever html you no longer need on the page if necessary.
In terms of code you are going to want to look at JQuery's ajax or post functions for the AJAX call.
You can use a javascript function (using jquery) to handle those events. This method does not use a button, so you will need to create your own button that will call the following function:
function postPage() {
$.post("post.php", $("#form_id").serialize(), function(){
$("#display_id").load('display.php');
});
}
You will need to have the post values processed in this case by "test.php", and then the contents of which you want to display back to the user after posting in display.php. The contents of display.php will be placed inside a div/container with the id of "display".
Here is another way, if you use the serialize function built into jquery along with the $.post you won't have to actually write much code.
html form and html displaying the messages:
<form action="data.php" method="post" class="commentForm">
<div>
<label for="comment">Type here:</label>
<textarea id="story" name="story" rows="2" cols="20">
</textarea>
<div id="txtHint"></div>
</div>
<div>
<div><input type="submit" value="Submit" class="submit"/></div>
</form>
<ul class="messages">
<li>Some old message</li>
<li>Some other old message</li>
</ul>
jquery to send the new messages to your server from the client and placing new message into the DOM and resetting the html form
//bind a click even to the submit
$('.commentForm input[type=submit]').click(function(){
$(this).closest('form').find('input[type=submit]').value('Submitting');
$.post(
$(this).closest('form').attr('action'),
$(this).closest('form').serialize(),
function(responseFromServer){
//get the message from the html form (don't need to send it back from the server)
var message = $(this).closest('form').find('textarea');
$('.messages').append('<li>'+message+'</li>');
//resetting the html form
$(this).closest('form').find('textarea').html('');
$(this).closest('form').find('input[type=submit]').value('Submit');
}
);
//prevent the form from actually sending in the standard fashion by returning false
return false;
});
php
//get the post variable and make it safe for inputting into the db
$message = mysql_real_escape_string(html_entities($_POST['story']));
if(!empty($message)){
//assuming you have a db connection
$insert_query = mysql_query("INSERT INTO textwalltable VALUES($message)");
echo 'message entered';
} else {
echo 'no message';
}

Calling a PHP function from an HTML form in the same file

I'm trying to execute a PHP function in the same page after the user enters a text and presses a submit button.
The first I think of is using forms. When the user submits a form, a PHP function will be executed in the same page. The user will not be directed to another page. The processing will be done and displayed in the same page (without reloading).
Here is what I reach to:
In the test.php file:
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" onclick="test()" />
</form>
The PHP code [ test() function ] is in the same file also:
<?php
function test() {
echo $_POST["user"]; // Just an example of processing
}
?>
However, I still getting a problem! Does anyone have an idea?
This cannot be done in the fashion you are talking about. PHP is server-side while the form exists on the client-side. You will need to look into using JavaScript and/or Ajax if you don't want to refresh the page.
test.php
<form action="javascript:void(0);" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
$("form").submit(function(){
var str = $(this).serialize();
$.ajax('getResult.php', str, function(result){
alert(result); // The result variable will contain any text echoed by getResult.php
}
return(false);
});
</script>
It will call getResult.php and pass the serialized form to it so the PHP can read those values. Anything getResult.php echos will be returned to the JavaScript function in the result variable back on test.php and (in this case) shown in an alert box.
getResult.php
<?php
echo "The name you typed is: " . $_REQUEST['user'];
?>
NOTE
This example uses jQuery, a third-party JavaScript wrapper. I suggest you first develop a better understanding of how these web technologies work together before complicating things for yourself further.
You have a big misunderstanding of how the web works.
Basically, things happen this way:
User (well, the browser) requests test.php from your server
On the server, test.php runs, everything inside is executed, and a resulting HTML page (which includes your form) will be sent back to browser
The browser displays the form, the user can interact with it.
The user submits the form (to the URL defined in action, which is the same file in this case), so everything starts from the beginning (except the data in the form will also be sent). New request to the server, PHP runs, etc. That means the page will be refreshed.
You were trying to invoke test() from your onclick attribute. This technique is used to run a client-side script, which is in most cases Javascript (code will run on the user's browser). That has nothing to do with PHP, which is server-side, resides on your server and will only run if a request comes in. Please read Client-side Versus Server-side Coding for example.
If you want to do something without causing a page refresh, you have to use Javascript to send a request in the background to the server, let PHP do what it needs to do, and receive an answer from it. This technique is basically called AJAX, and you can find lots of great resources on it using Google (like Mozilla's amazing tutorial).
Here is a full php script to do what you're describing, though pointless. You need to read up on server-side vs. client-side. PHP can't run on the client-side, you have to use javascript to interact with the server, or put up with a page refresh. If you can't understand that, there is no way you'll be able to use my code (or anyone else's) to your benefit.
The following code performs AJAX call without jQuery, and calls the same script to stream XML to the AJAX. It then inserts your username and a <br/> in a div below the user box.
Please go back to learning the basics before trying to pursue something as advanced as AJAX. You'll only be confusing yourself in the end and potentially wasting other people's money.
<?php
function test() {
header("Content-Type: text/xml");
echo "<?xml version=\"1.0\" standalone=\"yes\"?><user>".$_GET["user"]."</user>"; //output an xml document.
}
if(isset($_GET["user"])){
test();
} else {
?><html>
<head>
<title>Test</title>
<script type="text/javascript">
function do_ajax() {
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var xmlDoc = xmlhttp.responseXML;
data=xmlDoc.getElementsByTagName("user")[0].childNodes[0].nodeValue;
mydiv = document.getElementById("Test");
mydiv.appendChild(document.createTextNode(data));
mydiv.appendChild(document.createElement("br"));
}
}
xmlhttp.open("GET","<?php echo $_SERVER["PHP_SELF"]; ?>?user="+document.getElementById('username').value,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" id="username"/>
<input type="button" value="submit" onclick="do_ajax()" />
</form>
<div id="Test"></div>
</body>
</html><?php } ?>
Without reloading, using HTML and PHP only it is not possible, but this can be very similar to what you want, but you have to reload:
<?php
function test() {
echo $_POST["user"];
}
if (isset($_POST[])) { // If it is the first time, it does nothing
test();
}
?>
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" onclick="test()" />
</form>
Use SAJAX or switch to JavaScript
Sajax is an open source tool to make
programming websites using the Ajax
framework — also known as
XMLHTTPRequest or remote scripting —
as easy as possible. Sajax makes it
easy to call PHP, Perl or Python
functions from your webpages via
JavaScript without performing a
browser refresh.
That's now how PHP works. test() will execute when the page is loaded, not when the submit button is clicked.
To do this sort of thing, you have to have the onclick attribute do an AJAX call to a PHP file.
in case you don't want to use Ajax , and want your page to reload .
<?php
if(isset($_POST['user']) {
echo $_POST["user"]; //just an example of processing
}
?>
Take a look at this example:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
You can submit the form without refreshing the page, but to my knowledge it is impossible without using a JavaScript/Ajax call to a PHP script on your server. The following example uses the jQuery JavaScript library.
HTML
<form method = 'post' action = '' id = 'theForm'>
...
</form>
JavaScript
$(function() {
$("#theForm").submit(function() {
var data = "a=5&b=6&c=7";
$.ajax({
url: "path/to/php/file.php",
data: data,
success: function(html) {
.. anything you want to do upon success here ..
alert(html); // alert the output from the PHP Script
}
});
return false;
});
});
Upon submission, the anonymous Javascript function will be called, which simply sends a request to your PHP file (which will need to be in a separate file, btw). The data above needs to be a URL-encoded query string that you want to send to the PHP file (basically all of the current values of the form fields). These will appear to your server-side PHP script in the $_GET super global. An example is below.
var data = "a=5&b=6&c=7";
If that is your data string, then the PHP script will see this as:
echo($_GET['a']); // 5
echo($_GET['b']); // 6
echo($_GET['c']); // 7
You, however, will need to construct the data from the form fields as they exist for your form, such as:
var data = "user=" + $("#user").val();
(You will need to tag each form field with an 'id', the above id is 'user'.)
After the PHP script runs, the success function is called, and any and all output produced by the PHP script will be stored in the variable html.
...
success: function(html) {
alert(html);
}
...
This is the better way that I use to create submit without loading in a form.
You can use some CSS to stylise the iframe the way you want.
A php result will be loaded into the iframe.
<form method="post" action="test.php" target="view">
<input type="text" name="anyname" palceholder="Enter your name"/>
<input type="submit" name="submit" value="submit"/>
</form>
<iframe name="view" frameborder="0" style="width:100%">
</iframe>

Linking page in a div with html forms and php

So I have this html code
<div id="wrap">
<div id="header">
</div>
<div id="content">
<form method="POST" action="code.php">
Name:
<input type="text" name="name" size="50">
<input type=submit value="Get Code">
</form>
</div>
<div id="footer">
</div>
Is it possible to load the code.php after the user clicks submit into the #content div?
Essentially, what I want is when the user clicks the submit button, the code.php after processing is loaded onto the same #content div.
So let say in my code.php, after processing the inputted data, I come up with this lilne of code,
<?php
some processing code here;
$name = 'john';
echo $name;
?>
So then after hitting submit, user would see
<div id="content">
john
</div>
Hope I didn't complicate my question by repeating myself, please let me know if this is possible with javascript, php or whatever.
Thanks for the read!
#JohnP yes, $.load is a good solution. However, you'll need to send the form data in the request:
UPDATED [3] for sending a POST with multiple fields and checkboxes:
$('form').submit(function(){
// create an object to send as a post
var form = this,
fields = form.elements,
el,
post = {};
for (var i = fields.length; i--; ) {
el = fields[i];
if (el.name) {
switch (el.type) {
case 'checkbox':
case 'radio':
post[el.name] = (el.checked) ? el.value : '';
break;
default:
post[el.name] = el.value;
}
}
}
// send the form data in the load request...
$('#content').load(this.action, post);
return false;
});
This will send the data as a POST.
Since you've tagged jQuery, I'll use a jQuery example
$(document).ready(function(){
$('form').submit(function(){
$('#content').load('code.php');
return false;
})
})
This makes a couple of assumptions here
This assumes that code.php is in the same path that you are in now.
There is only one form in the page.
As #johnhunter points out, this example obviously won't work with post. You can send the post data along with the method. See here for usage : http://api.jquery.com/load
EDIT
Here's a fiddle example : http://jsfiddle.net/jomanlk/J4Txg/
It replaces the form area with the content from jsfiddle/net/echo/html (which is an empty string).
NOTE 2 Make sure to include the code in $(document).ready() or include it at the bottom of the page. It goes without saying you need jQuery in your page to run this.
You might want to check out jquery form plugin http://jquery.malsup.com/form/#
in simple way use
<div id="content">
if(isset($_POST['submit'] && !empty($_POST) )
{
// do your all post process
$name ='John';
echo $name;
}
else {
<form method="POST" action="$_SERVER['PHP_SELF']">
<label for="uname" >Name:</label><input type="text" name="uname" id="uname" size="50">
<input type=submit value="Get Code" name="submit">
</form>
}
</div>

Categories