Using Javascript and PHP to delete an item out of database - javascript

I am using an anchor tag to run the JS function confirm(), and if the user clicks okay it adds "deltopic=id", and use the $_GET method to get 'deltopic' to delete that specific item, but it seems to not be finding the $_GET['deltopic']
<script language="JavaScript" type="text>
function deltopic(title, tid) {
if(confirm("Are you sure you want to delete '" + title + "'")){
window.location.href = "?viewtopic.php&deltopic=" + tid;
}
}
</script>
<?php
if(isset($_GET['deltopic'])){
if($_GET['deltopic'] !=='1'){
$query = "DELETE FROM `bkg`.`bkg_topics` WHERE `bkg_topics`.`topic_id` = :topicid";
$query_params = array(':topicid' => $_GET['deltopic']);
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
header('Location: index.php?forums&action=deleted');
exit;
} catch(PDOException $e) {
$error[] = "An error has occured. Please try again later.";
}
}
echo "deltopic is set";
}
I added the last echo just to see if its checking if deltopic isset, or if it was an error in my SQL that I was just not seeing. However I do not see "deltopic is set".
I am not sure what I am doing wrong and/or what I am forgetting. I have code similar to this, that does work, and double checked it closely.
EDIT: I saw the error I was doing in my 'window.location.href' string, where I was adding .php to the end of ?viewtopic, making it ?viewtopic.php. Removing the .php fixed my issue as well.

window.location.href = "?viewtopic.php&deltopic=" + tid;
will result in URL where "viewtopic.php" is a part of URL QUERY. Perhaps you want it in the PATH:
window.location.href = "viewtopic.php?deltopic=" + tid;

Related

Cannot Redirect when Logging in an Account using javascript and php

Currently, I am developing a website, for my own purposes. I am a beginner at web developing so please understand me if I am not getting this correct. Please Help.
I have a code for javascript when clicking an html element button
for logging in. see code below:
$(document).ready(function(){
$("#login").click(function(){
var username = document.getElementById("username").value;
var pword = document.getElementById("password").value;
validateUser(username,pword);
});
});
function validateUser(user,pass){
var username =user;
var pword =pass;
var datasend = "username="+ username + "&password=" + pword;
$.ajax({
type:'POST',
url:'../bench/php/login.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
alert("Hello World"); //Trying to pop up
$('#username').val('');
$('#pword').val('');
}
});
}
I successfully triggered the button for the second time I try to click it, and the hello world message will pop out, but it cannot redirect the page if it was successfully logged in using an account in MySQL in WAMP server. Here is the code in PHP below:
<?php
// require("php/config.php");
include("config.php");
session_start();
if($_POST['username'] != '' && $_POST['password'] !='') {
// username and password sent from form
echo $myusername = mysqli_real_escape_string($db,$_POST['username']);
echo $mypassword = mysqli_real_escape_string($db,$_POST['password']);
//$sql = "SELECT user_id FROM user WHERE username = '$myusername' and password = '$mypassword'";
$sql = "SELECT * FROM user WHERE username = '$myusername' and password = '$mypassword'";
$result = mysqli_query($db,$sql);
$rows = mysqli_fetch_array($result);
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
session_regenerate_id();
$_SESSION['login_user'] = $myusername;
header("Location: index.html");
} else {
echo '<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>';
echo '<script type="text/javascript">';
echo 'setTimeout(function () { swal("Oops!","Your Account Credentials is Invalid, Please Try Again!","error");';
echo '}, 100);</script>';
}
}
?>
The problem is, the page does not redirect to the index.html even when the second click triggers the HELLO WORLD alert.
I don't know what I am doing wrong.
I don't why this is not working, I see the console, there is no error exist.
can someone help me with this? any help will much be appreciated. thanks and regards.
If you'd like to keep to using the AJAX setup you have at the moment (which is totally fine), what you'll need to do is to beef up the on-success function to read the returned results from your PHP.
A simple example
Instead of
header("Location: index.html");
write
echo "index.html";
exit;
and then add the following to your on-success function:
window.location.href = msg;
That will start to give you a flavour of how the relationship between an AJAX call and your PHP server should look like.
Next steps
Instead of having your AJAX return a string (index.html) have it
return an array of information, perhaps you want to welcome the user
with a personalised message?
You don't need to create a string (var datasend = "username="+ username + "&password=" + pword;) and feed that to your AJAX call, you can send an array.
Make sure your passwords are not stored in plain text on the server.
An ajax request will not follow the Location header of responses to redirect users.
You need to either redirect the user manually using JS in the success callback or change your form submission to use a classic HTML form
The first thing to make sure, PHP Redirect Header doesn't work when sending an Ajax Request.
So the solution to your problem is:
Change this part of your code in PHP file:
header("Location: index.html");
Into:
echo "Success";
exit();
And then in your Ajax Request Success Callback:
success:function(msg){
if (msg == 'Success') {
window.location = "/path/to/redirect";
}
}
Let me know if you have still confusion in this.

JS XMLHttpRequest to PHP Page to Execute MSSQL Query

I'm having an issue with an XMLHttpRequest. Basically, an HTML button makes a call to the deleteItem function, which then makes a call to the other function. Each of these two functions makes the XHR to a php page in order to remove tuples from two different database tables.
Here's the code (variables renamed to generics):
JS:
//remove first item from first table
function deleteItem() {
var conn = new XMLHttpRequest();
var query = "DELETE FROM MyTable WHERE ID = " + arrayOfObjects[i][0] + ";";
conn.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
deleteWorkflowProcess(arrayOfObjects[i][1], conn.responseText);
}
}
conn.open("GET","../../db_query/sql.php?q=" + query + "&p=DELETE", true);
conn.send();
}
//remove other items from other table
function deleteWorkflowProcess(s, r) {
var conn = new XMLHttpRequest();
var query = "DELETE FROM MyOtherTable WHERE FOREIGN_KEY = '" + s + "';";
if (r == "Deletion succeeded.") {
conn.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = conn.responseText;
alert(response);
window.location.replace("thissamepage.php");
}
}
conn.open("GET","../../db_query/sql.php?q=" + query + "&p=DELETE", true);
conn.send();
} else {
alert(r);
}
}
And here's the PHP page that it makes its two calls to:
//set up connection
$serverName = "SERVER\MSSQLINSTANCE";
$connectionInfo = array("Database"=>"DATABASE");
if (isset($_REQUEST['q'])) {
//establish connection
$conn = sqlsrv_connect($serverName, $connectionInfo);
if ($conn) {
//delete data
if ($_REQUEST['p'] == "DELETE") {
$result = sqlsrv_query($conn, $_REQUEST['q']);
if ($result) {
echo "Deletion succeeded.";
} else {
echo "Deletion failed: " . explode("]",sqlsrv_errors()[0]['message'])[3];
}
}
//do some other stuff based on 'p' value
//e.g. insert, update, etc.
}
sqlsrv_close($conn);
}
Here's what I know for sure:
The queries are phrased correctly and have no syntax errors.
The queries are calling the correct tables.
The first function works as it should by deleting the correct tuples from the first table.
The second function fails to delete anything from the second table
My question is: Why would the first function work correctly, but not the second?
Edits:
$_REQUEST['q'] is equal to the SQL Query, in this case "DELETE FROM MyOtherTable WHERE FOREIGN_KEY = 'asdf';"
$_REQUEST['p'] is the SQL command I'm using, in this case "DELETE".
sqlsrv_errors() returns nothing, because it's never being called. Near as I can tell, the query executes successfully, it's just that nothing happens. How I know this:
I know the XHR passes successfully, because the IE developer tools Network tab says this:
sql.php?q=SELECT * FROM MyOtherTable WHERE FOREIGN_KEY = 'asdf';&p=SELECT
The above GET gives a status 200 code.
If it had failed, JS would pop an alert that said "Deletion failed" and then would give the error. Instead, it pops an alert that says "Deletion succeeded", which only happens if the query succeeds, and thus sqlsrv_errors() is not called.
At the suggestion of Zhorov, I've put in sqlsrv_rows_affected() to determine exactly what is happening. It seems that the same number of affected rows is reported each time, regardless of how many rows match the condition in the SQL statement, or even if there are any rows to affect. This behavior only occures in Internet Explorer. In Chrome, both functions behave as they should.
Major Edit:
It looks like the scope of this problem has changed. By temporarily disabling caching in IE, I've been able to run both files as intended, with no errors. I'm not sure why IE decided to cache it, but the question now has become what can be done to the program to disable or work around the caching in IE? I can hardly expect every user to do this themselves.
I will suggest something, that may help you. Your DELETE statement executes, but does not delete rows, because there are no rows that match WHERE condition.
It is not clear what are your table definitions and what is the actual data (I suppose that 'asdf' is just an example), but I had similar test case and this was a solution.
Check the number of rows modified by the last statement executed with sqlsrv_rows_affected().
Just put one additional line in your script:
...
$result = sqlsrv_query($conn, $_REQUEST['q']);
if ($result) {
echo 'Rows affected: '.sqlsrv_rows_affected($result).'</br>';
echo "Deletion succeeded.";
} else {
echo "Deletion failed: " . explode("]",sqlsrv_errors()[0]['message'])[3];
}
...
So, if this statement is executed without errors and there are 0 rows affected, then one possible reason may be the fact, that FOREIGN_KEY column seems to be of type varchar/nvarchar/text.
If values in FOREIGN_KEY column contains any special characters, you have to consider the encoding issues when you pass this DELETE statement.
This also will explain the fact, that first function work correctly, while the second one fails.
First function deletes records with WHERE condition based on numeric column values, while the second function deletes records with WHERE condition based on text column values.
How to test the statement:
With SQL Server Management Studio and see the result and affected rows.
With your code, just put INSERT statement before the DELETE statement and check again sqlsrv_rows_affected().
...
$sql = "INSERT MyOtherTable (FOREIGN_KEY) VALUES ('asdf');";
$sql = $sql + $_REQUEST['q'];
$result = sqlsrv_query($conn, $sql);
if ($result) {
echo 'Rows affected: '.sqlsrv_rows_affected($result).'</br>';
echo "Deletion succeeded.";
} else {
echo "Deletion failed: " . explode("]",sqlsrv_errors()[0]['message'])[3];
}
...
Information about sqlsrv_rows_affected() can be found here.
Update:
User information from php.net:
If the sql contains INSERT, UPDATE or DELETE statements, the number of affected rows must be consumed.
The sqlsrv_query returns a sql cursor that must be read to finish the transaction, if the result is non false.
This same is valid for sqlsrv_execute. In this case the cursor must be also read using the prepared statement handle.
...
$result = sqlsrv_query($conn, $_REQUEST['q']);
if ($result) {
while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
}
echo 'Rows affected: '.sqlsrv_rows_affected($result).'</br>';
echo "Deletion succeeded.";
} else {
echo "Deletion failed: " . explode("]",sqlsrv_errors()[0]['message'])[3];
}
...
Another solution is to place SET NOCOUNT ON at the top of the sqlsrv statement and all called procedures, functions and triggers.
...
$sql = "SET NOCOUNT ON;";
$sql = $sql + $_REQUEST['q'];
$result = sqlsrv_query($conn, $sql);
if ($result) {
echo 'Rows affected: '.sqlsrv_rows_affected($result).'</br>';
echo "Deletion succeeded.";
} else {
echo "Deletion failed: " . explode("]",sqlsrv_errors()[0]['message'])[3];
}
...

Why my JS Alert box is not displaying?

I have the following code.
if(isset($_POST['save'])){
$descript = $_POST{'descript'};
$type = $_POST{'type'};
$c_max = $_POST{'c_max'};
$status = $_POST{'status'};
$queryInsert = "INSERT INTO `item_master` (`Item`, `Descript`, `Type`, `C_max`, `Exist`, `Status`) VALUES ('$item', '$descript', '$type', '$c_max', '0', '$status');";
try{
$resultInsert = mysqli_query($conn, $queryInsert);
if($resultInsert)
{
if(mysqli_affected_rows($conn) > 0)
{
echo '<script type="text/javascript">alert("Item Inserted");</script>';
header ("Location: Insertion.php");
}else{
echo '<script type="text/javascript">alert("The item could not be inserted ");</script>';
}
}
} catch (Exception $ex){
echo 'Error Delete '.$ex->getMessage();
}
}
My code works fine my query actually can insert new data in my DB but as the title said my "confirmation" alert is not displaying and I don't understand why. Before my if(isser($_POST['save'])) a JS function runs and ask me if I really want to insert a new data. So obviously I have the pop alerts activated in my browser. So... Im I doing somthing wrong?
Thanks for your comments!
you can use window.location(or other related options like:window.location.href).
if(mysqli_affected_rows($conn) > 0)
{
echo '<script type="text/javascript">alert("Item Inserted");window.location="Insertion.php";</script>';
}else{
echo '<script type="text/javascript">alert("The item could not be inserted ");</script>';
}

How to search for error?

I'm using "Bootstrap Editable" with "in line editing".
I'm printing a table with data from MySQL.
Now i´d like to be able to edit a cell and update my database with PHP.
The "in line edit" script works fine.
But the mysql update doesn't.
Now, when i turn on "php error mode" or tries to "JS alert" my variables in post php, to check if they holds data i can't see any errors or alerts on the front page.
How can i read the error codes or alerts?
This is my code:
HTML
echo "<td><a href='#' id='element_ant' data-type='text' data-pk='".$row['id']."' data-url='php/posts.php' data-title='Anteckning..'>".$row['element_ant']."</a></td>";
PHP
if($_POST['name']=='element_ant'){
$id=$_POST['pk'];
$element_ant=$_POST['value'];
//Prepare query
$query = "SELECT COUNT(*) as count FROM table WHERE id=$id";
try{
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch(PDOException $ex){
die("Failed to run query: " . $ex->getMessage());
}
//Result from query
$row = $stmt->fetch();
//Deside insert or update
if($row[0]==0){
$query = "INSERT INTO table(id,element_ant) VALUES(:id,:element_ant)";
}
else{
$query = "UPDATE table SET element_ant = :element_ant WHERE id = :id";
}
// Security measures
$query_params = array(':id' => $id,':element_ant' => $element_ant);
//Connect and execute
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){
die("Failed to run query: " . $ex->getMessage());
}
}
JS
$(document).ready( function () {
$('#element_ant').editable({
url : '../php/elements.php',
title : 'Enter comments'
});
});
1) The url attribute is duplicated, i.e you have declared it as data-url in your HTML and in your Js code as url:. Decide which one is right and use either, not both.
2) In your php, there is if($_POST['name']=='element_ant'); you have to set it in your editable HTML element as such:
<a href='#' id='element_ant' data-name="element_ant"
When the Editable object is being saved, the data-name will be passed as a POST parameter name.
For Client-Side Debugging: Firebug
For Server-Side Debugging: Xdebug
I think you can use some sort of logging framework , or you can write your own logging functions to log your error code on the file system.

Using javascript to ask if the user is sure they want to delete the data

I am trying to run a function that calls some Javascript to ask the question "Are you sure you want to delete this customer?" But my link to the java-script does not seem to work. All I get at the Java-script end is the word remove. It is supposed to ask if they are sure and if not return them back to the page they clicked on. If they are sure, then delete the data.
This script checks to make sure there is no other data connected to the customer's data. If there is they are not allowed to delete it. But if there is nothing attached they can delete it but I want to make sure that's what they want to do.
I think my problem is in my links but not sure.
function checkcustomeruse($custid,$pid,$name){{}
global $db;
$sql = "SELECT COUNT(*) from signings WHERE pid = ? AND custid = ?";
$stmt = $db->prepare($sql);
$stmt->bindParam(1, $pid, PDO::PARAM_INT);
$stmt->bindParam(2, $custid, PDO::PARAM_STR);
$stmt->execute();
$number_of_rows = $stmt->fetchColumn();
$number = $number_of_rows;
if($number == 0)
{
echo 'Remove';
}
else
{
$Message = 'You can not delete this customer because it has signings attached to it.';
header("Location: viewallcustomer.php?Message=" . urlencode($Message));
}
}
This is the javascript
function deleteAlert(custid,name){
var conBox = confirm("Are you sure you want to delete: " + name);
if(conBox){
location.href="formpross.php?processtp=deletecustomers&delete=yes&custid";
}else{
return;
}
}
can you try this:
function deleteAlert(custid,name){
var conBox = confirm("Are you sure you want to delete: " + name);
if(conBox){
location.href="formpross.php";
}
return conBox;
}
Try echoing out your Javascript function a little differently. The escaped single quotes turn into single quotes around the values we're sending into the javascript function.
echo 'Remove';
Also, we need to return false if the Javascript function results in cancelling the action.
function deleteAlert(custid,name){
var conBox = confirm("Are you sure you want to delete: " + name);
if(conBox){
location.href="formpross.php?processtp=deletecustomers&delete=yes&custid";
} else {
return false;
}
}

Categories