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
}
Related
So i have problem whit symbols "&", here my code on javascript
$("#shipCurr").change(function(){
var curr = $(this).val();
$("#shipPO").empty();
if(curr != "")
{
$("#shipPO").prop('disabled',false);
$.ajax
({
type: "POST",
url: host+"buypo/ListPOShippDoc",
data:{
'curr':curr
},
cache: false,
success:function(data)
{
console.log($("#shipPO").html(data));
}
});
}
else
{
$("#shipPO").prop('disabled',true);
}
// console.log("test");
});
and on php code
public function ListPOShippDoc()
{
$currency = $_POST['curr'];
$fullName = $_SESSION['fullName'];
$PONo = $this->shippDoc->ListPO($fullName,$currency)['items'];
$option .= '<option value=""></option>';
while ($val = $PONo->fetch_assoc()) {
$option .= '<option value="'.utf8_decode($val['PONo']).'">'.utf8_decode($val['PONo']).'</option>';
}
echo $option;
}
My problem is,if the PONo value like H&M-000762-001 it show on my html into H&M-000762-001.
How do i get wrong in here? Wy it show H&M-000762-001 not H&M-000762-001? Any idea?
I try utf8_decode() utf8_encode() is still same result H&M-000762-001.
function convertSymbol($value)
{
$value = mb_convert_encoding($value, "ISO-8859-1", "UTF-8");
$ampersandval = str_replace("&", "&", $value);
return $ampersandval;
}
?>
/* mb_convert_encoding this function is used to Convert ISO to UTF-8 */
Using str_replace function we can convert & to &
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.
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);
});
So for my next site, I want to use AJAX and PHP since it doesn't need to reload the page. It didn't work as expected, and after some internet searching, I turned to StackOverflow.
I have the following JS function:
$(function() {
$('#page-wrap #cssmenu a').click(function() {
var $linkClicked = $(this).attr('href');
document.location.hash = $linkClicked;
var $pageRoot = $linkClicked.replace('#page', '');
if (!$(this).hasClass("active")) {
$("#page-wrap #cssmenu a").removeClass("active");
$(this).addClass("active");
$.ajax({
type: "POST",
url: "load.php",
data: 'page='+$pageRoot,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#main-content').slideUp().slideDown().html(msg);
$('#main-content section');
}
}
});
}
else {
event.preventDefault();
}
});
var hash = window.location.hash;
hash = hash.replace(/^#/, '');
switch (hash) {
case 'page2' :
$("#" + hash + "-link").trigger("click");
break;
case 'page3' :
$("#" + hash + "-link").trigger("click");
break;
case 'page4' :
$("#" + hash + "-link").trigger("click");
break;
}
});
The function loads this PHP file:
<?php
if(!$_POST['page']) die("0");
$page = (int)$_POST['page'];
if(file_exists('pages/page'.$page.'.php'))
echo file_get_contents('pages/page'.$page.'.php');
else echo 'There is no such page!';
?>
In this case, I wanna load the staff page. Since it gets all of the staff from a DB it makes use of a lot of PHP, the following lines are from the file:
$rank = '10';
$query = $db->conn->prepare('SELECT * FROM ht_users WHERE rank = ? OR rank2 = ?');
$query->bind_param('ss', $rank, $rank);
$query->execute();
$result = $query->get_result();
$count = $result->num_rows;
$base = 1;
while($row = $result->fetch_assoc())
{
$direction = 'direction=3&';
if($base == 1) $direction = '';
if($base == $count) $direction = 'direction=4&';
$content = '<div class="med">
<b class="eigenaar"><center>' . $row['naam'] . '</center></b>
<img src="imager?hb=img&user=' . $row['naam'] . '&' . $direction . 'head_direction=3&action=sit,wav&gesture=sml&size=l" />
<div style="margin-right:275px;"></div>
</div>
';
echo $content;
$base ++;
}
But when I run the page, it doesn't parse the code, but it just echo's it.
My question is how do I solve this problem?
What you could do is instead of file_get_contents() is look at include this should take care of your issue
if(file_exists('pages/page'.$page.'.php'))
{
include 'pages/page' . $page . '.php';
} else {
echo 'There is no such page!';
}
if you wanted to parse the contents into a variable then you could look at ob_start()
ob_start( );
include 'pages/page' . $page . '.php';
$html = ob_get_clean( );
I have written a php file and jquery to retrieve data from a database and validate on a textfield blur event to check the typed value is whether available or not. Below are my code:
On form php:
<script>
$("#catname").blur(function() {
$.post("./scripts/checkavailability.php", {
nameava: $("#catname").val(),
}, function(data) {
alert(data);
});
var setr = "<?php
include './scripts/checkavailability.php';
$dbava = getfromdb("name", "tbl_category");
$avams = check($txtval, $dbava, "$name");
echo $avams;
?>";
$("#jinx").html(setr);
});
</script>
checkavalilability.php :
<?php
if (isset($_POST['nameava'])) {
$txtval = mysql_real_escape_string($_POST['nameava']);
}
function getfromdb($field, $table) {
$avres = mysql_query("SELECT `" . $field . "` FROM `" . $table . "`");
return $avres;
}
function check($curval, $qres, $s_field) {
while ($a_row = mysql_fetch_array($qres)) {
$dbval = $a_row[$s_field];
if ($curval == $dbval) {
return "This value is taken";
break;
} else {
return "This value is available";
}
}
}
?>
Note: catname is the textfield id and jinx is the div id.
I think you are trying something like this:
jQuery:
<script>
$("#catname").blur(function() {
$.post("./scripts/checkavailability.php", {
nameava: $("#catname").val(),
}, function(data) {
alert(data);
$("#jinx").html(data);
});
});
</script>
PHP:
<?php
function getfromdb($field, $table) {
$avres = mysql_query("SELECT `" . $field . "` FROM `" . $table . "`");
return $avres;
}
function check($curval, $qres, $s_field) {
while ($a_row = mysql_fetch_array($qres)) {
$dbval = $a_row[$s_field];
if ($curval == $dbval) {
return "This value is taken";
//break;
} else {
return "This value is available";
}
}
}
if (isset($_POST['nameava'])) {
$txtval = mysql_real_escape_string($_POST['nameava']);
$dbava = getfromdb("name", "tbl_category");
$avams = check($txtval, $dbava, "name");
echo $avams;
}
exit();
?>