I have written following PHP and Javascript code to prompt a user to delete a record, which works great.
I somehow do not think that this code is secure, the reason is if you run the script in a browser, and do a View-source a person will be able to see that I am using delete.php and passing an ID to delete the record.So there can be a possibility of deleting the records using delete.php
Is there a way to secure the code.
My PHP code is
<?
$rs = "SELECT * FROM my tablename";
$result = mysqli_query($con,$rs);
$data = mysqli_num_rows($result);
$responses = array();
if($data != 0) {
while($results = mysqli_fetch_assoc($result))
{
$res_id=$results['id'];
echo "<tr id='".$results['id']."'><td>".$results['_name'] ."</td>";
echo "<td><a alt='delete' href='javascript:;' onclick='fun_delete(".$results['id'].")' title='delete'><span class='glyphicon glyphicon-remove-circle'></span> ";
e
}
}
?>
My Javascript code is
<script>
function fun_delete(x)
{
//alert(x);
var result = confirm("Are you sure you want to delete the record?");
if (result) {
//alert(x);
jQuery.ajax({
url: "delete.php",
type: "post",
data: {id:x},
success: function(data){
if(data){
location.reload();
}
},
error:function(){
// JQ.fancybox.hideLoading();
alert("failure");
}
});
}
}
</script>
Related
In my project am using ajax for sending message the problem is i can't get the response in the ajax function the function works perfectly before,Can't find exact cause of the issue help me to solve it
ajax
var str = {
message:message, department_id:department, email:email, username:name
};
$.ajax( {
type: "POST",
url:'<?php echo base_url(); ?>home/savemessage',
dataType:"json",
data: str,
success: function(msg) {
$('#sentchat') . hide();
$('#chatmessage') . show();
$('#userchat') . html(msg . dataid);
$('.chat-box-content') . hide();
$('#adminname span').html('waiting for admins reply');
var elem = document . getElementById('userchat');
elem.scrollTop = elem . scrollHeight;
}
});
php controller
function savemessage() {
extract($this->input->post());
$data['message_id'] = $this->session->userdata('msgid');
$data['username'] = $username;
$data['email'] = $email;
$data['department_id'] = $department_id;
$data['message'] = $message;
$data['datetime'] = date('Y-m-d H:i:s');
$data['status'] = 'new';
$data['message_by'] = '1';
$this->db->insert('message', $data);
echo json_encode($username);
exit;
}
I cant get the response in it help me to solve it
You use ajax to communicate with a PHP script, inside the PHP script you could have the content of the function you want to execute. For example in your code:
$.ajax( {
type: "POST",
url:'<?php echo base_url(); ?>home/savemessage.php',
dataType:"json",
data: {myData:str},
success: function(msg) {
$('#sentchat') . hide();
$('#chatmessage') . show();
$('#userchat') . html(msg . dataid);
$('.chat-box-content') . hide();
$('#adminname span').html('waiting for admins reply');
var elem = document . getElementById('userchat');
elem.scrollTop = elem . scrollHeight;
}
});
Then, on the server side the php script "savemessage.php" would receive the POST action, so you could have:
if(isset($_POST['myData']) && !empty($_POST['myData'])) {
$obj = $_POST['myData'];
//rest of your code
echo json_encode($username);
exit;
}
However from your code I cannot see $username defined, so that probably would return an error.
I have read many answers on stack overflow but I can't find an apt answer. I want to send multiple variables from php file to a javascript file. I want to use those variables later separately. So please explain with a simple example of how to get the variables from php file and how to use them separately later.
This is my js.
<script>
function here(card_numb) {
alert("pk!");
$.ajax({
url: 'details.php',
type: "GET",
dataType: 'json',
data: ({
card_number: card_numb
}),
success: function(data) {
console.log('card_number:'+data.card_number+'book_issued:'+data.book_isued);
}
});
}
I'm getting the alert 'pk!'. But $.ajax ain't working.
This is details.php
<?php
if(isset($_GET['card_number'])){
$card_number = $_GET['card_number'];
$query = "Select * from users where card_number = '".$card_number."'";
$query_run = mysqli_query($link,$query);
$row_numb =#mysqli_num_rows($query_run);
if($row_numb == 0){
echo "<div class='bdiv1'>No such number found!</div>";
} else{
$row=mysqli_fetch_assoc($query_run);
$book1 = $row['user_name'];
$arr = array('isued_book' => $book1,'card_number' => $card_number);
echo json_encode($arr);
exit();
}
}
?>
Thank you!
somthing.js - ur jspage
<script>
function here(card_numb) {
$.ajax({
url: 'details.php',
type: 'GET',
dataType: 'json',
data: {
card_number: card_numb
},
success: function(data) {
console.log('card_number:'+data.card_number+'book_issued:'+data.isued_book);
}
});
}
success: function(result){
console.log('variable1:'+result.var1+'variable2:'+result.var2+'variable3:'+result.var3);
} });
details.php
<?php
if(isset($_GET['card_number'])){
$card_number = $_GET['card_number'];
$query = "Select * from users where card_number = ".$card_number;
$query_run = mysqli_query($link,$query);
$row_numb =#mysqli_num_rows($query_run);
if(!$query_run){
echo "<div class='bdiv1'>No such number found!</div>";
} else {
$row=mysqli_fetch_assoc($query_run);
$book1 = $row['user_name'];
$arr = array('isued_book' => $book1,'card_number' => $card_number);
echo json_encode($arr);
exit();
}
if the currect value get in $row you can get the result in console
I have a small problem here, i'm trying to have an anchor tag called "Photos", so when the user clicks on that anchor, tha Ajax will grab the results from PHP/MySQL database and display the images inside the opened lightbox.
I have tried to create something like this:
Fotos
Then Ajax:
$(document).on('click','#photos',function(event){
var imovel_id = $(this).attr('id');
$.ajax({
url: 'gallery_query',
type: 'POST',
dataType:"json",
data:{imovel_id: imovel_id},
success: function(data) {
if(data.status == 1) {
//Display images;
} else {
// Return Error message;
}
}
});
initLightbox();
});
Then my PHP query:
<?php require("includes/db_connect.php"); ?>
<?php $imovel_id = $_POST['property_id']; ?>
<?php
$query = "SELECT * FROM gallery WHERE imovel_id = '$imovel_id'";
$result = mysqli_query($connection,$query);
while($row = mysqli_fetch_assoc($result) ){
?>
<?php
if($result > 0){
$data['status'] = 1;
$data['retorno'] .= '<img src="../images/imoveis/'. $row['foto_gallery'] .'>';
mysqli_close($connection);
}else{
$data['status'] = 0;
$data['retorno'] = "Erro ao exibir fotos, se o erro persistir, entre em contato conosco.";
}
echo json_encode($data);
?>
<?php } ?>
My problem is, i don't know if this is working, and what to use in Ajax success. I'm learning how Ajax works exactly, so i tried to implement it with lightbox as experiment.
Any thoughs?
Thanks!
A few pointers:
Escape your string to ensure no SQL injections are sent to your server (not escaping could allow someone to delete all your data!
<?php $imovel_id = mysqli_real_escape_string($_POST['property_id']); ?>
This is if in your database you record strings for imovel_id,
If not
<?php $imovel_id = intval($_POST['property_id']); ?>
<?php
$query = "SELECT * FROM gallery WHERE imovel_id = $imovel_id";
Sending the result:
// declare $data before, scope issue
$data = null;
if($result > 0){
$data['status'] = 1;
$data['retorno'] .= '<img src="../images/imoveis/'. $row['foto_gallery'] .'">'; // you were missing a closing quote for the image src.
}else{
$data['status'] = 0;
$data['retorno'] = "Erro ao exibir fotos, se o erro persistir, entre em contato conosco.";
}
mysqli_close($connection); // close connection regardless of returned data
echo json_encode($data);
Hope this helps.
Edit:
One last thing, if you want to display what you are receiving:
$.ajax({
url: 'gallery_query',
type: 'POST',
dataType:"json",
data:{imovel_id: imovel_id},
success: function(data) {
if(data.status == 1) {
$('#idOfElement').html(data.retorno);
} else {
// Return Error message;
}
}
});
I have some problem with the returned value of ajax.
this is the ajax code:
$(document).ready(function() {
var request;
$("#flog").submit(function(event) {
if(request)
request.abort();
event.preventDefault();
var form = $(this);
var serializedData = form.serialize();
var btnname = $('#log').attr('name');
var btnval = $('#log').val();
var btn = '&'+btnname+'='+btnval;
serializedData += btn;
request = $.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: serializedData,
});
request.done(function(data, status, jdXHR) {
alert(data);
});
request.fail(function(jdXHR, status, error) {
});
});
});
it takes data from a form and send it to another page.
this is the second page:
<?php include 'head.php'; ?>
<?php
if($_POST['login']) {
session_regenerate_id(true);
$con = mysqli_connect("localhost", "Alessandro", "ciao", "freetime")
or die('Could not connect: ' . mysqli_error($con));
$query = 'SELECT * FROM users WHERE username="' . $_POST['user'] . '"';
$result = mysqli_query($con, $query) or die('Query failed: ' . mysqli_error($con));
if(mysqli_num_rows($result) == 0) {
mysqli_close($con);
session_unset();
session_destroy();
$res = false;
return $res;
}
$query = 'SELECT password FROM users WHERE username="' . $_POST['user'] . '"';
$result = mysqli_query($con, $query) or die('Query failed: ' . mysqli_error($con));
$line = mysqli_fetch_array($result, MYSQL_ASSOC);
if(md5($_POST['password']) != $line['password']) {
mysqli_close($con);
session_unset();
session_destroy();
return false;
}
?>
<?php include 'foot.php'; ?>
and in .done the returned data is all the html page.
How can I retrieve only a data, like $res? I tried with json_encode() but with no results.
If in the second page I delete the lines include 'head.php' and include 'foot.php' it works. But I need that the secon page is html, too.
Somenone can help me?
Dont use the Data attribute from AJAX.
Replace
request.done(function(data, status, jdXHR) {
alert(data);
});
with
request.done(function(data, status, jdXHR) {
alert(jdXHR.responseText);
});
You could do it in a much simpler way.
In PHP store the result of the attempted login into a variable, for instance $result =0; to start with
If the login is valid change it to 1 and return it to ajax by doing an echo at the end of your PHP file. If you need other value returned such as the name you could add it to the variable with a separator such as || for instance.
in javascript collect your return and go data = data.split('||');
if (data[0] == 0){alert("Welcome back " + data[1]);}else{alert("wrong login...")}
Previous use is correct, you need to escape the user collected in your PHP script.
Hope this helps.
Hi I have a PHP file with data. The value is passed on to another php file which process it successfully. But the first php file does not refresh to update the new result. It have to do it manually. Can any one tell me where I'm wrong or what needs to be done. Please find my code below.
PHP code (1st page, index.php)
function display_tasks_from_table() //Displayes existing tasks from table
{
$conn = open_database_connection();
$sql = 'SELECT id, name FROM todolist';
mysql_select_db('todolist'); //Choosing the db is paramount
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
echo "<form class='showexistingtasks' name='showexistingtasks' action='remove_task.php' method='post' >";
while($row = mysql_fetch_assoc($retval))
{
echo "<input class='checkbox' type='checkbox' name='checkboxes{$row['id']}' value='{$row['name']}' onclick='respToChkbox()' >{$row['name']} <img src='images/show_options.gif' /><br>";
}
echo "</form>";
echo "<label id='removeerrormsg'></label>";
close_database_connection($conn);
}
Javascript code which finds the selected value:
var selVal; //global variable
function respToChkbox()
{
var inputElements = document.getElementsByTagName('input'),
input_len = inputElements.length;
for (var i = 0; i<input_len; i++)
{
if (inputElements[i].checked === true)
{
selVal = inputElements[i].value;
}
}
}
jQuery code which passes value to another page (remove_Task.php):
$(document).ready(function() {
$(".checkbox").click(function(){
$.ajax({
type: "POST",
url: "remove_task.php", //This is the current doc
data: {sel:selVal, remsubmit:"1"},
success: function(data){
//alert(selVal);
//console.log(data);
}
});
});
});
PHP code (2nd page, remove_task.php);
session_start();
error_reporting(E_ALL);ini_set('display_errors', 'On');
$task_to_remove = $_POST['sel'];
function remove_from_list() //Removes a selected task from DB
{
$db_connection = open_database_connection();
global $task_to_remove;
mysql_select_db('todolist');
$sql = "DELETE FROM todolist WHERE name = "."'".$task_to_remove."'";
if($task_to_remove!='' || $task_to_remove!=null)
{
mysql_query($sql, $db_connection);
}
close_database_connection($db_connection);
header("Location: index.php");
}
if($task_to_remove != "") {
remove_from_list();
}
The selected value is getting deleted but the display on index.php is not updated automatically. I have to manually refresh to see the updated result. Any help would be appreciated.
By calling header("Location: index.php"); you don't redirect main page. You sent an ajax request - you can think about it as of opening a new page at the background, so this code redirects that page to index.php.
The better way to solve your task is to return status to your success function and remove items which were deleted from the database.
success: function(data){
if(data.success){
//remove deleted items
}
}