How to handle AJAX error if sql update fails? - php

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.

Related

Implement Ajax for a PHP Function

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).

how to open html page using trigger

i am using database trigger
when database row updated i want to get real time notification like change happened now
suppose i am using message table in my database
suppose user inserted value in message table. i want change should be noted using
trigger at real time and then i want open an html page when row inserted in my
message table then html page should open or an alert box show notification
that"you received a new message".
Please help me to solve this problem
for example
CREATE TRIGGER notifyMe
ON table1
AFTER INSERT, UPDATE, DELETE
AS
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'DB AutoMailer',
#recipients = 'user#example.com',
#body = 'The DB has changed',
#subject = 'DB Change';
in above example mail is sending but i want to open html page i need syntax to open html page
Well below is a example of what you need exactly:
javascript
var old_count = 0;
setInterval(function(){
$.ajax({
type : "POST",
url : "file.php",
success : function(data){
if (data > old_count) {
alert('new record on i_case');
old_count = data;
}
}
});
},1000);
then php
$sql = "SELECT count(*) as count FROM i_case";
$qry = pg_query($connection, $sql);
$row = pg_fetch_assoc($qry);
echo $row['count'];

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

Display Notifications

I'm trying to follow the first answer here in order to accomplish my alert feature on my app. Facebook like notifications tracking (DB Design)
but in that example, the user has to open the notifications page to check for new notifications. For me, i need to let user knows that there is a notification (database updated) by displaying an icon like Facebook alerts or something like that.
is there any clear idea about how to do that ?
EDIT
i did something but can't test it coz i don't have my laptop right now.
would you please take a look and let me know if something not OK ?
PHP file
$userID=$_GET["userid"];
//Database connection
$sql = 'SELECT count(*) as count FROM list_notifications WHERE userid ='.$userID;
$qry = pg_query($sql);
$row = pg_fetch_array($qry);
echo $row['count'];
jQuery & JavaScript
var old_count = -1;
setInterval(function() {
$.get("file.php", { userid: "userid" },
function(data){
if (data > old_count) {
alert("the list is updated with: " + data);
//OR
//console.log('the list is updated with:' + data);
old_count = data;
}
}
)},5000); // every 5 seconds
once the user is logged in, the userid must be sent periodically to the php file to check for new notifications. then display them to the user.
for count variable, i made it Increases incrementally with Database trigger.

Categories