How to update and output a database without reloading the page - php

I have data which is a name. And I am having an input type=text where the value is equals to the name, together with a button type=submit. So what i'm trying to do is that, i want to change and update the name in my database and also output the new name without reloading the page at once because I want to run a JS function (Not Alert but a Toast Notification) which is I cannot do. So to shorten, ( EDIT -> UPDATE -> SHOW = without reloading the page).
EDIT:: I'm sorry I forgot to mention. I know jQuery and AJAX is the solution but I am having trouble understanding AJAX not unlike jQuery.
profile.php (FORM CODE)
<form action="profile.php" method="POST">
<input type="text" id="changename" name="changename" class="form-control" placeholder="New Name" required>
<button id="btnchange" type="submit"></button>
</form>
profile.php (PHP CODE)
<?php
if(isset($_POST['changename'])) {
require 'connect.php';
$newname = $_POST['changename'];
$user_id = $_SESSION['temp_user'];
$sql = "UPDATE login SET login_name='$newname' WHERE user_id='$user_id'";
if(mysqli_query($conn, $sql)){
header('location: profile.php');
// MY JS FUNCTION HERE //
}
mysqli_close($conn);
}
?>

How to update and output a databse without reloading the page? what u looking for is AJAX.
I know you have selected the answer, but there's an extra information that you need that might help you in the long run
The are some good ajax tutorials you can follow in the web
Ajax Introduction
What is Ajax ?
And many more you can find on the web.
This is what u need to do, first your form method is GET and on your php script you are requesting an $_POST therefore this will generate an undifined notice error,changename : notice : undifined variable changename so the solution is to use one method in a single form if your form is $_GET you use $variable = $_GET['fieldname'] if form method is POST on your server side use $variable = $_POST['fieldname']; not the way you did. So lets change your form method to POST Then this is what u should do.
edit.php
Update
<script type="text/javascript">
$('document').ready(function(){
$('form').on('submit',function(event){
event.preventDefault();//prevent the form from reloading the page when submit
var formData = $('form').serialize(); // reading form input
$.ajax({
type :'POST',
data : formData,
url : 'profile.php',
dataType : 'json',
encode : true,
success : function(response){
//response = JSON.parse(response);
if(response == "ok"){
$('#success').html('profile updated success');
setTimeout(' window.location.href = "profile.php"; ', 6000); // redirecting
}else{
//could not update
$('#error').html(response);
}
},
error : function(e){
console.log(e); // debugging puporse only
}
});
});
});
</script>
That's what you need on the frontend side.. Please note if you have more than one form in a single page then do not use $('form').on('submit',function(event){}); you then give each form a unique ID then on replace the form on jquery/ajax with the iD of the form u wanna submit.
Then your server side.
I have noticed that you have header('location: profile.php'); that's
for redirecting, since we are sending ajax request to the server and
back to the client, you don't redirect on the server side, your
redirect using the client side after you have received the response
you expected from the server. I have commented that section where I do
redirecting with client side, on the script above.
profile.php
<?php
$message = '';
if(isset($_POST['submit'])) {
require 'connect.php';
//validate your input field
$newname = $_POST['changename'];
$user_id = $_SESSION['temp_user'];
$sql = "UPDATE login SET login_name='$newname' WHERE user_id='$user_id'";
if(mysqli_query($conn, $sql)){
$message = 'ok'; // success
}else{
$message = 'system error could not update please try again later';
}
echo json_encode($message);//sending response back to the client
mysqli_close($conn);
}
?>
That's all you need, note you need to validate all your inputs fields in both the client and server side before using them.
I would also advice you to learn more about prepared statements, using mysqli or PDO they are very easy to use and very safe.
running a query like this : $sql = "UPDATE login SET login_name='$newname' WHERE user_id='$user_id'"; is very unsafe, your inputs are not validated and not filtered and sanitized.
so with prepared statements its easy like :
profile.php prepared
<?php
$message = '';
if(isset($_POST['submit'])) {
require 'connect.php';
//validate your input field
$newname = $_POST['changename'];
$user_id = $_SESSION['temp_user'];
//prepare and bind
$sql = $conn->prepare("UPDATE login SET login_name= ? WHERE user_id= ? ");
$sql->bind_param("si",$newname,$user_id);
if($sql->execute()){
$message = 'ok';
}else{
$message = 'Error Could not update please try again later';
}
echo json_encode($message);
$conn->close();
}
?>
$sql->bind_param("si",$newname,$user_id); This function binds the parameters to the SQL query and tells the database what the parameters.
are.By telling mysql what type of data to expect, we minimize the risk of SQL injections.

First thing to do in your form is to change your form method to POST (and not GET) as you try to retrieve "changename" by POST method.
So change this:
<form action="profile.php" method="GET">
by this:
<form action="profile.php" method="POST">

Related

How to handle AJAX error if sql update fails?

I have a php file, which updates the SQL, if the "follow this user" button is clicked, and an AJAX calls this PHP file. The code below works, it follows the user! My problem is: If, for some reason the SQL update fails, I want the AJAX to drop an error message (e.g. an alert), but I really don't know how this could be possible. The AJAX doesn't know whether the update succeeded or not.
Here's my code:
PHP
if(!empty($_GET['a']) and $_GET['a']=='follow')
{
$id = sql_escape($conn,$_GET['id']);
$me = $user2[0];
//the user's id who clicks on the follow button
$query = sql_fetch(sql_query($conn, "select * FROM
forum where id='$id'"));
//check who created this forum, so we know who to follow
$follow_this_user = $query['user'];
//the user to follow
$now = date('Y-m-d H:i:s');
$already_follow_user = sql_fetch(sql_query($conn,
"SELECT * FROM follow WHERE user_id=".$me." AND
followed_user =".$follow_this_user." "));
//check if user already followed by this user
if(empty($already_follow_user[0])) {
//if not followed
sql_query($conn,"INSERT INTO follow
(user_id, followed_user, date) VALUES
('".$me."', '".$follow_this_user."', '".$now."');")
or die(mysqli_error($conn));
}
}
AJAX:
$(document.body).on('click', '.followable', function(){
//User clicks on the follow text, which has "followable" class
$.ajax({
//type: 'GET',
url : '/ajax/ajax_follow.php?a=follow&id=<?php print $topic[id]; ?>'
//the $topic['id'] is the id of the current topic, which
//I need to know who created this forum, to follow that user
//(as mentioned above in the php code)
});
I need data and error, but no idea how to get them working. I tried many things, but I just can't get the data.
Add this to your ajax request:
success: function(data) {
alert(data);
}
And simply echo something on your PHP page.
For example:
$result = mysql_query($sql);
echo $result;
If you want to recieve more data, JSON is your friend.

Process database delete action in the same PHP page with post

I'm building PHP application for process employee leave records. In this application the main screen populate database records and action buttons. when user click the action button it take the database id from the table and go through another file to delete that record and then redirect back to the same page. This mechanism implemented using HTML _GET method. that means anyone can see the row ID in the URL feed and if anyone request this url with different row ID, PHP file delete the record since any other security measures not taken place in to prevent that. and also this application not using any kind of session.
this is my href code for the task I mentioned above.
echo "<a href='rejectone.php?id=$lvid' class='btn btn-danger btn-xs m-r-1em'>Cancal</a>";
and this is my rejectone.php code
<?php
$lid =$_GET['id'];
include 'database.php';
$accval = "Accept";
try {
$query = "UPDATE leavesrecords SET leavestatus = 'Reject' WHERE lvid = '$lid'";
$stmt = $con->prepare( $query );
$stmt->bindParam(1, $id);
$stmt->execute();
}
catch(PDOException $exception){
die('ERROR: ' . $exception->getMessage());
}
header( "refresh:0;url=bs.php" );
?>
I have two questions
1.) How can I run the rejectone task inside the same PHP file without redirecting to another PHP file
2.) How can I use HTML _POST method instead of get method to transfer data if I still use jejectone.php file
thanks!!
First of all change your line:
echo "<a href='rejectone.php?id=$lvid' class='btn btn-danger btn-xs m-r-1em'>Cancal</a>";
to
echo 'Cancal';
If you haven't included jQuery on your site, you can do it by adding this script to your page, just before closing
</head> tag
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
Add this JavaScript file to the bottom of your page, just before closing </body>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click', '.delete-item', function(e){
e.preventDefault();
if(!confirm('Are you sure you want to delete this item?')) return false;
$.post('bs.php', {'id': t.attr('primary-key'), 'delete_item': 1}, function(e){
window.location = 'bs.php';
})
})
})
</script>
Copy your rejectone.php to bs.php, but make these changes:
if(isset($_POST['delete_item']))
{
$lid = (int)$_POST['id'];
include 'database.php';
$accval = "Accept";
try {
$query = "UPDATE leavesrecords SET leavestatus = 'Reject' WHERE lvid = :lid ";
$stmt = $con->prepare( $query );
$stmt->bindParam(':lid', $lid );
$stmt->execute();
}
catch(PDOException $exception){
die('ERROR: ' . $exception->getMessage());
}
}
That is it.
Use ajax post method. See Full example of accepted solution with sample code for more details here : Delete MySQLi record without showing the id in the URL
Then using jquery remove that record from the page which will give more good UI experience.

Sending data to database only after submit has been clicked on a form that posts to same page

I have a form that posts to the same page because I need the values to display below after submit has been clicked, which it does. The problem is that as soon as the page is loaded, the php runs and sends the data to the database instantly, so it sends an empty value to the database since the user has not submitted anything.
$servername = "localhost";
$username = "my_username";
$password = "my_password";
$dbname = "my_database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO my_table (firstname)
VALUES (:firstname)");
$stmt->bindParam(':firstname', $firstname);
// insert a row
$firstname = $name;
$stmt->execute();
echo "New records created successfully";
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
<form method="post" id="nick-form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
?>
I would like the $name variable to only get sent when the user hits submit, if possible.
"I would like the $name variable to only get sent when the user hits submit, if possible."
Use a conditional isset() with your submit button.
<?php
if(isset($_POST['submit']))
{
// code to execute
}
Sidenote: You could/should also add an !empty() on your inputs also, which is highly recommended in order to prevent empty submissions.
You could also implement a header upon successful submission to redirect to another page:
header('Location: http://www.example.com/');
exit; // avoid further execution of code, if any resides below that
http://php.net/manual/en/function.header.php
Just make sure you're not outputting before header if you plan on using it.
Here's an article on Stack about this:
How to fix "Headers already sent" error in PHP
There is also a good article on how to prevent multiple submits using sessions and tokens:
http://www.phpro.org/tutorials/Preventing-Multiple-Submits.html
Something I have used in the past with success which could be useful.
What you have is a possible checking clause with an if statement using
if (count($_POST) > 0) {
//code runs if POST is submitted data
if (!empty($_POST['name'])){
///process the name form field value
}
}
Which would solve your issue, BUT when the page is refreshed by the user, the refreshed page will also resubmit the POSTED data , this is why on database activity pages it is HIGHLY advisable to send the data to another page, and then once the data is saved, return the browser to the original page, so refreshing the original page does not resubmit the POSTED data
To illustrate further, make another PHP file called "save.php" and everything in the PHP tags ABOVE the <form> element, put in the save.php file, then set the form to goto save.php and at the bottom of the save.php set a header("location:formpage.php");die(); to return to the form.
You will still need a database call on the form page to display the desired output. But this will prevent resubmitting of data upon page refresh
You can use if :
if(isset($_POST['name']) && $_POST['name'] != null) {
// Your code
}
You should also check $_POST['submit'].

how to add a content to html from a database after inserting data from mysql no refresh php

For example I am a user and I want to post a comment and after submitting it and saved to my database. The other page of the admin updates and automatically the data that I inserted displays without refreshing the page of the admin. Help please..
any code can help. Thanks. I'm using php for server-side language. Any language can help javascript or ajax.
Javascript (jQuery):
$.post('path_to_your_php_script.php', function(data) {
$('the_dom_element_you_want_to_show_the_comment_in').html(data);
});
Somewhere in path_to_your_php_script.php:
// some code to save the data
echo '<div>New comment</div>';
exit;
For more information, please refer to jQuery's post and ajax methods. You can do the same thing without jQuery, but you shouldn't reinvent the wheel.
yourphpfile.php is the php file where you need to do all your database operations (in your case its insert into database).
So,basically you want to show the recently insert data in a webpage without refreshing the page, to do that, we need Ajax.
So, do your insert operation in yourphpfile.php, and if the insert operation is successful, just return the result (inserted data into DB) using echo $output;exit;
where $output = 'recently inserted data';
That's what you need to do in the php side.
Your yourphpfile.php:
<?php
//your database insert operation
echo $output;// $output should have the inserted data
exit;
?>
Now in ajax function:
You could use jquery.ajax
$.ajax({
type: "GET",
url: "yourphpfile.php",
success: function(response){
if(response != '') {
//data that I inserted displays without refreshing the page of the admin
$('yourDivContent').html(response);
} else {
// response error
}
}
});
In the reponse variable you would get what you have echoed in the yourphpfile.php.
That is $output. Then you could use the reponse varible inside ajax function and use it to insert into your HTML.
Suppose you have a form and you can use Ajax for sending the data to the backend. The ajax call would look in the following way:
var id = $(this).attr('id');
$.ajax({
type:"POST",
url:"ajax.php",
data:{id:id},
success:function(data){
// do something if insertion into database has succeeded
}
});
...and in php you write something as:
// Connecting to Database
mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASS) or die ('Can not connect to MySQL database');
// Selecting Database
mysql_select_db(DBNAME) or die ('Cant select Database');
$action = mysql_real_escape_string($_POST['action']);
if ($action == "insert")
{
foreach ($recordArray as $key=>$value) {
$query = "INSERT INTO `TABLE`
SET name = `".$_POST['name']."`
SET age = `".$_POST['age']."`
.
.
mysql_query($query) or die('Error, insert query failed');
}

how to get the current added in the table without getting all the data

guys im trying to make a simple commenting system, that when i click the submit the fields will automatically save in the database then fetch it using ajax. but im getting all the data repeatedly instead of getting the recently added data in the database here is the code:
<div id="wrap-body">
<form action="" method="post">
<input type="text" name="username" id="username">
<input type="text" name="msg" id="msg">
<input type="button" id="submit" value="Send">
</form>
<div id="info">
</div>
</div>
<script>
$(document).ready(function (){
$('#submit').click(function (){
var username = $('#username').val();
var msg = $('#msg').val();
if(username != "" && msg != ""){
$.ajax({
type: 'POST',
url: 'get.php',
dataType: 'json',
data:{ 'username' : username , 'msg' : msg},
success: function (data){
var ilan=data[0].counter;
var i = 0;
for(i=0;i<=ilan;i++){
$('#info').append("<p> you are:"+data[i].username+"</p> <p> your message is:"+data[i].mesg);
}
}
});
}
else{
alert("some fields are required");
}
});
});
</script>
PHP:
<?php
$host='localhost';
$username='root';
$password='12345';
$db = 'feeds';
$connect = mysql_connect($host,$username,$password) or die("cant connect");
mysql_select_db($db) or die("cant select the".$db);
$username = $_POST['username'];
$msg = $_POST['msg'];
$insert = "INSERT INTO info(user_name,message) VALUES('$username','$msg')";
if(#!mysql_query($insert)){
die('error insertion'.mysql_error());
}
$get = "SELECT * FROM info ";
$result=mysql_query($get)or die(mysql_error());
$inside_counter = mysql_num_rows($result);
$data=array();
while ($row = mysql_fetch_array($result))
{
$data[] = array(
'username'=>$row['user_name'],
'mesg'=>$row['message'],
'counter'=>$inside_counter
);
}
echo json_encode($data);
?>
SELECT *
FROM "table_name"
ORDER BY "id" desc
LIMIT 1
This is a SQL query to get last record from table. It return last inserted according to id. id should be a auto increment field. I think this will be helpful for you.
Its because you are returning all the row in the table again to the ajax call via
$get = "SELECT * FROM info ";
if you do return all of them again you will have to test if they are not already there before appending them with the jQuery
Perhaps only return the newly inserted row.
or
The jQuery already knows the data it sent to the server, just return success true or false, and then append it if true with the jQuery, no need to return the data back again to the client side
EDIT
I'm not going to write code for you but perhaps these suggestions may help
mysql_query($insert)
link here for reference - http://php.net/manual/en/function.mysql-query.php
will return true of false depending on if the insert statement was successful
you could potentially also check that it acutally inserted a row by calling
mysql_affected_rows()
link here for reference - http://php.net/manual/en/function.mysql-affected-rows.php
then assuming that the insert was successful (i.e. true from mysql_query($insert) or mysql_affected_rows() > 0) simply return successful (i.e. something like
echo json_encode(true);
then on the client side you could do something like the following:
(jQuery Ajax success function only:)
success: function (data){
if (data) {
$('#info').append("<p> you are:"+username +"</p> <p> your message is:"+msg);
}
else
{
alert('There has been an error saving your message');
}
}
using the variables that you just used to send the request
(Please note code samples provided here are only for example, not intended to be used verbatim)
Couple of points though. Is your intention to post the data via ajax only? (i.e. no page refresh) as if that is the case, you will need to return false from you form submit event handler to stop the page full posting. Also you do not appear to have any logic, or are not worried about complete duplicates being entered (i.e. same username, same message) - not sure if you want to worry about this.
I would also potentially look at tracking all the messages via ids (although I don't know your DB structure), perhaps using
mysql_insert_id()
link here FYI - http://php.net/manual/en/function.mysql-insert-id.php
That way each message can have a unique id, may be easier to establish duplicates, even if the username and message are identical
There are numerous ways to deal with this.
Anyway hope that helps
PS - using the mysql_ - group of commands is generally discouraged these days, use the mysqli_ range of function instead

Categories