Implement Ajax for a PHP Function - php

I am trying to work implement ajax due to maximum site load which PHP causes. But I am not aware of where I am making a mistake here. it is an anchor tag, when it is clicked the status of the particular row should be changed to a string which is hard coded.
PHP WAY
USERDETAIL.PHP
Next
Then it triggers This (IGNORE SQL INJECTION)
if(isset($_GET['changeStatus'])){
$id = $_GET['changeStatus'];
$user=$_SESSION['user'];
$sql = "select * from productOrder where id = ".$id;
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){
$row = mysqli_fetch_assoc($result);
$sql = "update productOrder set prodStatus = 'Ready', By='".$user."' where id=".$id;
if(mysqli_query($conn, $sql)){
header("Location:USERDETAIL.php");
}
}
}
According to this way, it works neat, but the userdetail.php would refresh anyways which is a lot time consuming. Then tried AJAX way is below.
Next
and that hits to
$(document).ready(function() {
$(".changeStatus").click(function(event){
event.preventDefault();
var status = "Ready";
var id = $(this).attr('data-id');
$.ajax({
url : 'action.php',
method : 'POST',
data : {status : status , id : id},
dataType: 'html',
success : function(response){
console.log(response);
}
});
});
});
and in the action.php it is (IGNORE SQL INJECTION AGAIN)
if(isset($POST['prodStatus'])){
$status = $_POST['prodStatus'];
$id = $_POST['id'];
$sql = "update productOrder set prodStatus= '$status' where id=".$id;
$result = mysqli_query($conn, $sql);
if($result){
return 'Updated';
}
}
The output is nothing happens. in the console it is just adding int values. I know I am making a mistake, or understood AJAX in a wrong way. it is just one button click and the string in SQL should be updated without an input text / modal. Please suggest what should be improved?
Also instead of having a seperate action php for these actions, can I do all these in userdetail.php itself with Ajax? is it possible?
Thanks in advance.

As B_CooperA pointed out, $POST should be $_POST.
Also, in $.ajax script data object your property name is status and in action.php you are checking it by prodStatus.
Furthermore, you should check the errors PHP is throwing in your script by enabling error reporting: error_reporting(E_ALL);
It's better to separate ajax calls from your view files. You can create a Class to handle all of your ajax calls (You should also consider authenticating your calls as per your use cases).

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.

How to update and output a database without reloading the page

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">

Why does the Jquery in my header prevent my PHP code from working?

I have a series of radio buttons. When I select a button and press submit, I want
two things to happen:
1. checkmarks should appear (done with a Jquery script in the header)
2. a mysql database should update the user's score, which in turn changes the color of the square (done with a PHP script in the body)
The problem is that when the jquery script is present, the checkmarks appear but the database doesn't update. When I remove the jquery script, however, the database successfully updates. They jquery script is preventing the PHP code from running and I'm not sure why
JQUERY SCRIPT:
<script type='text/javascript'>
`$(document).ready(function () {`
$('#questionform').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr('action') || window.location.pathname,
type: "POST",
data: $(this).serialize(),
success: function (data) {
if ($('input[name=functions_question]:checked').val() == 2)
{
$("#correctanswermarkwhengotright").fadeIn('slow');
$(".incorrectanswermark").fadeIn('slow');
// I THINK THIS IS WHERE THE PHP CODE NEEDS TO GO TO FIX THE PROBLEM BUT I DON'T KNOW HOW TO INTEGRATE IT
} else {
$("#correctanswermarkwhengotwrong").fadeIn('slow');
$(".incorrectanswermark").fadeIn('slow');
}
},
});
});
});
</script>
PHP SCRIPT:
<?php
$id = $_SESSION['id'];
$ress = $db->query("SELECT 1 FROM answers WHERE user_id=$id AND question_group='Functions'");
if($ress->num_rows==0){
$db->query("INSERT INTO answers VALUES(NULL, $id, 'Functions', 0)");
}
if(isset($_POST['functions_question'])){
$res = $db->query("SELECT score FROM answers WHERE id=$id AND question_group='Functions'");
$data = $res->fetch_array();
if($_POST['functions_question']==$_SESSION['functions_question']){
if($data['score']<2)$db->query("UPDATE answers SET score = score+1 WHERE id=$id AND question_group='Functions'");
}else{
if($data['score']>-2)$db->query("UPDATE answers SET score = score-1 WHERE id=$id AND question_group='Functions'");
}
}
?>
You can see this code in action here: carouseltest.byethost8.com/onanswersubmittest.php
You can login with the username: mail#test.com and password: test
If someone can explain how to integrate the PHP with the Jquery so that both actions work, I would appreciate it. Thank you!
You're trying to test every logic of your code at once. It's quite complicated. You need to test your code step by step.
1)Try to comment everything inside ajax success handler and see what's happening (fadein and fadout logic).
2) Try to test your ajax handler (the .php file). Comment everything insde this file and echo the $_SESSION['functions_question'] and $_SESSION['id']. If they return values then go to the next step.
3) Uncomment only this chunk of code
$ress = $db->query("SELECT 1 FROM answers WHERE user_id=$id AND question_group='Functions'");
if($ress->num_rows==0){
$db->query("INSERT INTO answers VALUES(NULL, $id, 'Functions', 0)");
}
If it works and returns what you need. And it writes data to your database correctly then go to the next step.
4)Uncomment this code.
if(isset($_POST['functions_question'])){
$res = $db->query("SELECT score FROM answers WHERE id=$id AND question_group='Functions'");
$data = $res->fetch_array();
if($_POST['functions_question']==$_SESSION['functions_question']){
if($data['score']<2)$db->query("UPDATE answers SET score = score+1 WHERE id=$id AND question_group='Functions'");
}
If it returns what you need and update your database table correctly then go to the next step.
5) Uncomment the last chunk of your code
else{
if($data['score']>-2)$db->query("UPDATE answers SET score = score-1 WHERE id=$id AND question_group='Functions'");
}
Test it the same way you tested previous code.
This will help debug your code.

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

Updating HTML Element Every Second With Content From MySQL Database

I'd like to have a div on my web page that is based off of the data in my MySQL database. When the data in the database changes, the content in the div should change as well.
Example: Let's say I have a field in the first row of a table called "server_statistics" in my MySQL database which keeps track of a server being online or offline. When the server goes offline, the MySQL field changes from 1 to 0. When it goes online, it goes from 0 to 1.
So I want to use Javascript to display the server status on my webpage and update it without refreshing the page.
I thought I'd be able to do it like this:
<script type="text/javascript">
var int = self.setInterval("update()", 1000);
function update() {
var statusElement = document.getElementById("status");
var status = "<?php
$con = mysql_connect("localhost", "root", "");
mysql_select_db("database_name", $con);
$row = mysql_fetch_array(mysql_query("SELECT * FROM server_statistics LIMIT 1"));
mysql_close($con);
echo $row[0]; ?>";
if (status == 0) {
statusElement.style.color = "red";
statusElement.innerHTML = "offline";
}
else {
statusElement.style.color = "green";
statusElement.innerHTML = "online";
}
}
</script>
But this doesn't work. The page needs to be refreshed for it to update and I don't know why...
I've read I can use JQuery but I have no knowledge of this language at all.
I tried this:
<script type="text/javascript">
var int = self.setInterval("update()", 1000);
function update() {
$('#status').load('load.php');
}
</script>
and then in load.php I had this:
<?php
echo "test";
?>
But nothing happened after 1 second passed. I'm probably doing it wrong because as I said, I don't know anything about this JQuery/AJAX stuff.
So how can I accomplish retrieving a field from a MySQL database at every specified interval and then automatically update an HTML element accordingly? It would be ideal to only update the HTML when a change occurred in the database but for now, I just want it to change every few seconds or minutes...
Thanks in advance.
What you need to do is utilize AJAX. Your page will need to make a request to the server each time it wants to check the status. There are two ways to do it: manually refresh the page yourself, or use an AJAX call.
AJAX really isn't all that difficult, you start by creating a separate PHP page check_status.php with the following in it:
<?php
$con = mysql_connect("localhost", "root", "");
mysql_select_db("database_name", $con);
$row = mysql_fetch_array(mysql_query("SELECT * FROM server_statistics LIMIT 1"));
mysql_close($con);
echo $row[0]; ?>
Then, in your HTML page, the easiest way to do this would be to use jQuery:
var statusIntervalId = window.setInterval(update, 1000);
function update() {
$.ajax({
url: 'check_status.php',
dataType: 'text',
success: function(data) {
if (parseInt(data) == 0) {
$("#status").css({ color: "red" }).text("offline");
} else {
$("#status").css({ color: "green" }).text("online");
}
}
}
}
That's it really. Every second, it will call the update() method which makes an AJAX call and inserts the result back into your HTML.
instead of var int = self.setInterval("update()", 1000); try using self.setInterval(update, 1000); and place it after the update function.

Categories