Delete data from database without reloading the page - javascript

I want to delete data from database without refreshing the page. My code is working but after deleteing a product needs to refresh the page. I want something like this
Here is my js code:
<script>
$(document).on('click', '.delete-it', function() {
var id = $(this).attr('delete-id');
bootbox.confirm("Are you sure?", function(result) {
if (result) {
$.ajax({
type: "POST",
async: false,
url: "delete_product.php",
data: {
object_id: id
},
dataType: 'json',
success: function(data) {
location.reload();
}
});
}
});
return false;
});
</script>
and the delete_product php code:
<?php
// check if value was posted
if($_POST){
// get database connection
$database = new Database();
$db = $database->getConnection();
// prepare product object
$product = new Product($db);
// set product id to be deleted
$product->id = $_POST['object_id'];
// delete the product
if($product->delete()){
echo "Object was deleted.";
}
// if unable to delete the product
else{
echo "Unable to delete object.";
}
}
?>
Please show me a way to make it!

I see no place where the you're targeting something in the page, but this is what I would use:
<script>
function swapContent(href, url_data, target) {
$.ajax({
type: 'GET',
cache: false,
url: href+'?' + url_data, //add a variable to the URL that will carry the value in your i counter through to the PHP page so it know's if this is new or additional data
success: function (data) { // this param name was confusing, I have changed it to the "normal" name to make it clear that it contains the data returned from the request
//load more data to "target" value div
target.innerHTML = (data); // as above, data holds the result of the request, so all the data returned from your results.php file are in this param but please see below
}
})
}
$(document).on('click', '.delete-it', function() {
var id = $(this).attr('delete-id');
bootbox.confirm("Are you sure?", function(result) {
if (result) {
swapContent(base_url, url_data, target) //set variables
}
});
return false;
});
</script>
note: because of how much ajax I use, I keep an ajax function by itself

Related

Display js code in php method ajax

I run the PHP code by ajax method with the click of a button.
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: {
name: name,
time: time
}
});
});
I would like the file.php to be able to run the js code, for example:
if ($time < $_SESSION['time']) {
[...]
}
else {
echo '<script>alert("lol");</script>';
}
And that when the button .btn_ranking on the page is pressed, an 'lol' alert will be displayed. If it is possible?
you can echo a response to the AJAX call and then run the JS according to the response..
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { name: name, time: time },
success: function (data) {
if(data==1){
//do this
}else if(data==2){
//do that
alert('LOOL');
}
}
});
});
PHP CODE:
if ($time < $_SESSION['time']) {
echo '1';
}
else {
echo '2';
}
You can't said to a server-side script to use javascript.
What you have to do is to handle the return of you'r ajax and ask to you'r front-side script to alert it. Something like that :
file.php :
if ($time < $_SESSION['time']) {
[...]
}
else {
echo 'lol';
exit();
}
Front-side :
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: {
name: name,
time: time
},
success : function(data) {
alert(data);
}
});
});
When you used ajax for call php script, everything will be print in the return of the php code will be return to the HTTP repsonse and so be on the Ajax return function as params.
Ok .. First change your js code to handle answer from php script:
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { name: name, time: time }
success: function(data) {
console.log(data);
// check if it is true/false, show up alert
}
});
});
Then change php script (file.php), something like that:
$response = [];
if ($time < $_SESSION['time']) {
$response['data'] = false;
}
else {
$response['data'] = true;
}
return json_encode($response);
Something like that is the idea :) When u send ajax with POST method get variables from there, not from $_SESSION :)
U can see good example here

Ajax change php variable

I've got this variable $type and I want it to be month or year.
It should be changed by pressing a div.
I've tried creating an onclick event with an ajax call.
The ajax call and the variable are in the same script (index.php)
Inside the onclick function:
var curr_class = $(this).attr('class');
$.ajax({
type: "POST",
url: "index.php",
data: {
type: curr_class
},
dataType: 'text',
success: function(data) {
// Test what is returned from the server
alert(data);
}
});
But the alert returns the whole html page.
When I console.log the data (create a var data = { type:curr_class }) and console.log *that data* it returnstype = month` (which is correct)
while I just want it to return month or year
So on top of the page I can call
if(empty($_POST['type'])){
$type = 'month';
} else {
$type = $_POST['type'];
}
and change the PHP variable so I can use it in the rest of my script.
But how can I accomplish this?
With kind regards,
as you are sending request to the same page so as a result full page is return .You will have to send it to another page and from that page return the type variable
if(empty($_POST['type'])){
$type = 'month';
} else {
$type = $_POST['type'];
echo $type;
keep this code in separate file and make an ajax call to that page
//Try This It's Work
Get Value
Get Value
$(".btn-my").click(function(){
var curr_class = $(this).data('title');
$.ajax({
type: "POST",
url: "index.php",
data: {
type: curr_class
},
dataType: 'text',
success: function(data) {
// Test what is returned from the server
alert(data);
}
});
});

Security measures for AJAX-PHP scripts

For a link like this
DELETE
i am using this ajax call
$(function() {
$(".delete_msgs").click(function() {
var msgid = $(this).attr("id");
var dataString4 = 'msgid=' + msgid;
$('a#'+msgid).html('<img src="img/loader.gif" class="loading" />');
$.ajax({
type: "POST",
url: "del_msg.php",
data: dataString4,
cache: false,
success: function(data){
if (data == 0) {
//alert('Sent!');
} else {
$('a#'+msgid).html(data);
$('.viewmessage'+msgid).hide();
}
}
});
return false;
});
});
The del_msg.php file contains that code:
if(isset($_POST)) {
$msgid = $_POST['msgid'];
$delmsg = mysql_query("DELETE FROM messages
WHERE id = $msgid") or die(mysql_error());
echo 'Message sent!';
} else {
echo 0;
}
My big question is, how can i protect my send throught AJAX function? Anyone can change the id of the #a element and, consequently, can delete any row from my database.
Is there a more secure way to call php with ajax, or at least, to hide my important variables sent via ajax?

ajax reporting success but nothing changing on the database

First, thanks for you reading. Here is my code
scripts/complete_backorder.php
<?php
if(!isset($_GET['order_id'])) {
exit();
} else {
$db = new PDO("CONNECTION INFO");
$order = $db->prepare("UPDATE `scs_order` SET `order_complete`= 1 WHERE `order_id` = :var");
$order->bindValue( ':var',$_GET['order_id'] );
if ( $order->execute() ) {
echo "DONE";
};
};
?>
js/tabs.js
/*
[#]===============================================================================[#]
MODAL: "complete_backorder_Modal"
USAGE: modal to confirm whether or not user want to complete a backorder.
[#]===============================================================================[#]
*/
$(function(){
$(" .remove_record ").click(function( event ){
event.preventDefault();
var rows = $(this).parent().parent().parent().parent().find("tr:last").index() + 1;
var order = $(this).attr("href");
var dataString = 'order_id='+order;
$( '#complete_backorder_Modal' ).modal({
keyboard: false,
backdrop: 'static'
});
$( '#complete_backorder_Modal #modal-yes' ).click(function(e){
$.ajax({
type: "POST",
url: "../scripts/complete_backorder.php",
data: dataString,
success: function(data){
alert("Settings has been updated successfully.");
}
});
});
});
});
so i know the php code is working as ive tested it over and over manually. but when i click on the ".remove_record" button the modal shows and i click the yes button in the modal the alert boxes shows up to say it was successful but when i look at the database nothing has changed.
any ideas?
Your SQL is never running becuase there are no $_GET variables, your are using $_POST But even if you did you are not passing through order_id correctly. Change:
var postData = {'order_id ' : order}; // instead of var dataString = 'order_id='+order;
And
$.ajax({
type: "POST",
url: "../scripts/complete_backorder.php",
data: postData, // instead of dataString
success: function(data){
alert("Settings has been updated successfully.");
}
});
In the PHP change:
if(!isset($_POST['order_id'])) { // Insetad of $_GET
And
$order->bindValue( ':var',$_POST['order_id'] );

how to get ajax return id in hidden variable....on request page

I need to get last insert id from controller to ajax success function......
I want to customize product and when user press add to cart ajax is executed and design is going to insert on database....
And after inserting in database i m getting last insert id.....on insert...
but need last insert id....when user press on add to cart button in hidden field...
here is my Ajax code.
$('#store').click(function(){
$.ajax({
type: "POST",
url: ajax_url_store,
data: {action: 'store', views: JSON.stringify(thsirtDesigner.getProduct()) },
success: function(data) {
if(parseInt(data) > 0) {
//successfully added..here i am getting last insert id...
// and i want to pass that in hidden variable.....
// on view page.....
}
else {
document.getElementById('succes-message').innerHTML = 'You Design has not Been Saved';
}
},
error: function() {
//alert('some error has occured...');
},
start: function() {
//alert('ajax has been started...');
}
});
});
my CI controller
public function saveData(){
if($this->input->post('action') == 'store') {
$views = $this->input->post('views');
$id = $this->product_model->save($views);
$data = array('cust_id'=>$id);
$this->session->set_userdata($data);
if($id !=''){
header('Content-Type: application/json');
echo json_encode($id);
}
}
}
$this->db->insert_id() returns the last id.
After your insertion operation in model, use following code
$this->db->insert_id();
this will give you id where last insert done.
Documentation

Categories