Jquery .onclick POST var using ajax and receiving data from mysql - javascript

I'm trying this:
- Onclick on button get this.data-id as id in a DB select
- These data will be dynamically shown in a modal
What I dont know is how to work with ajax, can anyone help?
HTML
<a data-toggle="modal" data-id="'.$method['id'].'" title="Visualizar" class="itemview btn btn-info btn-mini" href="#MethodView">Visualizar</a>
.php
if(!empty($_POST)){
if (isset($_POST['id']) && $_POST['id'] > 0){
$id=$_POST['id'];
GetPaymentMethodView();
}
}
function GetPaymentMethodView() {
global $db;
try{
$query = $db->query("SELECT * FROM payment_methods WHERE id=$id");
$row=$query->fetch(PDO::FETCH_ASSOC);
$result['success'] = true;
$result['result'] = $row;
echo json_encode($result);
return true;
} catch (PDOException $pe) {
return false;
}
}
.js
$('.itemview').click(function (e) {
e.preventDefault();
var uid = $(this).data('id');
$.ajax({
type: "POST",
url: "resources/controllers/get.php",
data: 'id='+uid,
dataType: "json",
success: function (data) {
if (data.success) {
console.log(data.result);
console.log(data.result.id);
} else {
alert("error");
}
}
});
});

In page where you want to display result put something like this
<div class="result"></div>
In try small modification
try{
$query = $db->query("SELECT id, name, bank_info FROM payment_methods WHERE id=$id");
$row=$query->fetch(PDO::FETCH_ASSOC);
$result['success'] = true;
$result['result'] = $row;
echo json_encode($result);
exit;
return true;
}
In js small editing
success: function (data) {
if (data.success) {
//How to show rows in php?
console.log(data.result);
console.log(data.result.id);
var result = data.result;
//prepare markup
var resultHtml = '';
resultHtml += '<p>Id = ' + result.id +'</p>';
resultHtml += '<p>Name = ' + result.name +'</p>';
resultHtml += '<p>Bankinfo = ' + result.bank_info +'</p>';
//Put markup in div
$(".result").html(resultHtml)
} else {
alert("error");
}
}
And see in browser console to understand.

As both code is in same page you can perform this without js/jQuery too, for that just add value of $method['id'] directly to <input>.
See below to understand
Remove value of $method['id'] from <a> tag
<a data-toggle="modal" data-id="" title="Visualizar" class="itemview btn btn-info btn-mini" href="#MethodView">Visualizar</a>
Add value directly to <input> tag
<input type="text" name="methodid" id="methodid" value = "<?php echo $method['id']; ?>" />
And problem solved without js. :) So remove js stuff.

Related

PHP - Mysql - Security

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>

AJAX On Keyup Search Function

I wrote a AJAX search function which grabs the keyword values on key up and fires off the script. My goal is to have it populate the content area every key reordering the results to be in ABC order.
Instead what's happening is the first key fires off and the top result is always this
*ENGRAVING
then the rest of the values under it are in no specific order that I can tell.
I think this has to do with escaping characters?
Any help would be appreciated. Please help me get this to function so as a user searches the content area reorders itself being in order based on the keyword being searched up to the value that has been entered at that time.
On page load 5 results are added to the page then on page scroll more results are added to the page like this,
var assetPath = "<?php echo $assetPath ?>";
var searchPath = "<?php echo $searchPath ?>";
function displayRecords(lim, off) {
jQuery.ajax({
type: "GET",
async: false,
url: assetPath,
data: "limit=" + lim + "&offset=" + off,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html) {
$("#productResults").append(html);
$('#loader_image').hide();
if (html === "") {
$("#loader_message").html('<button data-atr="nodata" class="btn btn-default" type="button">No more records.</button>').show();
} else {
$("#loader_message").html('Loading... Please wait <img src="http://www.example.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
}
Then when a user wants to search they use this form,
<div class="form-group pull-right">
<input type="text" name="itemID" id="itemID" class="search form-control" placeholder="Search product number">
</div>
Then this ajax function fires off on keyup
$("#itemID").keyup(function (){
var itemID = $(this).val();
var url = searchPath;
$.ajax({
type : "GET",
async : false,
url : url,
data : "itemID=" + encodeURIComponent(itemID),
cache : false,
success: function(html) {
$('#loader_image').hide();
$( "#productResults" ).replaceWith( html );
if (html === "") {
$("#loader_message").html('<p>There were no results that match your search criteria</p>').show();
} else {
$("#loader_message").html('Searching... Please wait <img src="http://www.example.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
});
which runs this script at searchPath as the path variable
require_once ('Dbconfig.php');
$sql=" SELECT * FROM wuno_inventory WHERE wuno_product like '%".$itemID."%' OR wuno_alternates like '%".$itemID."%' ORDER BY wuno_product ";
try {
$stmt = $DB_con->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo '<tr class="invent">';
echo '<td>' . $res['wuno_product'] . '</td>';
echo '<td>' . $res['wuno_alternates'] . '</td>';
echo '<td>' . $res['wuno_description'] . '</td>';
echo '<td>' . $res['wuno_onhand'] . '</td>';
echo '<td>' . $res['wuno_condition'] . '</td>';
echo '</tr>';
}
}
The initial data populates perfectly in order from what is in the database. So I do not see why there would be problems for this function if it is a escaping situation.
Also the initial data is paginated. Would this cause a problem with the second query? I was thinking maybe since there is so much data it's all being appended to the content instead of replacing it. Maybe the jquery is conflicting?
Try introducing the timeout for your AJAX call. Move your AJAX JS into a separate function first:
function get_search_results(event) {
var itemID = $(event.target).val();
var url = searchPath;
$.ajax({
type : "GET",
async : false,
url : url,
data : "itemID=" + encodeURIComponent(itemID),
cache : false,
success: function(html) {
$('#loader_image').hide();
$( "#productResults" ).replaceWith( html );
if (html === "") {
$("#loader_message").html('<p>There were no results that match your search criteria</p>').show();
} else {
$("#loader_message").html('Searching... Please wait <img src="http://www.example.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
}
Then add it to your keyup handler:
$("#itemID").keyup(function (){
setTimeout(get_search_results, 200);
});

Confirm action then delete row from mysql table

I am using javascript to alert user if he is sure to delete row from database.
In html table I am using column for deleting rows.
<td><center><a href="" id="brisi" value="<?=$r['Id']; ?>" class="delete" data-confirm="Are you sure that you want to delete?"><i class="fa fa-times"></i></center>
I am using script to alert user then to navigate to php script to delete row
<script>
var deleteLinks = document.querySelectorAll('.delete');
for (var i = 0; i < deleteLinks.length; i++) {
deleteLinks[i].addEventListener('click', function(event) {
event.preventDefault();
var choice = confirm(this.getAttribute('data-confirm'));
if (choice==true) {
var x =document.getElementById("brisi").value;
$.ajax({ url: 'edit/delete.php?a=1',
type: 'post',
success: function(output) {
document.getElementById("brisi").value = output;
}
});
}
if (choice==false) {
return false;
}
});
}
</script>
Php script
<?php
if ($_GET['a']==1) {
$id = test_input($_POST['brisi']);
echo $id;
}
?>
I am trying to send value of each row. For some reason my js does not work, could anyone provide quick advice?
you should change your html
<td><center><a href="javascript:;" data-value="<?=$r['Id']; ?>" class="delete" data-confirm="Are you sure that you want to delete?"><i class="fa fa-times"></i></center>
and also change javascript
$('.delete').off('click').on('click', function(e){
e.preventDefault();
var choice = confirm($(this).data('confirm'));
if(choice){
var x = $(this).data('value');
$.ajax({
url: 'edit/delete.php?a=' + x,
type: 'post',
success: function(output) {
document.getElementById("brisi").value = output;
}
});
}
else{
return false;
}
});
and php code
<?php
if (isset($_GET['a']) && $_GET['a'] != ''){
$id = test_input($_GET['a']);
echo $id;
}
?>
onclick="return confirm('Are you sure you want to delete this item?');"
I would like to know why you are checking for this:
var x =document.getElementById("brisi").value;
And you don't use it.
I hope also that 'brisi' is the unique ID only for this element.
Next you are doing a POST request with ajax:
$.ajax({ url: 'edit/delete.php?a=1',
type: 'post',
success: function(output) {
document.getElementById("brisi").value = output;
}
});
I notice in your PHP you are trying to GET your posted vriable:
if ($_GET['a']==1) {
$id = test_input($_POST['brisi']);
echo $id;
}
And you should do:
if (isset($_POST['a') && $_POST['a'] == 1) {
$id = test_input($_POST['brisi']);
echo $id;
}
And finally what is this function doing:
test_input($_POST['brisi'])
You don't have any posted value with this index.
To recap If you need more help please post your complete HTML form.

Showing Busy loading Indicator during an AJAX Request using jQuery

I have status active/Deactive Buttons when user clicks on active status it turns into deactive with red color and vice versa
currently i'm able to update my status #backend but everytime i should refresh to see my changes!!
my requirement is during active/deactive process of changing status i want to load ajax image loader where loader image should overlay entire screen. and my status should be updated in mysql db!!
please any help is appricated Thanks!
Php Code
<?php
include 'db.php';
$sql = "select * from sections order by id asc";
$data = $con->query($sql);
$str='';
if($data->num_rows>0)
{
while( $row = $data->fetch_array(MYSQLI_ASSOC))
{
$str.="
"?>
<div class="row">
<div class="col-md-1">
<?php
if ($row['status'] == '1')
{
?>
<a href="#" class="btn btn-success btn-sm active" ida='<?php echo $row['id'];?>'></a>
<?php }
else if($row['status'] == '0')
{
?>
<a href="#" class="btn btn-danger btn-sm deactive" idde='<?php echo $row['id'];?>'></a>
<?php } ?>
</div>
</div>
<?php
}
}
else
{
$str .= "<p style='text-align:left;'>No Data Available</p>";
}
echo $str;
?>
Jquery Code
<script type="text/javascript">
$('body').delegate('.active','click',function(e){
var IdStatus = 0;
var id = $(this).attr('ida');
$.ajax({
url:"pages/status1.php",
data:{
status:IdStatus,
id:id
},
dataType:'html',
success:function()
{
alert('success');
}
});
e.preventDefault();
return false;
});
$('body').delegate('.deactive','click',function(e){
var IdStatus = 1;
var id = $(this).attr('idde');
$.ajax({
url:"pages/status1.php",
data:{
status:IdStatus,
id:id
},
dataType:'html',
success:function()
{
alert('success');
}
});
e.preventDefault();
return false;
});
</script>
PHP Updation Code
<?php
if(isset($_REQUEST['status']))
{
$status = $_REQUEST['status'];
$id = $_REQUEST['id'];
$sql = 'update sections set status='.$status.' where id='.$id.'';
$result = mysql_query($sql);
if($result)
{
echo 'updated successfully';
}
else
{
echo 'failed to update';
}
}
?>
Try this script with mentioned changes:
Changes:
Keep same attribute as data-id for both the operations
loaderElem will be the loader container which should be there in your DOM
BODY is nothing but a body selector, just to avoid redundant selectors
var elem = $(this); is used as I need this reference after success callback
Also make habit of using error callback as you might need to handle that case
var BODY = $('body');
var loaderElem = $('#loader');
BODY.delegate('.active', 'click', function(e) {
loaderElem.show();
var IdStatus = 0;
var elem = $(this);
var id = elem.attr('data-id');
$.ajax({
url: "pages/status1.php",
data: {
status: IdStatus,
id: id
},
dataType: 'html',
success: function() {
elem.removeClass('active').addClass('deactive');
loaderElem.hide();
alert('success');
}
});
e.preventDefault();
return false;
});
BODY.delegate('.deactive', 'click', function(e) {
loaderElem.show();
var IdStatus = 1;
var elem = $(this);
var id = elem.attr('data-id');
$.ajax({
url: "pages/status1.php",
data: {
status: IdStatus,
id: id
},
dataType: 'html',
success: function() {
elem.removeClass('deactive').addClass('active');
loaderElem.hide();
alert('success');
}
});
e.preventDefault();
return false;
});
Try using beforeSend option of $.ajax()
$('body').delegate('.active','click',function(e){
var IdStatus = 0;
var id = $(this).attr('ida');
$.ajax({
url:"pages/status1.php",
beforeSend: function() {
// do overlay stuff
},
data:{
status:IdStatus,
id:id
},
dataType:'html',
success:function()
{
// remove overlay stuff
alert('success');
}
});
e.preventDefault();
return false;
});

Facebook style ajax like system no error but no result

i am currently trying to create a facebook style ajax like system. Below i have created the code like :
Jquery function for ajax call :
function addLikes(likeid,action) {
$('.likebox #tutorial-'+likeid+' li').each(function(index) {
$(this).addClass('selected');
$('#tutorial-'+likeid+' #rating').val((index+1));
if(index == $('.demo-table #tutorial-'+likeid+' li').index(obj)) {
return false;
}
});
$.ajax({
url: "like_process.php",
data:'likeid='+likeid+'&action='+action,
type: "POST",
beforeSend: function(){
$('#tutorial-'+likeid+' .btn-likes').html("<img src='LoaderIcon.gif' />");
},
success: function(data){
var likes = parseInt($('#likes-'+likeid).val());
switch(action) {
case "like":
$('#tutorial-'+likeid+' .btn-likes').html('<input type="button" title="Unlike" class="unlike" onClick="addLikes('+likeid+',\'unlike\')" />');
likes = likes+1;
break;
case "unlike":
$('#tutorial-'+likeid+' .btn-likes').html('<input type="button" title="Like" class="like" onClick="addLikes('+likeid+',\'like\')" />')
likes = likes-1;
break;
}
$('#likes-'+likeid).val(likes);
if(likes>0) {
$('#tutorial-'+likeid+' .label-likes').html(likes+" Like(s)");
} else {
$('#tutorial-'+likeid+' .label-likes').html('');
}
}
});
}
PHP code:
$str_like = 'like';
if(!empty($count)) {
$str_like = 'unlike';
}
$sql = $mysqli->query("SELECT mind.mind_id, mind.mind_user, mind.post_message, mind.like_count, mind.mind_date FROM mind LEFT JOIN friends ON (mind.mind_user = friends.hunter) OR (mind.mind_user = friends.target) WHERE ((friends.hunter = '".$muser."' AND friends.status = '1') OR (friends.target = '".$muser."' AND friends.status = '1')) OR (mind.mind_user = '".$muser."') ORDER BY mind.mind_date DESC limit $start,$limit");
$str='';
if($sql!=null && $sql->num_rows>0){
while($none = $sql->fetch_assoc()){
$timep = $none['mind_date'];
$count = $none['like_count'];
$timeframe=date('c', $timep);
$likeid = $none["mind_id"];
$str.="<div id=\"likebox\"><div class=\"bubble-list\"><div class=\"bubble clearfix\"><img src=\"#\"><div class=\"bubble-content\"><div class=\"point\"></div><p><b>".$none['mind_user']."</b> <small> <time class=\"timeago\" datetime=\"".$timeframe."\">".$timeframe."</small></time></p><p>".$none['post_message']."</p><div id=\"tutorial-$likeid\">
<input type=\"hidden\" id=\"likes-".$none["mind_id"]."\" value=\"".$none["mind_id"]."\">
<div class=\"btn-likes\"><input type=\"button\" title=\"ucwords($str_like)\" class=\"$str_like\" onClick=\"addLikes('$likeid','$str_like')\" /></div>
</div>
</div></div></div></div></div>";
}
$str.="<input type='hidden' class='nextpage' value='".($page+1)."'><input type='hidden' class='isload' value='true'>";
}else{
$str .= "<input type='hidden' class='isload' value='false'><p>Loading Completed</p>";
}
echo $str;
SQL call to like and unlike :
if(!empty($_POST["likeid"])) {
switch($_POST["action"]){
case "like":
$mysqli->query("UPDATE `mind` SET `like_count` = like_count + 1 WHERE `mind_id` = '" . $_POST["likeid"] . "'");
}
break;
case "unlike":
$mysqli->query("UPDATE `mind` SET `like_count` = like_count - 1 WHERE `mind_id` = '" . $_POST["likeid"] . "'");
}
break;
}
}
When i click the button nothing change or it does not update database. I don't know where i am doing wrong. can anybody help me with this situation as i am stuck doing it and tried in different ways but couldn't make it.
Can you try deserializing the data and send as an object?
data: {
'likeid': likeid,
'action': action
}

Categories