I need some help with a project. I'm still learning javascript and jquery so bear with me. The website that I'm working on needs to update a database entry when a button is clicked, the button content is also queried from the database.
First database query to get the buttons:
<?php
$freq_sql = "SELECT freq FROM disc_freq WHERE in_use='0'";
$result_freq = $connection->query($freq_sql);
echo "<h5>Available frequencies</h5>";
while($row = mysqli_fetch_array($result_freq)){
$set_freq=$row[0];
?>
<a id='button' class='w3-bar-item w3-button'><?php echo $set_freq ?></a>
Then the ajax script I tried but there is something wrong with it
$(document).ready(function(){
$("#button").click(function(){
$.ajax({
url: "set_freq.php",
type: "POST",
data: {"set_freq":<?php echo $set_freq ?>},
success: function(data){
data = JSON.toString(data);
}
});
});
});
Finally the php file
<?php
session_start();
include("konf.php");
if(isSet($_POST['set_freq'])){
$update_sql="UPDATE disc_freq SET in_use = '1', working_usr='".$_SESSION['username']."' WHERE freq='".$_POST['ins_freq']."'";
$update_run=mysqli_query($connection,$update_sql);
}
?>
For some the first button when clicked on initiates same number ajax calls of how many buttons have been displayed. Others won't do anything.
The php code does work but the only problem is the ajax call and I haven't found a solution yet so any help is appreciated.
please update code as in your code there is error in ajax script in js
change
you can change code from
data: {"set_freq":<?php echo $set_freq ?>},
to
data: {"set_freq":'<?php echo $set_freq ?>'},
First of all you should prevent your page to refresh because you are clicking on a tag so.
You should send your data with #pritamkumar's answer or also send like my answer.
$(document).ready(function(){
$("#button").click(function(event){
var data=$(this).text();
event.preventDefault()
$.ajax({
url: "set_freq.php",
type: "POST",
data: {"set_freq":data},
success: function(data){
data = JSON.toString(data);
}
});
});
});
As per your comment that there are many links than you should change your selector. Like as below
<a class='button' class='w3-bar-item w3-button'><?php echo $set_freq ?></a>
And also change JS code
$(".button").click(function(event)
there is always passed the same value to ajax
data: {"set_freq":<?php echo $set_freq ?>},
in html change
<a id='button' class='button w3-bar-item w3-button' data-freq='<?php echo
$set_freq ?>'><?php echo $set_freq ?></a>
in js
$(document).ready(function(){
$(".button").click(function(){
$.ajax({
url: "set_freq.php",
type: "POST",
data: {"set_freq":this.data('freq')},
success: function(data){
data = JSON.toString(data);
}
});
});
});
i didn't test it - writing from "memory"
Related
I have the following dropdown list which changes the output of <div id="item"></div> with ajax when select option is changed. I'm not using select2.
<?php
$biqsQuery = "SELECT biq.biqid, biq.name FROM biq";
$biqs = $db->query($biqsQuery);
?>
<select name="itemselector" id="itemselect">
<?php foreach ($biqs ->fetchAll() as $biq): ?>
<option value="<?php echo $biq['biqid']);?>">
<?php echo e($biq['name']);?>
</option>
<?php endforeach; ?>
</select>
<div id="item"></div>
PHP File:
if(isset($_GET['itemselector'])){
$biqQuery = "SELECT biq.biqid, biq.name, biq.img
FROM biq
WHERE biq.biqid= :biqid ";
$biq= $db ->prepare($biqQuery);
$biq->execute(['biqid' => $_GET['itemselector']]);
$selectedBiq=$biq->fetch(PDO::FETCH_ASSOC);
echo '<img src="'. $selectedBiq['img']. '">';
}
Javascript File:
$('#itemselect').on('change',function(){
var self = $(this);
$.ajax({
url: '../helpers/biq.php',
type: 'GET',
data: {itemselector : self.val()},
success: function(data){
$('#item').html(data);
}
});
});
It's currently succesfully changing the output, no problem on that part.
But when the page is first loaded, it shows the first value of the table on the dropdown menu, however it doesnt output the image of that first value into <div>.
What i need is; when the page is loaded i need the first entry in the database to be outputted into the <div id="item"></div> automatically.
Any help is appreciated, thanks in advance.
you could write on body load event to accomplish this. please correct if any type mistake will there but this will help you to get it rid
$(document).ready(function(){
var first = $("#itemselect option:first").val();
$.ajax({
url: '../helpers/biq.php',
type: 'GET',
data: {itemselector : first},
success: function(data){
$('#item').html(data);
}
});
});
I'm currently into developing simple 'one score' votting system and I'm facing the problem: though php script workd fine I cant get AJAX updating the answer div without reloading page. I've tried different methods, some do nothing, other reload page, for example, I've tried adding (return: false) after AJAX or PreventDefault in it. Here is html and php index page:
<body>
<div align="center">
<h3>Voting with jQuery, Ajax and PHP</h3>
<?php
include('config.php');
$sql=mysqli_query($bd, "SELECT * FROM messages LIMIT 9");
while($row=mysqli_fetch_array($sql))
{
$msg=$row['msg'];
$mes_id=$row['mes_id'];
$total_score=$row['total_score'];
?>
<div id="main">
<div class="box1">
<img class='image'src="img/thumbsup.png">
<span class='this'><?php echo $total_score; ?></span><div class='tr'></div>
<img class='image' src="img/icon-down.png"></div>
<div class='box2' ><?php echo $msg; ?></div>
</div>
<?php
}
?>
</div>
</body>
And here is my working up_vote.php (down_vote.php is almost same, so I wont add it)
<?php
include("config.php");
$ip=$_SERVER['REMOTE_ADDR'];
if($_POST['id'])
{
$id=$_POST['id'];
$ip_sql=mysqli_query($bd,"select ip_add from Voting_IP where mes_id_fk='$id' and ip_add='$ip'");
$count=mysqli_num_rows($ip_sql);
$sql = "update Messages set total_score=total_score+1 where mes_id='$id'";
mysqli_query($bd, $sql);
$sql_in = "insert into Messages (mes_id_fk,ip_add) values ('$id','$ip')";
mysqli_query($bd, $sql_in);
$count=mysqli_num_rows($ip_sql);
}
?>
And finally, the complete JQUERY - AJAX script (this's my problem - need to show the results in (div class = 'this') without refreshing the page):
$(function() {
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if(name=='up')
{
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success:function(data){
$(".this").append(data);
},
complete: function() {alert('complete');};
});} else
{
$(this).fadeIn(200).html('<img src="img/icon-down.png" align="absmiddle" style="height: 10px;width:10px;">');
$.ajax({
type: "POST",
url: "down_vote.php",
data: dataString,
cache: false
}).done(function ( data ) {
$('.this').append(data);
});
}
return false;
});
});
I have spent whole my day and I know the solution is obvious, Im just really new in this all and so I would appreciate any helpful response. Thanks in advance.
I have added this code to up_vote.php at the buttom:
$result=mysqli_query($bd, "select total_score from Messages where mes_id='$id'");
$row=mysqli_fetch_array($result);
$up_value=$row['total_score'];
echo $up_value;
Thanks to all of you guyz!!! It works now! The problem was that php script didnt return anything!!! As I though - obviouse))) THANKS!
HAve NEW PROBLEM NOW - WHEN I CLICK ON ICONS IT UPDATES ALL OF THEM!! IN EVERY DIV! I VOTE FOR ONE THING - AND IT ADDS VOTES FOR EACH ONE!! whats wrong with that?
I have a script that copies an entire div into a variable. It works when I alert the data, but It wont work when I try to echo it in php.
<script>
var vin = "<?php echo trim($vin1); ?>";
function orderImage(){
var orderIm=$('<div/>').append($('#image-dropzone').clone()).html();
$.ajax({
type: 'POST',
url: 'orderImage.php?id='+vin,
data: {ordering:orderIm},
dataType: 'html'
})};
</script>
And my php:
<?php
echo $_GET['id'];
echo '<br />';
echo gettype($_POST['ordering']);
echo $_POST['ordering'];
?>
Output:
JS2YB417785105302
NULL
You can using full post request
<script>
var vin = "<?php echo trim($vin1); ?>";
function orderImage(){
var orderIm=$('<div/>').append($('#image-dropzone').clone()).html();
$.ajax({
type: 'POST',
url: 'orderImage.php,
data: {ordering:orderIm,id:vin}, // added id:vin on POST parameter
dataType: 'html'
})};
</script>
And my php :
<?php
echo $_POST['id']; // converted into $_POST
echo '<br />';
echo gettype($_POST['ordering']);
echo $_POST['ordering'];
?>
when i use the succes function :
var vin = "<?php echo trim($vin1); ?>";
function orderImage(){
var orderIm=$('<div/>').append($('#image-dropzone').clone()).html();
$.ajax({
type: 'POST',
url: 'orderImage.php',
data: {ordering:orderIm,id:vin},
dataType: 'html',
success: function(data) {
alert(data)}
})};
it shows the correct data. i guess it means that its solved. i just dont see it in the php file while i access it via the console log--> double clicking on XHR finished loading.
even tho the variables types shows NULL in the php script, i can still manipulate the content of them and everything is working fine !
hi guys i try to create like button with php and ajax so write this codes but just work in first loop
<?php header('Cache-Control: no-cache'); ?>
<script>
$(document).ready(
function(){
$("#like").click(function(){
$.ajax({
type: "POST",
url: "<?php echo ADDRESS ;?>thank.php",
data: "like="+$("#like").val(),
success: function(result){
$("#result").html(result);
}
});
});
}
);
</script>
<?php
foreach ($this->value['posts'] as $post){
echo $post[1] . $post[0] .$post[2] . $post[3] . '</br>';
echo '<div id="result"></div>';
}
?>
I think the problem is in my #like that repeat and jquery dont know which one is our div
ok some one answered my question but id dont know why deleted :O
any way he or she writed
$(this)
thanks!
your code not worked but help me to fix that ok problem was in my button value ! all the buttons returned value for the first loop so i changed the js code to this
<script>
$(document).ready(
function(){
$(".like").click(function(){
var spdiv = ".result" + $(this).val();
$.ajax({
type: "POST",
url: "<?php echo ADDRESS ;?>thank.php",
data: "like="+$(this).val(),
success: function(result){
$(spdiv).html(result);
}
});
});
}
);
</script>
and i use class instead of id .
IDs are Identifiers - meaning they must be unique! Also your script is messy and I guess you didn't mention there are many like buttons on the page, right?
Try this PHP code:
foreach ($this->value['posts'] as $index=>$post) {
echo '<div class="comments">';
echo $post[1] . $post[0] .$post[2] . $post[3] . '</br>';
echo '<button class="like" data-id="<?php echo $index; ?>">LIKE</button>';
echo '<div class="result"></div>';
echo '</div>';
}
And this javascript:
$(document).ready(function(e) {
$("div.comments").on("click", "button.like", function(e) {
$.ajax({
type: "post",
url: "<?php echo ADDRESS ;?>thank.php",
data: {
like: $(this).attr("data-id")
},
success: function(data, textStatus, jqXHR) {
$(this).siblings(".result").html(data);
}
});
});
The script above will add an event listener to all buttons that have the class like. The $(this) will refer to the like button and the $(this).siblings(".result") will get the result div that is a direct sibling of the like button(!), meaning they both sit in the same <div class="comments">.
I have changed the way you approach DOM elements. I also added a new identifier to your LIKE button so don't forget to change this data-id to suit your needs!
I have a problem to pass value to my php script via Ajax, there is my code :
I send value to ajax via a href link :
After scan directory i get links of my files on href :
<?php echo $file; ?>
My js function to receive value :
function getfilename(content) {
alert(content); // i can see my value here
$.ajax({ //not work
type: 'POST',
url: 'script.php',
data:{song: content},
async: false,
success: function(response) {
alert(response); //nothing
});
}
My script.php
$album = $_POST['song'];
echo $album;
I dont understand why it does not work.
Thank you for your help!
Try changing
<?php echo $file; ?>
To this
<?php echo $file; ?>
Maybe your page is refreshing before the ajax data loads.
When you use the link element it will automatically go to the location in the href after it executes the onclick event. Leaving it empty will reload the page.
I would recommend you to add a "return false;" as the last instruction of the onclick.
<?php echo $file?>
Hope this helps.
Looking to your js code your success callback is missing a "}" in the end of function.
// $file = 'teste';
<?php echo $file?>
function getfilename(content) {
alert(content);
$.ajax({
type: 'POST',
url: 'script.php',
data:{song: content},
async: false,
success: function(response) {
alert('Response: ' + response); //Alerts Result
}
});
}
// Script.php
<?php
echo $_POST['song']
?>