I am stuck on this. I have an ajax function posting to php. The post function is working fine. I just want css to toggle on and off with each click while posting with each click.
When I click the '.fav-btn' button the first time I want 'fav-h' to be added to the class for styling. Also post to the php script.
When I click the '.fav-btn' button the second time I want 'fav-h' to be removed and button returns to original style. Also post again to the php script.
I have tried various things including the .removeclass. My code is below, I am not sure how to get the fav-h class style to be removed on the second click.
$(document).ready(function(){
var pageID = <?php echo $pageID ?>;
var user_id = <?php echo $user_id ?>;
$('.fav-btn').click(function(){
$(this).addClass('fav-h');
$.ajax({
type:"POST",
url:"../ajax.php",
data: { act: 'fav', pageID: pageID, user_id: user_id },
success: function(){
}
});
});
});
$(document).ready(function(){
var pageID = <?php echo $pageID ?>;
var user_id = <?php echo $user_id ?>;
$('.fav-btn fav-h').click(function(){
$('.fav-btn fav-h').removeClass('fav-h');
$.ajax({
type:"POST",
url:"../ajax.php",
data: { act: 'fav', pageID: pageID, user_id: user_id },
success: function(){
}
});
});
});
Use $.toggleClass() to just have one block of code:
$(document).ready(function(){
var pageID = <?php echo $pageID ?>;
var user_id = <?php echo $user_id ?>;
$('.fav-btn').click(function(){
$(this).toggleClass('fav-h');
$.ajax({
type:"POST",
url:"../ajax.php",
data: { act: 'fav', pageID: pageID, user_id: user_id },
success: function(){}
});
});
});
PS: your code was not working because you used $('.fav-btn fav-h'):
<div class="fav-btn">
<fav-h></fav-h> <!-- This is what this selector leads to -->
</div>
instead of the correct selector $('.fav-btn.fav-h'):
<div class="fav-btn fav-h"></div> <!-- Found the right one! -->
It looks like it is the same ajax call either way. You can probably just bind to the button once. Also, you might want to only update the class if the post was successful.
$(document).ready(function(){
var pageID = <?php echo $pageID ?>;
var user_id = <?php echo $user_id ?>;
$('.fav-btn').on('click', function(){
var $t = $(this);
$t.addClass('fav-saving');
$.ajax({
type:"POST",
url:"../ajax.php",
data: { act: 'fav', pageID: pageID, user_id: user_id },
success: function(){
$t.toggleClass('fav-h');
},
complete: function(){
$t.removeClass('fav-saving');
}
});
});
});
Related
I want to poulate cities on behalf of selected state in select box. I am able to get the id of the selected state but unable to pass that state id to php function to get array of dependent cities. All this is in wordpress.
<script type="text/javascript">
$(document).ready(function()
{
function ajaxSubmit(){
var stateId = $(this).val();
// alert("SID"+stateId);
jQuery.ajax({
type:"POST",
action:'getDist',
data: stateId,
url: "<?php echo $adminUrl; ?>"
});
}
$('#billing_state').on("change", ajaxSubmit);
});
</script>
Above ismy ajax call and below is my php function to which i want to pass state id..
<?php
function getDist($id){
global $wpdb;
$dists = $wpdb->get_results("select name from cities where state_id = ".$id);
if($dists === FALSE):
echo $wpdb->error;
else:
foreach($dists as $dist){
echo"<option value=".$dist->name.">".$dist->name."</option>";
}
endif;
}
add_action('wp_ajax_getDist', 'getDist');
?>
after this i get nothing in cities select box..
Not totally wrong approach...I was just missing the acction function in ajax..
here's update..
$.ajax({
type:"POST",
url:"<?= admin_url('admin-ajax.php') ?>",
data:({
action:'get_city',
state_id:stateID
}),
success:function(response){
$("#billing_city").html(response);
}
});
After a user clicks a div this javascript function runs:
$('.test').click(function(e)
{
e.preventDefault();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {"id": "<?php echo $rows['id']?>"},
success:function(data){
window.location.href = 'index.php';
}
});
});
I want to pass in an ID associated with the div the user clicks into my ajax.php file where this code runs:
<?php
session_start();
//connect to db here
$_SESSION['id'] = $_POST['id'];
?>
However this is not working. To expand further what I did to pass get the rows['id'] variable is run this SQL code:
$sql_select = "SELECT id FROM ids WHERE id = '$id'";
$results_select = $conn->query($sql_select);
I then outputted a bunch of divs with id's corresponding to them:
<?php
while ($select_rows = mysqli_fetch_array($results_select))
{
echo "<div class = 'test'></div>";
}
?>
Does anyone know how I can accomplish this?
Use data attributes:
Try:
<?php
while ($select_rows = mysqli_fetch_array($results_select))
{
echo "<div data-id='".$rows['id']."' class = 'test'></div>";
}
?>
js:
$('.test').click(function(e)
{
e.preventDefault();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {"id": $(this).attr('data-id')},//fetch the data attribute
success:function(data){
window.location.href = 'index.php';
}
});
});
Please check your JS code for data: {"id": "<?php echo $rows['id']?>"}. This line may not be able to pass your actual value so store it into div with id attribute and get it by jQuery and pass it.
JS:
$('.test').click(function(e)
{
dataValue = $(this).attr('id');//Get user clicked div id attribute value...
e.preventDefault();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {"id": dataValue},
success:function(data){
window.location.href = 'index.php';
}
});
});
PHP:
With above JS code you need to make some change for PHP code as well:
while ($select_rows = mysqli_fetch_array($results_select))
{
echo "<div class = 'test' id='". $select_rows['id'] ."'></div>";
}
Please confirm this code by print_r($_POST); on AJAX post handler page. This will print the POST data requested by AJAX code.
Let me know if there is any concern regarding this.
I m creating like and unlike button for my website , at my local server i used seprate file it it working fine but when i install at my website then it is not working properly.
I m Fetching some information using this code from url bar
<?php
error_reporting (0);
include "includes/session.php";
include 'database/db.php';
extract($_REQUEST);
if(isset($_GET["i"]))
{
$pid=($_GET['p']);
$lid=($_GET['i']);
}
?>
<?php
$likquery = mysql_query("select * from likes where userid=$id and postid=$lid");
if(mysql_num_rows($likquery)==1){
?>
<a class="unlike" id="<?php echo $lid ?>">UnLike</a> <span class="like_update" id="<?php echo $lid ?>"></span>
<?php }else{?>
<a class="like" id="<?php echo $lid ?>">Like</a>
<?php
}?>
AFTER this I use script
<script src="js/jquery-1.8.3.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$('body').on('click','.like',function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=<?php echo $id ?>';
$.ajax({
type: "POST",
url: "like_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('UnLike').addClass('unlike').removeClass('like');
}
});
})
$('body').on('click','.unlike',function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=<?php echo $id ?>';
$.ajax({
type: "POST",
url: "likeun_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('Like').addClass('like').removeClass('unlike');
}
});
})
});
</script>
And I m not getting any response but when i use
<script src="js/jquery-1.8.3.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$(".like").click(function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=<?php echo $id ?>';
$.ajax({
type: "POST",
url: "like_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('UnLike').addClass('unlike').removeClass('like');
}
});
})
$(".unlike").click(function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=<?php echo $id ?>';
$.ajax({
type: "POST",
url: "likeun_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('Like').addClass('like').removeClass('unlike');
}
});
})
});
</script>
only once it is changing the value
Ok, the second version works only once, because at the beginning, the event is on the button, then you re-render the button by changing it's class and text, so the events get unbinded.
Same is for the 1st version. Jquery says: Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().... If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page.
So re-bind the events after changing the button.
I suggest something like this:
function bindEvents() {
$('.like').off().on('click', function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=' + <?php echo $id ?>;
$.ajax({
type: "POST",
url: "like_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('UnLike').addClass('unlike').removeClass('like');
//rebind events here
bindEvents();
}
});
$('.unlike').off().on('click', function(){
var postId = $(this).attr('id');
var postData = 'postid='+postId+'&uid=' + <?php echo $id ?>;
$.ajax({
type: "POST",
url: "likeun_notes",
data: postData,
cache: false,
success: function(){
$('#'+postId).text('Like').addClass('like').removeClass('unlike');
//rebind events here
bindEvents();
}
});
}
$(document).ready(function(){
bindEvents();
});
Also notice that in var postData = 'postid='+postId+'&uid=<?php echo $id ?>'; code, the php part won't be treated as php. It will be just a string. So replace that part with the following, assuming that the code is located inside a php file:
var postData = 'postid='+postId+'&uid=' + <?php echo $id ?>;
I have problem with deleting records from database, using ajax and jquery. If i click to button nothing happens. there is my css:
<button class='delete_p' id_p='<?php echo $post_id; ?>'>x</button>"
<script type="text/javascript" src="jquery-1.11.1.js"></script>
<script src="delete_post.js"></script>
and there is ajax that i'm using:
$(document).ready(function(){
$('.delete_p').click(function(){
var del_id = $(this).attr('id_p');
$.ajax({
type:'POST',
url:'delete_post.php',
data:'delete_id='+del_id,
});
});
});
and there is delete_post.php that i'm using:
<?php
include 'esas/core/database/connect.php';
$id = $_POST['delete_id'];
$query = "DELETE FROM `status` WHERE `id` = '$id'";
?>
data shouldn't be a string but a JavaScript object:
$.ajax({
type: 'POST',
url: 'delete_post.php',
data: {
delete_id: del_id
}
});
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