Security measures for AJAX-PHP scripts - javascript

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?

Related

How refresh particular div without reload whole page?

<div id="success_hold">
<?php
if($row['mandate_end']!=date('Y-m-d') && $row['job_position']=='unhold')
{
echo '<span class="badge badge-success">Open</span>';
}
else
{
echo '<span class="badge badge-warning">Hold</span>';
}
?>
</div>
<script>
$(document).ready(function(){
var flag = 1;
$(".hold").click(function(){
job_id = this.id;
if(flag == 1)
{
$.ajax({
type:"POST",
data:{"job_id":job_id},
url:"<?php echo base_url(); ?>pausehold",
success:function(data){
$("#success_hold").load("#success_hold");
}
});
flag = 0;
}
else
{
$.ajax({
type:"POST",
data:{"job_id":job_id},
url:"<?php echo base_url(); ?>resumehold",
success:function(data){
$("#success_hold").load("#success_hold");
}
});
flag = 1;
}
});
});
</script>
I have div where id="success_hold". Now, what happens when I click on class="hold" I am updating my data. Now, I want to refresh my <div id="success_hold"> without reload whole page where I am using .load() function But the problem is that when I use .load() the function shows the whole page in success_hold. So, How can I fix this issue? I want to refresh only success_hold.
Thank You
The problem is because load() is used to make another AJAX request and place the a portion of the HTML retrieved from that request in the target element.
As you're already making an AJAX request to get the data, which is presumably HTML, you simply need to append() data to the container.
Also note that the only difference between the two sides of your condition is the URL the request is sent to, so you can easily DRY this code up:
$(document).ready(function() {
var flag = true;
$(".hold").click(function() {
var url = '<?php echo base_url(); ?>' + (flag ? 'pausehold' : 'resumehold');
flag = !flag;
$.ajax({
type: "POST",
data: { job_id: this.id },
url: url,
success: function(data) {
$("#success_hold").append(data);
}
});
});
});
If data contains the entire page, then you should change that PHP file to return only the relevant HTML as it will help to speed up the request. If, for whatever reason, you can't do that then you can extract the required element from the response like this:
$("#success_hold").append($(data).find('#success_hold'));
success:function(data){
$("#success_hold").load("#success_hold");
}
This is your success method in ajax. You want to pur the content of data into your div #success_hold ?
If you want that, just do this :
success:function(data){
$("#success_hold").html(data);
}

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);
}
});
});

Delete data from database without reloading the page

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

Make page refresh if successful login with ajax/jquery

Ajax code
$("#login_btn").click(function() {
var url = "core/login.php";
$.ajax({
type: "POST",
url: url,
data: $("#sr").serialize(),
success: function(data) {
var responseData = jQuery.parseJSON(data);
$('.oops').html('<div class="error">'+responseData.oops+'</div>');
alert(responseData.good);
if(responseData.good === 1) {
alert(good)
location.reload();
}
}
});
});
Php code if everything passes
else {
$_SESSION['id'] = $login;
$good = 1;
exit();
}
How come it's not freshing the page with location.reload? Should I be using .done .try?
Dont refresh, the whole idea of using ajax is that you dont need to.
You can set your sessions in the ajax php script and pull new content based on the change in session.
That being said, you are missing a ';' at
alert(good);

Categories