A Better way of doing Fade Out with PHP - javascript

I amc creating A Login script with php and javascript.
What I want to do is log the user in without the page refresh which I have archived so far, With some help from Stack Flow users, I am fairly good with PHP but new to the Javascript client side.
Anyway, When the user enters the correct data and the session gets started how do I get it to call the fade out function?
Heres the PHP Side
<?php
require "../core/database.php";
//lets create some veriables to use, This way is shorter
$username = strip_tags(trim($_POST['user_login']));
$password = strip_tags(trim($_POST['pass_login']));
$md5_pass = md5($_POST['pass_login']);
$user_login = mysql_real_escape_string($username);
$pass_login = mysql_real_escape_string($md5_pass);
if (($user_login) && ($password)) {
//Connect to the database to fetch the users username and password
$select_user = mysql_query("SELECT username,password FROM users WHERE username='$user_login' AND password='$pass_login'");
$user_rows = mysql_fetch_array($select_user);
$username_row = $user_rows['username'];
$password_row = $user_rows['password'];
if(($username_row==$user_login) && ($md5_pass==$password_row)) {
//All user information is correct, Now start the session
//I HAVE CALLED IT HERE HOPING THERE,S A BETTER WAY OF DOING THIS. IT WILL CAL
echo "
Yes, Now we can start the session right here, when your ready.
<script>
$('#field').fadeOut();
</script>";
} else {
echo "The username or password you entered is incorrect";
}
} else {
echo "<b>Blank Fields</b> <br>
You must enter A Username/Password Combination";
}
?>
Incase yous need it, there is the client side aswill (modified by some users to make the functionality better)
$(document).ready(function() {
// Make a function that returns the data, then call it whenever you
// need the current values
function getData() {
return {
user_login: $('#user_login').val(),
pass_login: $('#pass_login').val()
}
}
function loading(e) {
$('#content').html('Loading Data');
}
function check(e) {
e.preventDefault();
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: getData(), // get current values
success: function (data) {
$('#content').html(data);
}
});
}
// Don't repeat so much; use the same function for both handlers
$('#field').keyup(function(e) {
if (e.keyCode == 13) {
var username = $('#user_login').val();
loading(e);
check(e);
}
});
$('#submit').click(function(e) {
if (e.keyCode != 13) {
loading(e);
check(e);
}
});
});
Since PHP is Server Side and Java Script controls the Client side, Probably the best way to do or call it is this way, But its worth A ask anyway.
Besides this everything is working out well.
If you want you can help change the way loading data is coded/works, But the functionality is working perfectly so theres not much need.

The ajax success method needs to check the response from the server to see if login was successful and then take the appropriate action:
// php
if(($username_row==$user_login) && ($md5_pass==$password_row)) {
//All user information is correct, Now start the session
echo 'correct';
} else {
echo 'The username or password you entered is incorrect';
}
// js
function check(e) {
e.preventDefault();
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: getData(), // get current values
success: function (data) {
if (data === 'correct') {
$('#field').fadeOut();
} else {
$('#content').html(data);
}
}
});
}

Returning JSON instead of raw HTML is much more flexible. Quick example:
PHP Side
<?php
require "../core/database.php";
$json = array('success' => false, 'error' => null);
$username = strip_tags(trim($_POST['user_login']));
$password = strip_tags(trim($_POST['pass_login']));
$md5_pass = md5($_POST['pass_login']);
$user_login = mysql_real_escape_string($username);
$pass_login = mysql_real_escape_string($md5_pass);
if (($user_login) && ($password)) {
$select_user = mysql_query("SELECT username,password FROM users WHERE username='$user_login' AND password='$pass_login'");
$user_rows = mysql_fetch_array($select_user);
$username_row = $user_rows['username'];
$password_row = $user_rows['password'];
if(($username_row==$user_login) && ($md5_pass==$password_row)) {
$json['success'] = true;
}
else {
$json['error'] = "The username or password you entered is incorrect";
}
} else {
$json['error'] = "<b>Blank Fields</b> <br>You must enter A Username/Password Combination";
}
echo json_encode($json);
Your AJAX function:
function check(e) {
e.preventDefault();
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: getData(), // get current values
success: function (data) {
var loginResult = JSON.parse(data);
if(loginResult.success){
//Login successful - fade out whatever form or fields
//that you want to
$('#field').fadeOut();
} else{
//Add error message to an error div or whatever
$('#error').html(loginResult.error);
}
}
});
}

I'll start by saying that your PHP should be using the newer mysqli_* functions or the PDO object for all of your database queries. Further, you should be using prepared statements which will safeguard you against SQL injection attacks.
Another thing to note is that in a PHP file that is not going to output anything to the browser, or in other words, is just going to run some code, you don't need a closing tag. In fact, you don't want a closing tag. That is because anything after the closing tag will get sent to the browser, which will get included in the response of your AJAX success function. That includes things like spaces and new lines.
Now, on to your PHP. You are going to want to output some JSON so that you can check for success or failure in your AJAX.
PHP
<?php
require "../core/database.php";
//lets create some veriables to use, This way is shorter
$username = strip_tags(trim($_POST['user_login']));
$password = strip_tags(trim($_POST['pass_login']));
$md5_pass = md5($_POST['pass_login']);
$user_login = mysql_real_escape_string($username);
$pass_login = mysql_real_escape_string($md5_pass);
//Create an array to represent our JSON data.
$json = array(
"successCode" => 0
);
if (($user_login) && ($password)) {
//Connect to the database to fetch the users username and password
$select_user = mysql_query("SELECT username,password FROM users WHERE username='$user_login' AND password='$pass_login'");
$user_rows = mysql_fetch_array($select_user);
$username_row = $user_rows['username'];
$password_row = $user_rows['password'];
if(($username_row==$user_login) && ($md5_pass==$password_row)) {
//All user information is correct, Now start the session
//echo "Yes, Now we can start the session right here, when your ready."
$json['successCode'] = 0;
} else {
//echo "The username or password you entered is incorrect";
$json['successCode'] = 1;
}
} else {
//echo "<b>Blank Fields</b> <br>
//You must enter A Username/Password Combination";
$json['successCode'] = 2;
}
//Set that our content type is JSON
header("Content-type: application/json");
echo json_encode($json); //Convert the PHP array to JSON and echo it as the response.
In our PHP, we have created a $json array which will story the successCode that we will be responding to the client. This will tell the client if the login was a success or failure, and even what type of failure occurred. It will then be up to the client to decide how to display that success or failure to the user. This allows multiple applications to use the same server side source, but display the errors differently if desired.
At the end of the PHP, we have set the header Content-type to specify that we are sending back application/json to the client. Then, we encode the PHP array as JSON, and output it to the response.
jQuery/Javascript
//Let's define different messages depending on what status code we get on the client.
var errorMessages = [
"Yes, Now we can start the session right here, when your ready.",
"The username or password you entered is incorrect",
"<b>Blank Fields</b><br />You must enter A Username/Password Combination"
];
function check(e) {
e.preventDefault();
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: getData(), // get current values
success: function (data) {
//First, make sure that data and data.successCode are defined.
if (data && data.successCode) {
//Here, you are getting back the JSON data from the login call.
$('#content').html(errorMessages[data.successCode]);
//If the successCode is 0, which means it was successful, then we want to fade out the #field div.
if (data.successCode == 0) {
$('#field').fadeOut();
}
} else {
//There must've been a server error. You'd handle that here.
}
}
});
}
Why put the error messages on the client instead of the server? Because it allows you to easily change how the error messages are displayed, without having to touch the server side code. The server just outputs an error code, and the client decides how to handle that code.
The Javascript array, errorMessages, defines the error messages corresponding to their index in the array. The error message at index 0 would correspond to successCode = 0, and so on. If you weren't going to use sequential successCodes, you could use a javascript object to specify keys corresponding to each error code.

Related

Button to change value in SQL without any redirection

Trying to use Javascript to pass the value from a button
to execute a PHP Script (The script simply changed a boolean column to 1 / True.
However i cannot get the code to work, i am not sure if its my Formatting, but i am not very familiar with Javascript
i am simply trying to change the value in the SQL Database on a column without any redirection.
index.php
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script language="javascript">
$("body").on("click","button", function(ev){
ev.preventDefault(); // prevent submitting a form ...
let data={id: $(this).data("id")}
$.post("viewed.php",data)
.done(function (result) {
console.log("Message:",result);
});
});
</script>
My Button index.php
<div><button name="Delete" data-id='<?echo $data['orderReference']?>'">Delete</button></div>
and Viewed.php
$orderID = $_POST['id'] ;
if ($_POST)
{
try {
$sqlOrderviewed = "UPDATE `Order_Header` SET `orderViewed` = '1' WHERE `Order_Header`.`orderReference` IN ($orderID) ";
$resultOrderupdate = $products->conn->query($sqlOrderviewed); // Execute Statement
echo $count = $resultOrderupdate->rowCount();
} catch
(PDOException $e) { // If error in SQL
echo "One or more errors occurred saving to database This transaction will be rolled back:" . $e->getMessage(); // Display Message on End Point
// $products->conn->rollback(); // Rollback SQL
}
}
I am aware of the SQL Injection in this example, this is not production just trying to get an example working
To do this I would suggest making REST API type behaviour in your PHP that accepts JSON (as an example) which you can define with headers. So your JavaScript can stay mostly the same, just make sure you are pointing to the correct URL. But I think your PHP should look more like this:
<?php
// Headers
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: POST'); //maybe make this an update to be Semantic with the SQL operation you are doing
// Get raw data from the post you made in JavaScript
$data = json_decode(file_get_contents("php://input"));
$id = $data.id;
// Use the data in your SQL
$sqlOrderviewed = "UPDATE `Order_Header` SET `orderViewed` = '1' WHERE `Order_Header`.`orderReference` IN ($id) ";
?>
If you need more information on creating APIs with PHP I suggest these resources:
https://www.youtube.com/watch?v=OEWXbpUMODk
https://shareurcodes.com/blog/creating%20a%20simple%20rest%20api%20in%20php
https://github.com/bradtraversy/php_rest_myblog
I am not sure that $(this).data("id") is getting the data you want. I assume you want to get the value of data-id in your button? If so I would change your JavaScript to something more like this:
<script language="javascript">
$("body").on("click","button", function(ev){
ev.preventDefault(); // prevent submitting a form ...
let id = ev.target.getAttribute("data-id");
let data={id: id};
$.post("http://localhost:{port}/viewed.php",data)
.done(function (result) {
console.log("Message:",result);
});
});
</script>
I hope this helps!
P.S this is how I might have written the JS for this, I just find it a bit more readable (Not tested, just written in the MD editor while answering the question):
let buttons = document.querySelectorAll("button");
buttons.forEach((button) => {
button.addEventListener("click", (e) => {
e.preventDefault();
let id = e.target.getAttribute("data-id");
let data = {
id: id
};
$.ajax({
type: 'POST',
url: '/viewed.php',
data: data,
success: function(result){
console.log( "result: " + result );
}
})
})
});

Ajax call to submit text into database don't work

I have a page where users can put comments below photos, everything works fine in php, comments go to the database and displayed below the photo.
Now I'm trying to make it work with ajax but I have some troubles.
I have an javascript document with this:
$(document).ready(function(){
$("#btnSubmit").on("click", function(e){
var update = $("#activitymessage").val()
$.ajax({
method: "POST",
url: "./ajax/save_comment.php",
//data: { update: update}, - first version, not correct
data: { activitymessage: update},
datatype: 'json'
})
.done(function(response) {
console.log("ajax done");
console.log (response.message);
var ht = "<li>" + update + "</li>";
$("#listupdates").append(ht);
});
e.preventDefault();
});
});
The php page (save_comment.php) where I tell what to do with the input text:
<?php
spl_autoload_register(function ($class) {
include_once("../classes/" . $class . ".class.php");
});
$activity = new Comment();
if (!empty($_POST['activitymessage'])) {
$activity->Text = $_POST['activitymessage'];
try {
//$activity->idPost = $_GET['nr'];
//$activity->idUser = $_SESSION['user_id'];
// with this it works, but not yet correct
$activity->idPost = 66;
$activity->idUser = 3;
$activity->SavePost();
$response['status'] = 'succes';
$response['message'] = 'Update succesvol';
} catch (Exception $e) {
$error = $e->getMessage();
$response['status'] = "error";
$response['message'] = $feedback;
}
header('Content-type: application/json');
echo json_encode($response);
}
There is also the file Comment.class.php with the 'Comment' class and the function SavePost(). This works without ajax, so I assume the function is correct.
What works
the comment (var update) is printed on the screen into the list.
The console says : "ajax done"
What don't work
The input text don't insert into the database (and disappears when page refresh)
The console says: "undefined" (there must be something wrong with the 'response I use in this function)
I hope you guys can help me out. Thanx
update
I changed the: data: { activitymessage: update} line in the js file, and set manually values for the $activity->idPost = 66; $activity->idUser = 3; And everything works !
Only one thing I want to get fixed
the values of the $_GET['nr'] and $_SESSION['user_id'] are now set manually. Is this possible to get these automatic?
The $_GET['nr'] is the id of the page were the photo is and the comments. In this way I can make a query that returns all comments for this page.
The $_SESSION['user_id'] is the id of the user,so I can echo the username and profile photo.
You are sending data with the key being update not activitymessage
Change data to:
data: { activitymessage: update}
Or change $_POST['activitymessage'] to $_POST['update']
Also you have no $_GET['nr'] in url used for ajax. Nothing shown would help us sort that out but you would need the url to look more like:
url: "./ajax/save_comment.php?nr=" + nrSourceValue,
Not sure why you need to use $_GET['nr'] and don't use $_POST for that also and and nr property to data object being sent

Update a DIV tag from PHP

I'm a new developer. I've read a lot of question all around about my topic, and I've seen a lot of interesting answers, but unfortunately, I cannot find a way to resolve mine.
I have a simple form in HTML and <div id="comment"></div> in it (empty if there is nothing to pass to the user). This DIV is supposed to give updates to the user, like Wrong Username or Password! when it's the case. The form is treated via PHP and MySQL.
...
$result = mysqli_query($idConnect, $sql);
if (mysqli_num_rows($result) > 0) {
mysqli_close($idConnect);
setCookie("myapp", 1, time()+3600 * 24 * 60); //60 days
header("Location: ../main.html");
} else {
//Please update the DIV tag here!!
}
...
I tried to "read" PHP from jQuery (with AJAX), but whether I didn't have the solution, or it cannot be done that way... I used this in jQuery (#login is the name of the form):
$("#login").submit(function(e){
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url : formURL,
type: "POST",
data : postData,
success:function(data) {
$("#comment").replaceWith(data); // You can use .replaceWith or .html depending on the markup you return
},
error: function(errorThrown) {
$("#comment").html(errorThrown);
}
});
e.preventDefault(); //STOP default action
e.unbind();
});
But I'd like to update the DIV tag #comment with some message if the credentials are wrong. But I have no clue how to update that DIV, considering PHP is treating the form...
Can you help please ?
Thanks in advance ! :)
In order for AJAX to work, the PHP must echo something to be returned from the AJAX call:
if (mysqli_num_rows($result) > 0) {
mysqli_close($idConnect);
setCookie("myapp", 1, time()+3600 * 24 * 60); //60 days
echo 'good';
} else {
//Please update the DIV tag here!!
echo 'There is a problem with your username or password.';
}
But this will not show up in error: function because that function is used when AJAX itself is having a problem. This text will be returned in the success callback and so you must update the div there:
success:function(data) {
if('good' == data) {
// perform redirect
window.location = "main.html";
} else {
// update div
$("#comment").html(data);
}
},
In addition, since you're calling the PHP with AJAX, the header("Location: ../main.html"); will not work. You will need to add window.location to your success callback dependent upon the status.
To begin, your pretend is using Ajax to send form data to PHP. So your client (HTML) have to communicate completely via Ajax. After you do authenticate, you need send an "Ajax sign" to the client.
$result = mysqli_query($idConnect, $sql);
if (mysqli_num_rows($result) > 0) {
mysqli_close($idConnect);
setCookie("myapp", 1, time()+3600 * 24 * 60); //60 days
echo 'true';//it's better for using json format here
// Your http header to redirect won't work in this situatition
// because the process is control by javascript code. Not PHP.
} else {
echo "false";//it's better for using json format here
}
//the result is either true or false, you can use json to send more details for client used. Example: "{result:'false', message:'wrong username'}";
// use PHP json_encode(Array(key=>value)) to convert data into JSON format
Finally, you have to check the "Ajax sign" in your js code:
$("#login").submit(function(e){
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url : formURL,
type: "POST",
data : postData,
success:function(data) {
// You can use `data = JSON.parse(data)` if the data format is JSON
// Now, data.result is available for your checked.
if (data == 'true')
window.location.href = "main.html";
else
$("#comment").html('some message if the credentials are wrong');
},
error: function(errorThrown) {
$("#comment").html('Other error you get from XHTTP_REQUEST obj');
}
});
e.preventDefault(); //STOP default action
e.unbind();
});

Is this piece of jquery ajax code correct?

I am making a simple web chat application using ajax,php,javascript and mysql.
What I am trying to do here is to avoid fetching the whole database after an interval of 1 sec(which is normally done in basic chat application ) but rather I want to fetch and display(by appending) also those chats which have been newly entered into the database by any user.
To implement this ,First when the user first opens the chat screen the whole database is loaded in the chat window(not shown in this code snippet),and then I am using the variable msgid to fetch the latest value of MSg_ID (which is the auto-increment primary key in my chat table) through an ajax request to the page 'Msg.php' which returns the required value of msg_id.
Now using this value of msgid and comparing it with the max value of Msg_ID every second in the database through the ajax request to the page 'Chat3.php'.
If the Max value of Msg_ID has changed the required rows are returned . After this I m updating the value of 'msgid' using the same earlier ajax request to the page 'Msg.php'
The pages Msg.php and Chat3.php are working perfectly ,as I have tested them thoroughly.
My question here is what is the problem in my code , why is not working?
Can we use an ajax request inside a ajax call back function or not?
What else can be a probable source of error?
Any input will be valuable :)
If you have any problem in understanding the code,leave a comment.
'#yyy' and '#zzz' are random div elements which i am using to test the data value of ajax callback function.
I can even post the rest of the code if it helps.
<script type"text/javascript">
$(document).ready(function() {
var dept = '<?php echo $deptId; ?>';
$.ajax({
url: 'scripts/php/Msg.php',
data: {dept:dept},
success: function(data) {
$('#yyy').html(data);//this displays the correct value
var msgid=data;
}
});
var interval = setInterval(function() {
$.ajax({
url: 'scripts/php/Chat3.php',
data: {dept:dept,msgid:msgid},
success: function(data) {
if(data!='bad'){
//$('#messages').prepend(data);
$('#zzz').html(data);//does not display any value although Chat3.php is returning the correct value.
//below ajax request to update the value of msgid
$.ajax({
url: 'scripts/php/Msg.php',
data: {dept:dept},
success: function(data) {
var msgid=data;
$('#zzz').html(data); //not displaying anything although above one is was displaying
}
});
}
}
});
}, 1000);
});
</script>
Here is my Msg.php
<?php
require '../../includes/database/connect.db.php';
function get_msg($dept){
$query= "SELECT Msg_ID,Sender, Message ,Time_stamp FROM chat WHERE Dept_ID='$dept' ORDER BY Msg_ID DESC" ;
$run=mysql_query($query);
$messages =array();
while($message=mysql_fetch_assoc($run)){
$messages[] =array('msgid'=>$message['Msg_ID'],
'sender'=>$message['Sender'],
'message'=>$message['Message'],
'time_stamp'=>$message['Time_stamp']);
}
return $messages;
}
$dept=$_GET['dept'];
$messages = get_msg($dept);
$x=count($messages);
if($x){
foreach($messages as $message) {
if($x==count($messages)){
echo $message['msgid'];
}
$x--;
}
}
?>
Here is my Chat3.php
<?php
require '../../includes/database/connect.db.php';
function get_msg($dept,$msgid){
$query1= "SELECT MAX(Msg_ID) as msg_id FROM chat" ;
$run1=mysql_query($query1);
$row = mysql_fetch_assoc($run1);
$result =$row['msg_id'];
$messages =array();
if($result>$msgid)
{
$query= "SELECT Sender, Message ,Time_stamp FROM chat WHERE Dept_ID='$dept' AND Msg_ID>'$msgid' ORDER BY Msg_ID DESC" ;
$run=mysql_query($query);
while($message=mysql_fetch_assoc($run)){
$messages[] =array('sender'=>$message['Sender'],
'message'=>$message['Message'],
'time_stamp'=>$message['Time_stamp']);
}
return $messages;
}
else
{
return $messages;
}
}
$dept=$_GET['dept'];
$msgid=$_GET['msgid'];
$messages = get_msg($dept,$msgid);
if(count($messages)){
foreach($messages as $message) {
echo '<strong>'.$message['sender'].' Sent</strong><br>';
echo $message['message'].' <i><small><div align="right">'.$message['time_stamp'].'</i></small></div>';
}
}
else {
echo 'bad';
}
?>
The problem is the msgid
In your first AJAX Request you are setting the variable var msgid=data; which is in local scope.
I think you are trying to access that variable in the second AJAX request while sending the datas
url: 'scripts/php/Chat3.php',
data: {dept:dept,msgid:msgid}, // Trying to access the local variable of previous ajax request
EDIT:
Try removing the var from var msgid=data; in your first AJAX request. Removing var will make the variable GLOBAL, Although its not good to pollute the global scope, but you can definitely try out this for the time being

How to make javascript work as a response to php events?

I am developing a website for practice, and I would like to know how to use JS to notify the user that the username he picked is already in use, all works fine, if my function(check_username) returns false, the user succesfully registers himself into the site, otherwise the register won't happen.
When the user can't register I would like to know how can I notify the user with a js script.
<?php
//database includes
include_once('../config/init.php');
include_once('../database/users.php');
if(!check_username($_POST['username'])) {
insertUser($_POST['name'], $_POST['username'], $_POST['email'], $_POST['pass']);
}
else header('Location: ../index.php');
?>
One way would be to change your redirect on failure to a javascript message
else
{
echo "<script>alert('Username already exists');</script>";
}
That's a very trivial example to get you started since you mentioned you're learning JS. You can build a lot of improvements on that.
You can set the returns into a javascript variable and use it to display message if the user is not registered.
var x = <?php echo check_username($_POST['username']); ?>;
if(x) {
alert("You are not registered");
}
You can use php ajax for a live notification to users.
<script>
$(document).ready(function() {
$("#InputFieldID").keyup(function (e) {
//removes spaces from username
$(this).val($(this).val().replace(/\s/g, ''));
//Getting value of input field.
var username = $(this).val();
//Check only if the username characters are above 4
if(username.length >= 4){
$("#IndicatorDivID").html('<p style="color:#ffbf25;">Checking..!</p>');
$.ajax({
type: 'POST',
url: 'check_username.php',
data: {"username": username},
dataType: 'json',
success: function (data) {
if(data.response=='true')
alert("Already Exist");
}
});
}
});
});
//Username Checker
</script>
The result fo check_username.php must be in json format.
eg: {"response":"false"}

Categories