on page login with jquery - javascript

I want to create on-page login system.
Without javascript I can login perfectly in this structure:
<?php
require_once('login.php');
$login = new Login();
// if we are logged in here:
if ($login->isUserLoggedIn() == true) {
// yes we are
echo "<div id=\"login\">you logged in as $_SESSION[user_name]. Logout</div>";
} else {
// no
echo "
<div id=\"login\" style=\"display: none;\">
<form action=\"index_.php\" method=\"post\" name=\"loginform\" id=\"loginform\" onsubmit=\"return false;\">
<input type=\"text\" class=\"form-control\" id=\"user_name\" name=\"user_name\><br>
<input type=\"password\" class=\"form-control\" id=\"user_password\" name=\"user_password\"><br>
<label class=\"checkbox-label\" style=\"pointer-events: all;\" for=\"user_rememberme\"><input checked class=\"user_rememberme\" name=\"user_rememberme\" id=\"user_rememberme\" value=\"1\" type=\"checkbox\"/>
Remember me</label>
Forgot Password?
<input class=\"btn btn-success\" type=\"submit\" name=\"login\" id=\"loginbutton\" value=\"Login\">
</form>
</div><!-- login ends -->
";
}
?>
Currently on working system, I'm sending form to current page. And code below telling user the result: (for instance. you logged in, please activate your account, login failed.)
<?php
// I send the form same page upside.
// and if i login or not, codes below lets me know.
if (isset($login)) {
if ($login->errors) {
foreach ($login->errors as $error) {
echo "<div id=\"message\">$error</div>";
}
}
if ($login->messages) {
foreach ($login->messages as $message) {
echo "<div id=\"message\">$message</div>";
}
}
}
?>
As a next step, I want to login on-page with the help of ajax. So Here is my javascript code to start with:
<script type="text/javascript">
// login on page
$(function(){
$("#loginform").submit(function(){ // .click yerine .submit
if($("#loginform").valid()){
$.ajax({
type: "POST",
url: "index_.php",
data: $("#loginform").serialize(),
beforeSend: function(){
$('#message').html('Loading...');
},
success: function(data){
$('#message').html(data);
}
});
}
});
});
</script>
Specifically this part of javascript code
success: function(data){
$('#message').html(data);
I want to output my php result, but copying php inside of data obviously doesn't work.
What should I do?

You can add an extra POST-Field (for example "AJAX")
and return other output, if this is set
$.ajax({
type: "POST",
url: "index_.php",
data: $("#loginform").serialize() + "&ajax=1",

Related

removing users from page on button click using ajax technology

I want to remove the whole element on button click.
Removal must be done through Ajax technology, that is, without reloading the page.
After deleting a user, the entry with him should disappear from the list of all users.
Here is the structure of my code:
<?php
require_once "lib/mysql.php"; //database connection
$query = $pdo->prepare('SELECT * FROM `users`');
$query->execute();
$users = $query->fetchAll(PDO::FETCH_ASSOC);
foreach($users as $user) {
echo '<div class="infoAllUsers"><b>Name: </b>' . $user['name'] . ', <b>Login: </b>' . $user['login'] . '<button onclick="deleteUser('.$user['id'].');">Delete</button></div>';
}; //display all users
?>
<script>
function deleteUser(id) {
$.ajax({
url: 'ajax/deleteUser.php',
type: 'POST',
cache: false,
data: {'id': id},
success: function(data) {
$(this).closest(".infoAllUsers").remove();
}
});
}
</script>
There are no errors in js and php, there is nothing in the console, deletion from the database occurs correctly.
I am new to jQuery so I have tried some things like:
$(this).parent('div').remove();
$(this).closest('div').remove();
$(this).parent('.infoAllUsers').remove();
Take a different/cleaner approach
Set the id as a data attribute and assign a class, then add the click event to that.
<button class="delete" data-id="'.$user['id'].'">Delete</button>
$('.infoAllUsers .delete').click(function(elm) {
$.ajax({
url: 'ajax/deleteUser.php',
type: 'POST',
cache: false,
data: {
'id': $(elm).data('id')
},
success: function() {
$(elm).parent().remove();
}
});
})
<?php
require_once "lib/mysql.php"; //database connection
$query = $pdo->prepare('SELECT * FROM `users`');
$query->execute();
$users = $query->fetchAll(PDO::FETCH_ASSOC);
foreach($users as $user) {
echo '<div class="infoAllUsers"><b>Name: </b>' . $user['name'] . ', <b>Login: </b>' . $user['login'] . '<button onclick="deleteUser('.$user['id'].', this);">Delete</button></div>';
}; //display all users
?>
<script>
function deleteUser(id, this2) {
var $t = $(this2);
$.ajax({
url: 'ajax/deleteUser.php',
type: 'POST',
cache: false,
data: {'id': id},
success: function(data) {
$t.closest('.infoAllUsers').remove();
}
});
}
</script>
The code seems correct, the only thing that occurs to me is that your php backend is not returning an Http code that is in the 2XX range and that is why it does not enter the success function of your ajax request, have you tried to make a console.log() inside the function that deletes the <div> to see if the JS reaches that point?
Jquery.ajax() function documentation

PHP - How to avoid reload a form when change route

I have this simple form in index.php:
<div class="form-container">
<form id="create-form" action="create.php" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<br/>
<label for="score">Amount:</label>
<input type="number" id="score" name="score">
<br/>
<input type="submit" name="addBtn" id="addBtn" value="Add" />
</form>
</div>
What create.php contains:
<?php
include 'db.php';
$name = $_POST["name"];
$score = $_POST["score"];
$sql = "insert into demo_table (name, score) values ('$name', '$score')";
$conn->query($sql);
$conn->close();
header("location: index.php");
?>
Currently, I have this script in index.js using JQuery and AJAX but keeps reloading the page because of the index.php call.
$(document).ready(function () {
$('#create-form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'create.php',
data: $(this).serialize(),
success: function(response)
{
console.log('agregado');
location.href = 'index.php';
}
});
});
});
Currently this works well, but reloads the page when clicking on the button and when reload the data (last line in create.php). What I am trying to do is to implement AJAX and/or JQuery in order to avoid this and have a complete Single Page Application.
Disclaimer: I am starting learning PHP. So, I am making any mistake, please let me know first of all. I will be attentive to your answers.
Try to make in comment the code location.href = 'index.php'; inside the success method.
Like that :
$(document).ready(function () {
$('#create-form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'create.php',
data: $(this).serialize(),
success: function(response)
{
console.log('agregado');
// location.href = 'index.php';
}
});
});
});

Pass javascript prompt input to PHP variable

So I am working on a code signing system for iOS. I need a user's UDID before they can access the website. How can I pass the javascript prompt input to a php variable.
I have tried posting the variable back to the same page.
<?php
$udid = $_POST['udid'];
if(empty($udid)){
$udid = file_get_contents("saves/" . $ip . ".txt");
}
if(empty($udid)){
?>
<script>
var udid=prompt("Please enter your UDID");
$.ajax(
{
type: "POST",
url: "app.php",
data: udid,
success: function(data, textStatus, jqXHR)
{
console.log(data);
}
});
</script>
<?php
}
if( strpos(file_get_contents("cert1.txt"),$udid) !== false) {
echo "Device status:<br><span class='badge badge-dark'>Signed</span><br>";
echo "Signed on cert:<br><span class='badge badge-dark'>1</span><br>";
} else {
$t = ' ' . time();
echo "<p>Device status:<br><span class='badge badge-dark'>Unsigned</span><br>You are now<br>on the waitlist</p><script>alert(\"Your device isn't approved yet. We have added you to the waitlist. Check back soon.\");</script>";
$txt = $_GET['udid'] . $t;
$myfile = file_put_contents('notsigned.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);
header("Location: notsigned.php");
}
?>
<br>
Get your udid
<br><br>
<form class='form-horizontal well' action='#' method='post'>
<input type='text' name='udid' class='input-large' size="9" border="2" placeholder="udid" value='<?= $udid ?>'>
<button type="submit" id="submit" style="text-decoration:none;font-family:arial;font-size:15px;color:#fff;padding:8px;border-radius:5px;background-color:springgreen;margin-bottom:5px;" class="badge-primary">Save</button>
</form>
<?php
setcookie("udid", $udid, time()+31536000000, "/");
file_put_contents("saves/" . $ip . ".txt",$udid);
if(empty($udid)){
alert('You cannot access anything till you enter your udid.');
}
?>
What I need it to do is set $udid (PHP) to what the user entered in either the prompt or the input form.
reposting my comment as an answer (with a little more detail):
You should have data: {udid: udid} rather than data: udid. The documentation says that data should be on "object, string or array", but it only mentions a string in the explicit case that it's a query string (eg ?key1=value1&key2=value2). By passing it as an object as shown then you ensure that the PHP backend will be able to access $_POST['udid'] and it will have the intended value.
Note: this object can be abbreviated as just data: {udid} if you're using ES6.
Change the data attribute to the following,
data: {
udid: udid
},

Am i getting html and javascript code when using ajax to pass parameters to the function on onClick event (Ajaxing on the same page)

<html>
tables, textbox, buttons
</html>
<?php
//some php, sql stuff
echo "<td><input type='button' name='disable' value='Disable' onClick='disable($id);'/></td>";
if(isset($_POST['action']) && $_POST['action']=="delete")
{
if(isset($_POST['ID']) && !empty($_POST['ID']))
{
$id = $_POST['ID'];
echo "Id:".$id;
//Call to another function
die();
}
?>
<script>
function disable(id) {
jQuery.ajax({ type: 'Post',
url: '',
data: {action: 'delete', ID: id}
})
.done(function(data) {
alert("Data Saved: " + data);
location.reload();
});
}
</script>
Alert box is showing html code which is in HTML block and successful messages from php block. I don't need to show HTML code, only need to show successful messages. How to do that??? many thanks
The issue is that you need to respond to the ajax request before any html is sent to the browser and call exit; to stop the remaining page content from being sent as well. Something like this would work:
<?php
if(isset($_POST['action']) && $_POST['action']=='delete'){
// process request......
$id = $_POST['ID'];
echo "Id:".$id;
//Call to another function
exit; // stop the script here so it doesnt also return the html content of the page
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
tables, textbox, buttons
<?php
//some php, sql stuff
// note that $id is not defined where you try to use it here in your code, not sure what that's about....
echo "<td><input type='button' name='disable' value='Disable' onClick='disable($id);'/></td>";
?>
<script>
function disable(id) {
jQuery.ajax({ type: 'Post',
url: '',
data: {action: 'delete', ID: id}
})
.done(function(data) {
alert("Data Saved: " + data);
location.reload();
});
}
</script>
</body>
</html>

AJAX form submission with php and jquery

I have looked at everything on here that I can find and I just can't figure out why I cannot perfect this code. What I am trying to do is allow users to delete something that they posted on my site without doing a page refresh. The form is going to be passed to a php file that will modify my MySQL DB. I am new to ajax and have only messed around with PHP for a short time as well.
form:
<form class='status_feedback' id='delete_status' onsubmit='delete_status()' action=''>
<input type='hidden' name='status_id' id='status_id' value='$status_id'/>
<input type='submit' value='X'/>
</form>
delete_status()
function delete_status(){
$.ajax({
type: "POST",
url: "/scripts/home/php/delete_status.php/",
data: status_id,
success: function() {
//display message back to user here
}
});
return false;
}
delete_status.php
<?php
$con=mysqli_connect("localhost","USER","PASSWORD","DB");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$status_id = $_POST['status_id'];
mysqli_query($con,"UPDATE status SET visibility = 'hidden' WHERE id = $status_id");
?>
at this point, all that happens when I strike the delete_status() function is my page refreshes and adds ?status_id=194 (when I click on status #194) to the end or my url.
Any help would be awesome. I have been researching for several days.
Change your HTML, Ajax and php a little.
HTML
Add this code:
<body>
<form class='status_feedback' id='delete_status' >
<input type='hidden' name='status_id' id='status_id' value='$status_id'/>
<input type='button' id='x_submit' value='X' />
</form>
<script>
$('#x_submit').on("click",function(){
var status_id= $('#status_id').val();
//Delete the alert message if you want.
alert("Check your status id :"+status_id);
$.ajax({
type: "GET",
url: "/scripts/home/php/delete_status.php?",
data: {status_id:status_id},
dataType:'JSON',
success: function(json) {
//display message back to user here
alert(json[0].response);
}
});
});
</script>
PHP:
<?php
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: GET, POST');
header('Content-type: application/json');
$con=mysql_connect("localhost","USER","PASSWORD","DB");
// Check connection
if (mysql_connect_errno())
{
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
$status_id = $_GET['status_id'];
$result = mysql_query("UPDATE status SET visibility = 'hidden'
WHERE id = '$status_id'");
if(! $result )
{
$data[]=array('response'=>"Unable to insert!");
}
else
{
$data[]=array('response'=>"Data successfully inserted into the database!");
}
$json_encode = json_encode($data);
print("$json_encode");
?>
Hope it will work.
You are not cancelling the form submission
onsubmit='delete_status()'
needs to be
onsubmit='return delete_status()'
and data: status_id, looks wrong unless you have a variable defined somewhere else

Categories

Resources