I am trying to create a page that will delete a user from my database when it is searched, ask for confirmation, and then delete it, i am extremely close but i need to pass the function through ajax to java script but im not understanding how to do that. Here is my code:
<html>
<head>
<?php
require_once('conn.php');
function deleteEmployee($conn, $employee, $table){
$query = "DELETE from $table where EmployeeName = '$employee'";
$confirmed = mysqli_query($conn, $query);
if ($confirmed){
echo "User Deleted";
}
else{
return True;
echo 'User has been deleted';
}
return;
}
//$query1 = 'select *
?>
<script>
function myFunction() {
var txt;
return confirm('Are you sure?');
if (confirm == true) {
deleteEmployee($conn, $name, "employee");//This is where i am having trouble
} else {
txt = "Okay";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</head>
<body>
<p id="demo"></p>
<form action="" method="post">
Search Name to be Deleted: <input type="text" name="term" /><br />
<button onclick="myFunction()" type="submit" value="Submit" />submit</button>
</form>
<?php
if (!empty($_POST['term'])) {
$term = mysqli_real_escape_string($conn,$_POST['term']);
$sql = "SELECT EmployeeName FROM employee ";
$r_query = mysqli_query($conn,$sql);
if($r_query->num_rows == 0){
echo "Name not in database";
} else{
while ($row = mysqli_fetch_array($r_query)){
$name = $row['EmployeeName'];
}
}
}
?>
</form>
As of right now, the window pops up but when i press ok, nothing happens since i do not understand how to pass a function through ajax to javascript. Can someone help? If you need more info, let me know
How about using jQuery AJAX, storing your php functions in different files and just past post/get data so your PHP methods can process what you want to process?
Example Usage:
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
Related
I want to prevent an echo from an AJAX response. I have 2 buttons and I need to enable and disable them using JS by AJAX responses. The JS code to enable/disable the HTML elements has been already written inside the PHP if condition of the AJAX URL Page. From AJAX I can display the results on <span id="dupmsg"></span>.
The result will be "Already Exists" and "Not Exist". I only want to display the message and enable/disable the buttons based on the condition. Here it's not working:
Index Page in php:
<h2>Enabling and Disabling text field using JavaScript</h2>
<form id="registration-form">
Enter your name: <input type="text" id="name">
</form>
<button onclick="disable()">Disable the text field</button>
<button onclick="enable()">Enable the text field</button>
<p>Ajax Response is: <span id="dupmsg"></span></p>
<script>
function check_dup()
{
var barcode=$("#memb_barcode").val();
$.ajax({
type: 'POST',
url: "ajax_attendance.php",
data: {
barcode: barcode
},
success: function(msg)
{
//alert(msg); // your message will come here.
$('#dupmsg')
.css('color', 'red')
.html(msg)
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
})
}
</script>
Ajax URL Page:
<?php
$reg_no = mysqli_real_escape_string($con, $_POST['reg_no']);
$barcode = mysqli_real_escape_string($con, $_POST['barcode']);
$sql = "SELECT id from tblstudent where reg_no = '$reg_no' && barcode like '$barcode' ";
$query = mysqli_query($con, $sql);
$ecount = mysqli_num_rows($query);
if($ecount!=0)
{
printf("Already Exists");
echo'
<script>
function disable() {
document.getElementById("name").disabled = true;
}
</script> ';
}
else
{
printf("Not Exists");
echo'
<script>
function enable() {
document.getElementById("name").disabled = false;
}
</script> ';
}
?>
The problem is that the JS written inside the PHP echo is reflecting back to span id="dupmsg" with AJAX response. I don't want to bring it in AJAX response. Please help.
<h2>Enabling and Disabling text field using JavaScript</h2>
<form id="registration-form">
Enter your name: <input type="text" id="name">
</form>
<button id="disable" onclick="disable()">Disable the text field</button>
<button id="enable" onclick="enable()">Enable the text field</button>
<p>Ajax Response is: <span id="dupmsg"></span></p>
<script>
function check_dup()
{
var barcode=$("#memb_barcode").val();
$.ajax({
type: 'POST',
url: "ajax_attendance.php",
data: {
barcode: barcode
},
success: function(msg)
{
if(msg=='true'){
document.getElementById("name").disabled = true;
$("#disable").attr("disabled", true); // write the id of the button u want to hide
$('#dupmsg')
.css('color', 'red')
.html("Already Exists")
}
else if(msg=='false')
{
document.getElementById("name").disabled = false;
$("#enable").attr("disabled", false); // write the id of the button u want to hide
$('#dupmsg')
.css('color', 'red')
.html("Not Exists")
}
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
})
}
function enable() {
document.getElementById("name").disabled = false;
}
function disable() {
document.getElementById("name").disabled = true;
}
</script>
ajax_attendance.php
<?php
$reg_no = mysqli_real_escape_string($con, $_POST['reg_no']);
$barcode = mysqli_real_escape_string($con, $_POST['barcode']);
$sql = "SELECT id from tblstudent where reg_no = '$reg_no' && barcode like '$barcode' ";
$query = mysqli_query($con, $sql);
$ecount = mysqli_num_rows($query);
if($ecount!=0)
{
return true;
}
else
{
return false;
}
?>
I have a login form, where I want to pass data from it by Ajax, into a PHP function in another file. The purpose of this is that I want the page not to reload when the user is logging in.
Right now nothing happens when user tries to log in. Seems like access.php is not proccessing the data sent from Ajax.
Can someone tell me why this is not working? What are the possible causes?
index.html:
<div class="login-form">
<form method="post" action="index.php">
<input id="username" type="text" placeholder="Username...">
<input id="password" type="password" placeholder="Password...">
<button id="button" type="submit">Login</button>
</form>
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script type="text/javascript">
$('#button').click(function(e) {
e.preventDefault();
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
type: 'POST',
url: 'resources/includes/access.php',
data: {
func: 'loginSubmit',
usernamePHP: username,
passwordPHP: password
},
success: function(response) {
$('#result').html(response);
}
});
});
</script>
</div>
access.php:
function loginSubmit(){
require '../dbh.inc.php';
$mailuid = $_POST['usernamePHP'];
$password = $_POST['passwordPHP'];
if(empty($mailuid) || empty($password)){
header("Location: ../../index.php?error=emptyfields");
exit();
}
else{
$sql = "SELECT * FROM users WHERE uidUsers=? OR emailUsers=?;";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)){
header("Location: ../../index.php?error=sqlerror");
exit();
}
else{
mysqli_stmt_bind_param($stmt, "ss", $mailuid, $password);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if($row = mysqli_fetch_assoc($result)){
$pwdcheck = password_verify($password, $row['pwdUsers']);
if($pwdcheck == false) {
header("Location: ../../index.php");
exit();
}
else if($pwdcheck == true) {
session_start();
$_SESSION['userId'] = $row['idUsers'];
$_SESSION['userUid'] = $row['uidUsers'];
header("Location: ../../index.php?login=success");
exit();
}
else{
header("Location: ../../index.php");
exit();
}
}
}
}
}
From what I can see from the documentation, adding the function name as a data property as you are, doesn't call that function;
data
Type: PlainObject or String or Array
When you call access.php, the file simply contains a function definition, you're not actually calling it.
So you have two options. Either call the function by adding loginSubmit() after the function (at the end of access.php), or remove the code on access.php from a function entirely.
Im all new to ajax and jquery so iam asking u guys for some help. I have to forms that one creates a new user and second logs the user in.
The functions work greate, but i want to create alert boxes for success or failure of the functions.
And i dont know how... Here is my code
HTML
<!-- Formular for signing up -->
<h4 class="form-headline"> Not a member? Sign up here </h4>
<form method="post">
<div class="form-group">
<label> Username </label>
<input type="text" class="form-control" id="newusername">
</div>
<div class="form-group">
<label> Password </label>
<input type="password" class="form-control" id="newpassword">
</div>
<div class="form-group">
<label> Your club </label>
<input type="text" class="form-control" id="newclub">
</div>
<input type="button" id="btn-reg" class="btn btn-success" value="Sign up!">
</form>
Script
// -----------------Registration of new user----------------------
console.log('Script loaded...');
// Calling for the method - reg
$("#btn-reg").on("click", reg);
function reg(e) {
e.preventDefault();
console.log('Klick, klick...');
// Declaring variables
var newusername=$("#newusername").val();
var newpassword=$("#newpassword").val();
var newclub=$("#newclub").val();
$.post('classCalling.php', {
newusername: newusername,
newpassword: newpassword,
newclub: newclub
},
function(data){
console.log(data);
});
}
PHP
// Creating instance of the class userClass.php
var_dump($_POST);
if(isset($_POST['newusername'])){
// Defining variables
$newusername = $_POST['newusername'];
$newpassword = $_POST['newpassword'];
$newclub = $_POST['newclub'];
// Password hash
$hashpassword = sha1($newpassword);
$user = new User();
$user->newUsers($newusername, $hashpassword, $newclub);
} else {
}?>
OOP
// >>>>>>>>>>>>>>>> Function for saving new user to database
public function newUsers($newusername, $hashpassword, $newclub) {
// Using prepared statement to prevent mysql injections.
$stmt = $this->db->prepare("INSERT INTO users(username, password, club)VALUES(?, ?, ?);");
$stmt->bind_param("sss", $newusername, $hashpassword, $newclub);
if($stmt->execute()) {
echo "<h3 class='usercreated'>Created</h3>";
} else {
echo "<h3 class='usercreated'> Failed </h3>";
}
}
Just noticed that you are using function to create a new user, my bad again
if(isset($_POST['newusername'])){
// Defining variables
$newusername = $_POST['newusername'];
$newpassword = $_POST['newpassword'];
$newclub = $_POST['newclub'];
// Password hash
$hashpassword = sha1($newpassword);
$user = new User();
$status = $user->newUsers($newusername, $hashpassword, $newclub);
if($status) {
echo json_encode(array("status" : "success"));
}else {
echo json_encode(array("status" : "failed"));
}
}
Make a return from this function
public function newUsers($newusername, $hashpassword, $newclub) {
// Using prepared statement to prevent mysql injections.
$stmt = $this->db->prepare("INSERT INTO users(username, password, club)VALUES(?, ?, ?);");
$stmt->bind_param("sss", $newusername, $hashpassword, $newclub);
if($stmt->execute()) {
return true;
}else {
return false
}
}
this will be the same
$.post('classCalling.php', {
newusername: newusername,
newpassword: newpassword,
newclub: newclub
},
function(data){
var object = JSON.parse(data);
alert(object.status);
// or you can add if else by using the status
});
}
You could just echo the script tag.
if($stmt->execute()) {
echo "<h3 class='usercreated'>Created</h3>";
echo "<script type="text/javascript">";
echo "alert("Hello World!")";
echo "</script>";
} else {
echo "<h3 class='usercreated'> Failed </h3>";
echo "<script type="text/javascript">";
echo "alert("Hello World!")";
echo "</script>";
}
}
For the Script block.
var posting = $.post('classCalling.php', {
newusername: newusername,
newpassword: newpassword,
newclub: newclub
});
posting.done(function( data ) {
alert( "Data Loaded Ok");
});
posting.fail(function( data ) {
alert( "Error loading data");
});
Hope this helps you.
The purpose is to display a DIV when you click on a button and then display text inside that DIV that comes from my database. Thing is that data in databse changes, so text inside that div also. I would need a setInterval... with AJAX
I'm new in javascript and don't know the good way to go...
HTML:
<div onClick="showDiv();"> click </div>
<div style="display: none;" id="div">
Info from database:
<span style="display: hidden;" id="data1"> DATA 1 </span>
<span style="display: hidden;" id="data2"> DATA 2 </span>
</div>
javascript:
function showDiv()
{
document.querySelector("#div").style.display = "block";
setInterval(function () {getData()}, 1000);
}
function getData()
{
$.post(
'process.php',
{
},
function(data){
if(data == '1'){
document.querySelector("#data1").style.display = "inline";
}
else if(data == '2'){
document.querySelector("#data2").style.display = "inline";
}
},
'text'
);
return false;
}
//don't know how to just take data from database without sending by POST or GET.
php:
<?php
SELECT x FROM database
if(x == 1)
{echo '1';}
else if(x == 2)
{echo '2';}
?>
Get data using AJAX : Learn here. Your code to setInterval() is correct or you can do this : setInterval(getData,1000);
Display data in spans :
document.getElementById("data1").innerHTML = "your content from database";
document.getElementById("data2").innerHTML = "your content from database";
You're not giving a lot of info so I will give you a basic example of getting data from a mySQL database with jQuery, Ajax and PHP.
First you need to include jQuery to the head of your document
<script src="http://code.jquery.com/jquery-latest.js"></script>
And then use Ajax
function showDiv(){
document.getElementById("div").style.display = "";
setInterval(function (){ getData('something'); }, 1000);
}
jQuery.noConflict();
jQuery(document).ready(function($){
getData = function(variable){
var postVar = variable;
var postVar2 = "exemple";
$.ajax({
type: "POST",
url: "php/file.php",
data: 'variable=' + postVar + "&" +
'variable2=' + postVar2,
success: function(data){
data = $.trim(data);
var dataSplit = data.split("++==09s27d8fd350--b7d32n0-97bn235==++");
if(dataSplit[0] == "1"){
document.getElementById("data1").innerHTML = dataSplit[1];
}
if(dataSplit[0] == "2"){
document.getElementById("data2").innerHTML = dataSplit[1];
}
}
});
}
});
Finally, you need to create an external php file (in this example "file.php" in the folder "php") to get the data from your database with mysqli
<?php
// to prevent error, I check if the post variable is set and
// if it's not only full of spaces
if(isset($_POST['variable']) && preg_replace("/\s+/", "", $_POST['variable']) != ""){
$con = mysqli_connect("hostname", "username", "password", "database_name");
$query = mysqli_query($con, "SELECT * FROM `table_name` WHERE `column_name` = '".$_POST['variable']."'");
$results = array(); $row = 0;
while($info = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$results[$row] = array();
$results[$row]['column_name1'] = $info['column_name1'];
$results[$row]['column_name2'] = $info['column_name2'];
$row++;
}
foreach($results as $result => $data){
echo "1" . "++==09s27d8fd350--b7d32n0-97bn235==++" .
'<div>'.$data['column_name1'].'</div>'.
'<div>'.$data['column_name2'].'</div>';
}
}
?>
Hope it helps!
as title, I am a beginner about website design.
Please never mind if I ask a stupid question.
while i send the form, it didnt work.
here is html:
<form id="form1" name="form1" action="toSQL.php" method="POST" accept-charset="utf-8">
<input type="text" name="Cliname" id="textfield" maxlength = "10" />
<textarea name="message" id="message" rows="3" maxlength = "20" ></textarea>
<input type="submit" value="submit" id="submit" />
</form>
<div class="alert"></div>
and here is js:
<script type="text/javascript">
$(document).ready(function() {
var form = $(this) ;
var submited = $('#submit') ;
var alerted = $('.alert') ;
form.on( 'submit', this, (function(event) {
event.preventDefault();
if ( $.trim($form.find('input[name="Cliname"]').val()) == "" || $.trim($form.find('input[name="message"]').val()) == "" ) {
alert( "please enter!!" ) ;
return ;
}
else {
$.ajax({
url: 'toSQL.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alerted.fadeOut();
},
success: function(data) {
alerted.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
},
error: function(e) {
console.log(e)
}
});
}
}));
});
</script>
server side php:
<?php
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){
if (isset($_POST['Cliname']) AND isset($_POST['message'])) {
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
if (send($name, $message)) {
echo 'Message sent!';
} else {
echo 'Message couldn\'t sent!';
}
}
else {
echo 'All Fields are required';
}
return;
}
function send( $name, $message ) {
$time = date("Y-m-d H:i:s");
$mysqlConnection=mysql_connect("localhost", 'root', '') or die("connect error!");
mysql_select_db('test') or die ("db error!");
$queryStr="INSERT INTO fortest (time, message, name)
VALUES ( '$time', '$message', '$name')";
mysql_query($queryStr,$mysqlConnection) or die(mysql_error());
return true ;
}
?>
here is the website i reference : http://www.w3bees.com/2013/08/submit-form-without-page-refresh-with.html
Did i miss something?
As a couple people have mentioned already, you are trying to serialize your entire dom object, which isn't going to work. Change it to var form = $("#form1") and it should work.
I recommend you open the webpage in chrome dev tools and click the network tab, click preserve log and then submit the form. When it is submitted you'll see the full headers that were sent to the server and can verify it works correctly to help narrow down the problem