Won't insert in mysql database because of script - javascript

I have a script that asks if I'm sure to add new data. My php is okay because when I want to insert data with my script disabled it inserts normally. But when my script is not disabled it will not insert anymore... I don't know why i don't get any errors (probably because there are 2 different files).
My Script
$(document).on("click", ".btnAddSubcat", function(e) {
event.preventDefault();
var subcatid = $('.CatEdit-select').val();
var subcatvalue = $('.subCat').val();
var subcatprocedure = $('.subProcedure').val();
var url = "../service/functions/postActions.php";
swal({
title: 'Add a new sub-category?',
text: "Are you sure to Add this sub-category?",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, Add it!'
}).then(function () {
$.ajax({
type: 'POST',
url : url,
data: {
'cat-select': subcatid,
'subCat': subcatvalue,
'Procedure': subcatprocedure
},
success: function (data) {
swal({
title: 'Add!',
text: "You Add a sub-category!",
type: 'success',
confirmButtonColor: '#3085d6',
confirmButtonText: 'OK'
}).then(function () {
window.location.reload();
})
}
});
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
if you need my php insert function or something else let me know
EDIT
My PHP function
function AddSubCat() {
$Catid = $_POST['cat-select'];
$Subnaam = $_POST['subCat'];
$procedure = $_POST['Procedure'];
include '../../../include/dbConnection/dbcon.php';
//set update query ready for database, with info from the Ajax POST method for update.
$sqladdSubCat = 'INSERT INTO `*****`(`naam`,`Werkwijze`) VALUES ("'.$Subnaam.'","'.$procedure.'")';
//if query is done right then 'Record updated successfully'
if (mysqli_query($conn, $sqladdSubCat))
{
//get new colourId
$newUpload_id = mysqli_insert_id($conn);
//set update query hw_algoritmes thee cat id that may have change.
$sqlalgotime = 'INSERT INTO `*****`(`categorie_id`, `subcategorie_id`) VALUES ("'.$Catid.'","'.$newUpload_id.'")';
//if query is done right then 'Record updated successfully'
if (mysqli_query($conn, $sqlalgotime)) {
//check if there is a new front image add
if ($_FILES['HWVideo']['name'] == "") {
//Empty
} else {
uploadVideoHw($_FILES['HWVideo'], $newUpload_id);
}
} else {
echo "Error updating record: " . mysqli_error($conn);
}
header('Location: /cms/service/index.php');
} else {
echo "Error updating record: " . mysqli_error($conn);
// header('Location:../../Categorieen');
}
}

Related

after ajax call , the code after waiting for Json response could not be executed

I have used Django2 to develop a web app.
I frontend, after the ajax call, the network tab on chrome dev does show the 200 status code, but I did not see any alert box. my app stuck at this line for waiting json: const msg_json = await response.json(); , the following alert does not execute
async function myFunction() {
Swal.fire({
title: '',
text: "Do you want to confirm entries?",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes',
cancelButtonText: 'No'
}).then(
async(result) => {
if (result.value) {
$.ajax({
url: '/content_checklist_name_url/',
type: 'POST',
data: $(this).serialize(),
cache: false,
success: function(data) {
var comment_html = "<div id='myform_1'>" + data['log_info'] + "</div>";
$('#myform_1').remove();
$('#ajax_data').prepend(comment_html);
$('#myform_input').val('');
},
});
const response = await fetch({ % url 'bms:content_checklist_name_url' %
});
const msg_json = await response.json();
alert(msg_json.responseText)
let a = msg_json;
if (a === "Duplicate Entry. This Course Code already exists.") {
Swal.fire({
title: '',
text: 'Duplicate Entry. This Course Code already exists.',
type: 'error',
})
} else {
Swal.fire({
title: '',
text: 'Entries have been saved.',
type: 'success',
})
}
// },
// failure: function(data)
// {
// alert('Got an error dude');
// }
// });
} else {
window.stop();
}
}
)
}
<form id="myform" action="/content_checklist_name_url/" method="POST">
...
</form>
<button class="button" onclick="myFunction()" type="button" id="submit">SUBMIT</button>
backend view.py:
#csrf_exempt
def content_checklist_name_url(request):
if request.method == 'POST':
...
msg = "success"
obj = {"msg": msg}
context = {'msg_json': json.dumps(obj)}
return render(request, 'bms/main.html',context=context)
I got the error in the console: VM355:4 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 3
no alert box shows.
How could I check where goes wrong?
Your view is waiting for a POST and you are sending a GET so this branch won’t be executed. Also, submitting a form by html, make the browser change pages so as the form is submitted, the ajax won’t be called.

ajax call keeps failing despite success on server site

I'm having some trouble with an ajax call.
When it's a success in one part, it's failing in the return.
Basically I have a PHP function to delete one ID in database.
The ajax call call the function and the PHP code deletes that row in table, but ajax call keeps faling. If I try to delete it again (the ID doesn't exist anymore), the ajax call shows as success with proper json to work.
function DeleteRole(e, id, role) {
Swal.fire({
title: 'Are you sure?',
text: "Do you want to delete Role " + role + "?",
icon: 'question',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes',
showLoaderOnConfirm: true,
confirmButtonClass: 'btn btn-primary',
buttonsStyling: false,
showCancelButton: true,
cancelButtonClass: "btn btn-danger ml-1",
preConfirm: function () {
$.ajax({
url: 'caller.php',
data: {
dados: JSON.stringify(id),
caller: 'DeleteRole',
dataType: 'json'
},
type: 'POST',
})
.done(function (response) {
console.log("done");
console.log(response);
})
.fail(function (response) {
console.log("fail");
console.log(response);
})
},
allowOutsideClick: function () {
!Swal.isLoading()
}
})
};
PHP Function:
function DeleteRole($mysqli){
header('Content-Type: application/json; charset=UTF-8');
$response = array();
$response["status"] = "error";
$response["message"] = "";
if(isset($_POST['dados'])){
$args["id"] = validate($mysqli, $_POST["dados"]);
if($stmt = $mysqli->prepare("SELECT * FROM roles WHERE id = ? LIMIT 1")){
$stmt->bind_param("i", $args["id"]);
$stmt->execute() or trigger_error($stmt->error, E_USER_ERROR);
($stmt_result = $stmt->get_result()) or trigger_error($stmt->error, E_USER_ERROR);
if ($stmt_result->num_rows>0) {
$row_data = $stmt_result->fetch_assoc();
$role_name = $row_data['role_name'];
if(crud_delete($mysqli, 'roles', $args) == true){
$response["status"] = "success";
$response["message"] = "Role ".$role_name." deleted with success";
echo json_encode($response);
}else{
$response["status"] = "error";
$response["message"] = "There was a problem deleting role ".$role_name;
echo json_encode($response);
}
}else{
$response["message"] = "ID does not exists.";
echo json_encode($response);
}
}else{
$response["message"] = "Something wrong happened.";
echo json_encode($response);
}
}else{
$response["message"] = "No data given to work.";
echo json_encode($response);
}
}
So, when I first call the function for first time do delete a specific ID, it deletes from database and should ouptut:
$response["status"] = "success";
$response["message"] = "Role ".$role_name." deleted with success";
echo json_encode($response);
Instead of that, it goes to fail part of my ajax call. Any clues?
EDIT:
First time to delete, I have an answer this way and appears in .fail of ajax call:
Array
(
[0] => id
)
{"status":"success","message":"Role Administrator deleted with success"}
If I do it a second time (the ID was already deleted first time) I have the following response (and goes to .done of ajax request):
{"status":"error","message":"ID does not exists."}

data submit even when cancel button is pressed in sweetalert2

I was able to send data when the confirm button pressed.
however, when the cancel button pressed sweetalert2 shows as it successfully inserted the data.
back-end shows as it a empty string.(in the database table)
how to validate when I pressed the cancel button, not to send data to the back-end.
Javascript function
function inputPass(complaintID) { // complaint id pass is ok.
swal({
text: 'Input comment message',
input: 'textarea',
showCancelButton: true,
}).then(function(sample_text) {
console.log(sample_text);
if(sample_text === '') { // problem is here.
swal({
type: 'warning',
html: 'cannot proceed without input'
});
} else {
console.log(sample_text);
$.ajax({
type: "POST",
url: "../ajax/ajax_active_deact.php?type=complaint_answered",
data: {complaintID: complaintID, sampleText: sample_text}
}).done(function (res) {
if(!res) {
swal({
type: 'error',
html: 'insert the valid text'
});
} else {
swal({
title: 'done',
text: 'all right',
type: 'success',
allowOutsideClick: false,
confirmButtonText: 'Ok'
});
}
});
}
});
}
php ajax code
function complaint_answered() {
include_once('../backend/ConsumerComplaint.php');
$con_complaint = new ConsumerComplaint();
$res = $con_complaint>mark_as_answered($_POST['complaintID'],$_POST['sampleText']);
echo $res;
}
This is my class function
function mark_as_answered($id, $comment) {
//var_dump($comment);
$val = $comment['value']; // $comment is a associative array, with the key of 'value'
$sql = "UPDATE c_consumer_complaint SET `status` = 'answered', `update` = '$val'
WHERE complaint_id = '$id' ";
$res = $this->conn->query($sql);
return $res;
}
image of when i pressed cancel button in network panel in chrome
image of the console
image of the post data in chrome
I'm new to development and can't get around how to solve this issue.
please can anyone give me what I'm doing wrong here.
Thnks!
You only get the result.value if the user clicked on Ok so you can check if there is a value and if it is empty you show your error message. If there is no value nothing happens.
Snippet:
swal({
text: 'Input comment message',
input: 'textarea',
showCancelButton: true,
}).then(function(result) {
if(result.value) {
$.ajax({
type: "POST",
url: "../ajax/ajax_active_deact.php?type=complaint_answered",
data: {complaintID: complaintID, sampleText: result.value}
}).done(function (res) {
if(!res) {
swal({
type: 'error',
html: 'insert the valid text'
});
} else {
swal({
title: 'done',
text: 'all right',
type: 'success',
allowOutsideClick: false,
confirmButtonText: 'Ok'
});
}
});
} else if (result.value === "") {
swal({
type: 'warning',
html: 'cannot proceed without input'
});
}
});
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#7.28.7/dist/sweetalert2.all.min.js"></script>
Your Class:
In your php ajax code you are passing the $_POST['sampleText'] which is not an array but a string so $comment['value'] will not contain the text.
function mark_as_answered($id, $comment) {
//var_dump($comment);
$val = $comment;
$sql = "UPDATE c_consumer_complaint SET `status` = 'answered', `update` = '$val'
WHERE complaint_id = '$id' ";
$res = $this->conn->query($sql);
return $res;
}
PS: Please educate yourself on SQL-Injection so people cant inject harmful code into your SQL-Queries.
Looks like sample text is always set to an array. I would try changing the if statement
if(sample_text === '') { // problem is here.
swal({
type: 'warning',
html: 'cannot proceed without input'
});
} else {
console.log(sample_text);
to something like
if(sample_text['dismiss'] == 'cancel') { // problem is here.
swal({
type: 'warning',
html: 'cannot proceed without input'
});
} else {
console.log(sample_text);

confirm delete swal not functioning

The swal stays that way infinetly
I am new to javascript. I am using swal to confirm delete of an order. the order is deleted correctly from the database and when I reload the page, I find the order deleted but the thing is that the page is not reloaded automatically.
echo ($paid == 0) ? "<td><p data-placement='top' data-toggle='tooltip' title='Delete'><a href='#' class='btn btn-danger btn-xs delete-confirm' id='" . $orderId . "'><span class='glyphicon glyphicon-trash'></span></p></td>" : "<td></td>";
<script type="text/javascript">
$('.delete-confirm').on('click', function() {
var orderId = $(this).attr('id');
console.log(orderId);
swal({
title: "Are you sure?",
text: "If you delete this post all associated comments also deleted permanently.",
type: "warning",
showCancelButton: true,
closeOnConfirm: false,
showLoaderOnConfirm: true,
confirmButtonClass: "btn-danger",
confirmButtonText: "Yes, delete it!",
}, function() {
setTimeout(function() {
$.post("delete.php", {
id: orderId
},
function(data, status) {
swal({
title: "Deleted!",
text: "Your post has been deleted.",
type: "success"
},
function() {
location.reload();
}
);
}
);
}, 50);
});
});
</script>
<script src="js/sweetalert.min.js"></script>
and the delete.php is here
<?php
session_start();
include('config.php');
if(!isset($_SESSION['username'])){
header("location: login.php");
}
$orderId = $_POST['id'];
$qry = "DELETE FROM orders WHERE order_id ='$orderId'";
$result=mysqli_query($connection,$qry);
?>
The order is deleted successfully from the database and the swal is not closed even if i wait infinite time and the page is not getting reloaded.
Please help me.
Which version of swal do you use?
Why are you using setTimeout, what are you waiting for?
I also use swal as deletion confirmation in the following way:
swal({
title: "Are you sure?",
text: "If you delete this post all associated comments also deleted permanently.",
type: 'warning',
showCancelButton: true,
showCloseButton: true,
reverseButtons: true,
focusCancel: true,
confirmButtonText: "Yes, delete it!",
cancelButtonText: "cancel"
})
.then( function (willDelete) {
if (willDelete) {
$.post( "delete.php",
{ id: orderId },
function(data, status) {
swal({
title: "Deleted!",
text: "Your post has been deleted.",
type: "success"
};
}
)
} else {
toastr.info(Texxt('delet canceled), Texxt('Abbruch') + '.', {
closeButton: true,
progressBar: true,
});
}
}).catch(swal.noop);

Remove an item from User's cart after 30 minutes with PHP and Javascript

I have a typical ecommerce site with a shopping cart and I want to automatically remove an item from a user's cart after 30 minutes (or some other defined time period). I'm really unsure of the best way to accomplish this. I know that there is the php sleep() function, but it seems that would be an undesirable method for waiting 30 minutes or more from a performance standpoint. I tried setting a timeout in my javascript using setTimeout() and had it call a function that would send an Ajax call to removefromcart.php along with the item's id. However, I was unsuccessful at getting that to fire at all. Below is the code used to add the item to the cart:
session_start();
require_once('../config.php');
try{
$itemId = array_key_exists('itemId', $_POST) ? $_POST['itemId'] : null;
if(!is_null($itemId)){
if(!in_array($itemId, $_SESSION['cart'])){
$i = count($_SESSION['cart']);
$_SESSION['cart'][$i] = $itemId;
$sql = "UPDATE
titems
SET
intInactive = 1
WHERE
intItemId = ? ";
$stmt = $conn->prepare($sql);
$stmt->execute([$itemId]);
echo ("Success");
$_SESSION['cart_count'] = count($_SESSION['cart']);
}
}
} catch(Exception $ex) {
error_log($ex->getMessage());
logError($conn, 'ADD TO CART FAILED. Error: '. $ex->getMessage());
echo("Fail");
}
Here is the Javascript used to fire this event:
// Add Item to Cart
$('button.addtocart').on('click', function(){
var btnId = this.id;
var itemId = btnId.split('-')[1];
$.ajax({
method: 'POST',
url: 'Backend/addtocart.php',
data: {itemId: itemId},
success: function(data){
if(data == 'Success'){
swal({
title: "Item Added!",
text: "my message",
type: "success",
confirmButtonText: "OK"
},
function(isConfirm){
if (isConfirm) {
$("#row-"+itemId).fadeOut("slow");
location.reload();
}
});
} else {
swal({
title: "Error!",
text: "Something Went Wrong! Please Try Again.",
type: "error",
confirmButtonText: "OK"
});
}
}
})
})
Javascript for removing an item when the user clicks "Remove From Cart", I'm hoping to use a similar Ajax call to accomplish my auto-removal:
// Remove Item From Cart
$('#CartTable :button').on('click', function(){
var btnId = this.id;
var itemId = btnId.split('-')[1];
swal({
title: "Remove?",
text: "Are you sure you want to remove this item from your cart?",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes, remove it!",
cancelButtonText: "No, keep it!",
closeOnConfirm: false
},
function(isConfirm){
if (isConfirm) {
swal("Removed!", "That item has been removed from your cart!", "success");
location.reload();
$.ajax({
method: 'POST',
url: 'Backend/removefromcart.php',
data: {itemId: itemId},
success: function(data){
if(data == 'Success'){
swal({
title: "Success!",
text: "Item Successfully Removed From Cart",
type: "success",
confirmButtonText: "OK"
});
$("#row-"+itemId).fadeOut("slow");
} else {
swal({
title: "Error!",
text: "Something Went Wrong! Please Try Again.",
type: "error",
confirmButtonText: "OK"
});
}
}
})
} else {
swal("Cancelled", "Too good to let go!", "error");
}
}
);
})
And finally, here is the php used to actually remove the item from the cart:
session_start();
require_once('../config.php');
try{
$itemId = array_key_exists('itemId', $_POST) ? $_POST['itemId'] : null;
if(!is_null($itemId)){
$i = array_search($itemId, $_SESSION['cart']);
unset($_SESSION['cart'][$i]);
$sql = "UPDATE
titems
SET
intInactive = 0
WHERE
intItemId = ? ";
$stmt = $conn->prepare($sql);
$stmt->execute([$itemId]);
echo ("Success");
$_SESSION['cart_count'] = count($_SESSION['cart']);
}
} catch(Exception $ex) {
error_log($ex->getMessage());
logError($conn, 'REMOVE ITEM FROM CART FAILED. Error: '. $ex->getMessage());
echo("Fail");
}
I'm really hoping to utilize the code that I already have in place to accomplish this task. I hope someone can help me out! Thanks.

Categories