Find data attribute and insert it to database using ajax - php

I need a correct script for iserting data attribute to database onclick using ajax.
HTML:
<li><a data-cat="random name">Button</a></li>
jQuery:
$('li a').click(function() {
$(this).data('cat');
// Dont know how correctly use ajax here.
});
PHP:
$cat = HERE MUST BE DATA ATTRIBUTE;
$timer = time();
$something = NULL;
$stmt = $db->prepare("INSERT INTO table (cat, timer, something) VALUES(:cat, :timer, :something)");
$stmt->execute(array(':cat' => $cat, ':timer' => $timer, ':something' => $something,));
Sorry for bad english, and thanks for any answers.

More info at about jQuery.post()
$('li a').click(function() {
var category = $(this).data('cat');
$.ajax({
type: "POST",
url: '/script.php',
data: {'cat': category}
});
});
PHP
$cat = $_POST['cat'];

Related

need help for proper way to write codes for create "loadmore" button and "like" button for posts

I create a load more button for load more posts from the database but when I add like button for that if one time clicks on load more button and then click on the like button, like.php file runs two times and adds two lines in likes table. if I click 2 times on load more then like.php file runs 3 times and...
I want to know how I should create a loadmore button and like the button to works fine.
this is simple of my codes:
posts.php :
<div id="comnts2"></div>
<button id="btn2" >load more</button><script>
$(document).ready(function() {
var comco2 = 2;
var offset2 = 0;
$("#btn2").click(function() {
$.ajax({
method: "POST",
url: "ld_comco.php",
data: { comnco2 : comco2, offset2 : offset2}
})
.done(function(msg2) {
$("#btn2").hide();
} else {
$("#comnts2").append(msg2);
});
offset2 = offset2 + comco2;
});
$("#btn2").trigger("click");
});
</script>
ld_comco.php:
<?php
$comnco2=$_POST['comnco2'];
$offset2=$_POST['offset2'];
$rzp=mysqli_query($conn,"SELECT * FROM `tbl_users_posts` WHERE uid = '$uid' ORDER BY id DESC limit $offset2, $comnco2");
while($rp=mysqli_fetch_assoc($rzp)){
$sid=$rz['id'];
$lik=$rz['lik'];
echo $sid."<br>";
/*like*/
echo'<img class="li_ik1" data-id="'.$sid.'" src="pc3/up.png">'.$lik.' Likes</img>';
?>
</span>
<?php }?>
<script type="text/javascript">
$(document).ready(function() {
var uid=<?php echo $uid;?>;
$(document).on("click", ".li_ik1", function() {
var psid = $(this).data('id');
$.ajax({
method: "POST",
url: "like.php",
data: {psid: psid, uid: uid}
}).done();
});
});
</script>
like.php:
<?php
$id=$_POST['psid'];
$uid=$_POST['uid'];
$Y=mysqli_query($conn,"INSERT INTO `t_plik` (pid,uid) VALUES ('$id','$uid')");
$Q=mysqli_query($conn,"UPDATE `tbl_users_posts` SET lik=lik+1 WHERE id='$id'");
?>
thanks
I think the problem is, that you bind your like button multiple times globally. Each time you load the content from ld_comco.php you also call $(document).on("click", ".li_ik1", ...) in the $(document).ready block, which means you bind all ".li_ik1" buttons on the entire document (but some of them has already been bind).
I would remove the $(document).ready(...) block from the ld_comco.php and move the logic into the posts.php right before you render your content. A further positive aspect is you have your business logic at one place.
KEEP IN MIND: You get a response of buttons in msg2, thats why you do not need to filter $msg2 anymore. But if you wrap your buttons with further html tags in ld_comco.php, your buttons will be on a deeper level, so you need to use a selector again, like you did with .on("click", ".li_ik1", ...).
posts.php
...
var $msg2 = $(msg2);
// Now you bind only the loaded buttons instead of
// the buttons in the entire document for multiple times
$msg2.on("click", function() {
var $element = $(this);
var psid = $element.data('id');
var uid = $element.data('uid');
$.ajax({
method: "POST",
url: "like.php",
data: {psid: psid, uid: uid}
}).done();
});
$("#comnts2").append($msg2);
...
In your ld_comco.php you need to add the data-uid="'.$uid.'" and remove the script block. Then your file should look like this:
<?php
$comnco2=$_POST['comnco2'];
$offset2=$_POST['offset2'];
$rzp=mysqli_query($conn,"SELECT * FROM `tbl_users_posts` WHERE uid = '$uid' ORDER BY id DESC limit $offset2, $comnco2");
while($rp=mysqli_fetch_assoc($rzp)){
$sid=$rz['id'];
$lik=$rz['lik'];
echo $sid."<br>";
/*like*/
echo'<img class="li_ik1" data-id="'.$sid.'" data-uid="'.$uid.'" src="pc3/up.png">'.$lik.' Likes</img>';
}
?>
$("#btn2").trigger("click");
this in posts.php means click the #btn2
so after clicking it, you click it again
$(document).ready(function() {
var comco2 = 2;
var offset2 = 0;
$("#btn2").click(function() {
$.ajax({
method: "POST",
url: "ld_comco.php",
data: { comnco2 : comco2, offset2 : offset2}
})
.done(function(msg2) {
$("#btn2").hide();
} else {
$("#comnts2").append(msg2);
});
offset2 = offset2 + comco2;
});
$("#btn2").trigger("click");
});
</script>

How Make a dependable dropdown list by taking values from Database

I want to make a dropdown list which is dependable on another dropdown list. Both dropdown list's values are retrieved from database. How can i do that?please help .
Also how can i pass the category name to database mysql query page (list.php).
I currently have this which list all subcategories..but i want to list only particular subcategory depending on category
<script>
$(document).ready(function(){
$.getJSON("getlist.php", function(return_data){
return_data.forEach(function(e,i){
$('#catn').append('<option value= "'+e.catname+'">'+e.catname+'</option>');
});
});
});
$(document).ready(function(){
$.getJSON("list2.php",{'catname':catname},function(return_data){
return_data.forEach(function(h,i){
$('#scatn').append('<option value= "'+h.subcatname+'">'+h.subcatname+'</option>');
});
});
});
list.php
<?php
$catname=$_GET['catname'];
$conn =mysqli_connect("localhost", "root", "", "project");
$sql = "SELECT * FROM catd where catname='$catname'";
$result = mysqli_query($conn, $sql);
$scat_arr = array();
while( $row = mysqli_fetch_array($result) )
{
$catid = $row['cid'];
$catname = $row['catname'];
$scat_arr[] = array("cid" => $catid, "catname" => $catname);
}
echo json_encode($scat_arr);
?>
You can use .change function in JS. While the first dropdown is changing it triggers the ajax with POST method to post to your file list.php(where your query runs).
jQuery(document).ready(function() {
$('#catname').change(function(){
var catname = $(this).val();
$.ajax({
url:list.php,
method:"POST",
data:{
catname:catname
},
dataType:"json",
success:function(data){
var $el = $("#subcatname");
$el.empty();
$el.append($("<option></option>")
.attr("value", '')
.attr("hidden",'')
.text('Select Sub Cat Name'));
$.each(data, function(index, value){
$el.append('<option
value="'+value.catid+'">'+value.catname+'</option>')
});
});
You must echo json_encode the output so that ajax recognize the returned value. And then you can append the values by casting it using append.
Hopes this helped.

Ajax and PHP not updating database

This ajax code gets called, I tested it, but the database does not get updated.
I think the code is small enough not to need any further explanation. When something from the class pdb gets clicked, it saves its source to the database.
$(function(){
$('.pdb').on('click',function(){
var sou = $(this).attr('src');
var iddo = $(this).attr('id');
var data = 'id='+iddo+'&value='+sou+'&turno='+(bia)?true:false;
$.ajax({
data: data,
type: "post",
url: "database.php",
success: function(data){
alert("Prova: " + data);
}
});
});
});
database.php
<?php
mysql_connect("localhost","pierostesting","");
mysql_select_db("my_pierostesting");
$id=$_POST['id'];
$value =$_POST['value'];
$turno=$_POST['turno'];
if(true){
$sql="UPDATE board SET $id=$value, turno=$turno WHERE partita=0";
$result=mysql_query($sql);
if($result){
echo "Nailed it";
}
}else{
}
?>
remove
var data = 'id='+iddo+'&value='+sou+'&turno='+bia;
and debug ajax calls use either console or firebug extension
replace:
var data = 'id='+iddo+'&value='+sou+'&turno='+(bia)?true:false;
with
data = { 'id':iddo,'value':sou,'turno':(bia)?true:false}
Needed to change the PHPto this:
$sql="UPDATE board SET $id='$value', turno=$turno WHERE partita=0";
Simply change $value with '$value', bloody ''. Thank you all guys.

ajax code stops running when I pass a string from PHP

php
$sortBy = array('upload_date','wall_views','wall_downloads');
$sort = 'upload_date';
if(isset($_GET['sort']) && in_array($_GET['sort'], $sortBy)){
$sort = $_GET['sort'];
}
ajax script
<script type="text/javascript">
var per_page = <?php echo $per_page;?>; //$per_page = 3
var last_page = <?php echo $last_page;?>; //$last_page = 4
var sort = <?php echo $sort;?>; //$sort = upload_date
$(function(){
$('.more').live('click', function(){
var page = $(this).attr('id'); //get the last id
$.ajax({
type: 'GET',
url: 'pagination.php',
data: {page: page, per_page: per_page, last_page: last_page, sort: sort},
success: function(data){
$('#itemContainer').append(data);
}
}); //ajax code end
}); //live end
}); //function end - when DOM is ready.
</script>
the problem occurs when I try to pass a string (upload_date) variable to ajax, I'm not sure if I'm passing the string correctly, this code works fine if only integers/digits are passed into the code. What I'm I doing improperly here? please help.
You'll have to add quotes around string variables. otherwise your generated javascript will look like variable names rather than string literals.
Like so:
var sort = "<?php echo $sort;?>"; //$sort = upload_date

getting info from json with jquery

Having trouble using ajax to retrieve info from a database. I was getting the code from here:
http://openenergymonitor.org/emon/node/107
the code from here worked but would only output 1 item
Simple Ajax Jquery script- How can I get information for each of the rows in the table?
I tried to add this to my code but I could not get it to work.
I am getting everything from a table with the following php:
$result = mysql_query("SELECT * FROM voterecords");
$data = array();
while ( $row = mysql_fetch_row($result) )
{
$data[] = $row;
}
echo json_encode($data);
which outputs the following if I navigate to that php page:
[["68","1234","0","1234",""],["69","added with ajax","0","this item was added using ajax",""]]
The format of the above is as follows:
id, title, votes, description, owner
I think that bit all works but I cant be sure because i dont know what JSON is supposed to look like.
Ok now here is the jquery which is supposed to retrieve the info from the JSON and put it into the html element #output
$(function ()
{
$.ajax({
url: 'retrieve.php', data: "", dataType: 'json', success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
var id = row[0];
var name = row[1];
var votes = row[2];
var info = row[3];
$('#output').append("<b>id: </b>"+id+"<b> name: </b>"+name+"<b> votes: </b>"+votes+"<b> info: </b>"+info)
.append("<hr />");
}
}
});
I was expecting this to output all the info but nothing happens.
Your code is fine except you have a missing closing ) from the callback function.
Also, in JavaScript, it's better to place opening braces on the same line, not on the next, as is common in some other languages.
Corrected/cleaned-up code:
$(function () {
$.ajax({url: 'retrieve.php', dataType: 'json'}).done(function(rows) {
for (var i in rows) {
var row = rows[i];
var id = row[0];
var name = row[1];
var votes = row[2];
var info = row[3];
$('#output')
.append("<b>id: </b>"+id+"<b> name: </b>"+name+"<b> votes: </b>"+votes+"<b> info: </b>"+info)
.append("<hr />");
}
});
});

Categories