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!
Related
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"
I have a while loop which loads the posts of the user and when the like button is clicked to get the post id send it to another php page which will process it and update in the database the likes number but I can't get the good id..
My while loop :
while($posts = mysqli_fetch_array($query)){
<div <?php echo "id=".$posts['id'] ?>
<div class="post">
.
.
</div>
</div> }
And the Ajax Request:
var id = "<?php echo $posts['id'] ?>";
$.ajax({
type: 'POST',
url: 'likes.php',
data: {id:id},
success: function(msg){
alert('Success!');
}
});
But it output only the last value of the while loop and I want for every post to get the id when the like button is pressed.Thanks for help!
What you're doing would never work. Since you have multiple IDs, you have to retrieve the ID from the <div> that was clicked on, and pass that to your ajax call, e.g.
<div data-id="42" class="clickme">
<script>
$('div.clickme').click(function (e) {
id = $(this).attr('data-id');
$.ajax( .... use "id" here ... );
}
alternatively, even something like this would help:
<? while(... fetch from db ... ){ ?>
<div onclick="doAjax(<?php echo json_encode($row['id']); ?>)">
<script>
function doAjax(id) {
$.ajax(... use "id" here ...);
}
</script>
I have tried to get this to work for a while now.
When I load new Ajax content into my accordion, then the new content won't work. The preloaded content works just fine, both before and after.
I have added my code here
I know you can't run the script with ajax, since my config and mysql runs local.
Here is my "update-data.php":
<?php
include('../../includes/config.inc.php');
if(isSet($_POST['content']))
{
$content=$_POST['content'];
$name=$_POST['name'];
$query = "INSERT INTO messages(msg,name) VALUES ('$content','$name')";
mysqli_query($sqlCon, $query);
//mysqli_query("insert into messages(msg) values ('$content')");
$sql_in= mysqli_query($sqlCon, "SELECT msg,msg_id,name FROM messages order by msg_id desc");
$r=mysqli_fetch_array($sql_in);
$msg=$r['msg'];
$name=$r['name'];
$msg_id=$r['msg_id'];
}
?>
<div class="accordionButton"><?php echo $msg_id; ?>:<?php echo $name; ?></div>
<div class="accordionContent" style="display: block;"><?php echo $msg; ?></div>
Thanks for your help
Here are the ajax call:
<script type="text/javascript">
$(function() {
$(".comment_button").click(function()
{
var element = $(this);
var boxval = $("#content").val();
var bval = $("#name").val();
var dataString = {content:boxval,name:bval};
if(boxval=='')
{
alert("Please Enter Some Text");
} else {
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
$.ajax({
type: "POST",
url: "<?php echo $total_path.'/update_data.php'; ?>",
data: dataString,
cache: false,
success: function(html){
$("div#wrapper_ac").prepend(html);
$("div#wrapper_ac .accordionButton:first").slideDown("slow");
document.getElementById('content').value='';
document.getElementById('name').value='';
$("#flash").hide();
}
});
}
return false;
});
</script>
You php is fine, just clean your inputs please and look into PDO
You can read about cleaning inputs here and PDO here
In your js I think your problem is your on statement
$('.accordionButton').on('click', function() {
// DO stuff
});
I think it's just not bubbling up the DOM far enough to capture new data, it's adding he click event onto all accordion buttons and listening for them.
Change it to this
$('#wrapper_ac').on('click', '.accordionButton', function() {
// DO stuff
});
This places the listener on #wrapper_ac so any click events that happen underneath will be caught.
Hope this helps
Edit: For more info on PDO check this site http://www.phptherightway.com/#databases
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']
?>
I have a problem about which I am very confused. I have a select box with s dynamically generated using a mysqli query:
$result = mysqli_query($db, "SELECT * FROM `users` WHERE `user_id` > 0");
echo '<html><form name="contacts" method="post"><select name="contacts"><option value="Contact list" onchange="func()">Contact List</option>';
while($row = $result->fetch_assoc()){
echo '<option value = '.$row['user_name'].'>'.$row['user_name'] . '</option>';
}
echo '</select></form>';
I am completely new to AJAX, but I need to use jquery and ajax to pass the this.value variable to a php variable for use in a later query.
Here is my script (most of which was found online):
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
$("#contacts").change(function() {
//get the selected value
var selectedValue = this.value;
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
});
</script>
Now, when I click a value in the select box, nothing happens. There are no warnings or errors, etc.
Please help me.
p.s. function.php does exist. It is just a simple echo for now (for testing purposes)
UPDATE: HERE IS FUNCION.PHP:
<?php
/*$val = $_REQUEST['selectedValue'];
echo $val;*/
function function(){
$val = $_REQUEST['selectedValue'];
echo $val;
}
?>
UPDATE: Thank you everyone for all your help. I have now got it to work in that the network section of chrome inspect shows the function.php being requested however I still don't get the echo (I used external .js files to get it to work). My J query function is also successful (the success function echoes into the console)
Your select box has no ID and you are watching the change event of $("#contacts").
Change:
echo '<html><form name="contacts" method="post"><select name="contacts"><option value="Contact list" onchange="func()">Contact List</option>';
to:
echo '<html><form name="contacts" method="post"><select name="contacts" id="contacts"><option value="Contact list">Contact List</option>';
^^^^^^^^^^^^^ here
You also only need one event handler, so I have removed the inline one which doesn't seem to do anything anyway.
Edit: If the select is created using ajax as well, you need event delegation:
$("body").on('change', '#contacts', function() {
^^^^ for example
Edit 2: Your variable is called $_REQUEST['option'] and not $_REQUEST['selectedValue']. You are also not calling your -badly named - function so you will not get any output from php except from an error like Parse error: syntax error, unexpected 'function' ....
Call onchange function in select tag as below
echo '<form name="contacts" method="post"><select name="contacts" onchange="func(this.value)"><option value="Contact list">Contact List</option></form>';
Javascript src should be in head of the html page.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
Add the above one in head of html. Update javacript as below
As onchange function is called in the select tag itself, following is enough
<script>
function func(selectedValue)
{
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
}
</script>
Updated php: If you must want to get value from function, you must call it. Otherwise, simply, you can make as below
<?php
if($_REQUEST['option'])
{
$val=$_REQUEST['option'];
echo $val;
}
?>
In .php file, receive it first-
$val = $_REQUEST['selectedValue'];
echo $val;
set an id attribute in your php code for the select tag and
please don't use the same value for the name attribute in form and select tags !!
just change your function to a 'body'.on, and give your elements an id of 'contacts'
$("body").on('change', '#contacts', function() {
//get the selected value
var selectedValue = $(this).val();
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
});