Jquery click function for a second time do not works - javascript

when user click for a second time click do not work, user need to reload the page again to it works
<script>
$(document).ready(function() {
$("#like_post").click(function(e) {
// $("#like_post").on("click", "#like_post", function (e) {
e.preventDefault();
var post_info = $("#post_info :input").serialize();
$.post("backend/ajax/like_post.php", post_info).done(function(data) {
$("#like_post").html(data);
$("#like").load(location.href+" #like>*","");
}).fail(function() {
//alert("Error submitting forms!");
})
})
})
</script>
this is the backend return from db
if user liked it will show
<div id="like_post><a href="" id="l"><input type="hidden" value="unlike" name="like_button" /><i style="color:red" class="fa fa-heart fa-2x" aria-hidden="true" data-toggle="tooltip" data-placement="top" title="'.$lang['you_liked_it'].'"></i>
</a></div>
else it will show
<div id="like_post"> <a href="" id="l"><input type="hidden" value="like" name="like_button" /><i class="fa fa-heart-o fa-2x" aria-hidden="true" data-toggle="tooltip" data-placement="top" title="'.$lang['like_it'].'"></i>
</a></div>
the same validation is on frontend where is will change the hidden input to like, or unlike , my backend check is fine and returning all ok when I check the html response, but the problem is that jquery do not work when user like and unlike without reload the page, it just get the first click and after that user need to reload the page to it works.
I had a similar issue before and it was something with event delegation.

Use the comment line in your code without "#like_post":
$("#like_post").on("click", function (e) {
});

Related

some portion of jquery in running remaining is not working in code but works in console

I am working on edit username with hide/show text field and, I found some questions for 'js works in console but not in code' but I have different scenario. some part jquery run perfectly, but rest of code is not working in code, it works in console, please help me with that. (I have loaded jquery that's why some code works)
on edit click
Here are the images for buttons
fisrt for edit name
second for close edit button which is not working
//for edit field showing
$(document).on('click', '.edit-nickname', (element) => {
element.preventDefault();
$('.hide-on-cancel').show();
$('.show-on-cancel').hide();
});
//for hiding edit field and display username
$(document).on('click', '.cancel-nickname', (element) => {
element.preventDefault();
// alert('hii');
$('.hide-on-cancel').hide();
$('.show-on-cancel').show();
//(OPTIONAL CODE to ABOVE) IF I UNCOMMENT BELOW 3 LINE THAT WORKS BUT 4th and 5th LINE IS NOT WORKING
// $('#sd-close').addClass('d-none');
// $('#sd-check').addClass('d-none');
// $('#sd-edit').addClass('d-none');
// $('#sd-pen').removeAttr('style');
// $('#text-edit-nickname').removeAttr('style');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="edit-nickname" class="second-text1">
<div class="row" style="padding-left: 50px;width: 90%;margin: auto;">
<span class="show-on-cancel" id="text-edit-nickname" data-toggle="tooltip" data-placement="top" title="{{ \Auth::user()->nickname}}">
{{ucfirst(\Auth::user()->nickname)}}
</span>
<span class="form-group nickname-form-group cust-d-none hide-on-cancel" id="sd-edit">
<input id="new_nickname" class="form-control" style="height: 44px;margin-top: 20px;" name="nickname" type="text" value="{{ \Auth::user()->nickname}}" >
<input id="old_nickname" class="" type="hidden" value="{{ \Auth::user()->nickname}}" >
</span>
<span class="edit-nickname">
<i class="fa fa-pencil ml-4 show-on-cancel" id="sd-pen"></i>
<i class="fa fa-check ml-2 save-nickname cust-d-none hide-on-cancel" id="sd-check"></i>
<i class="fa fa-times cust-d-none cancel-nickname hide-on-cancel" id="sd-close"></i>
</span>
</div>
</div>
First put your script tag at the end of your body tag.
Then add document.ready function to your code like below:
$(document).ready(function(){
$(document).on('click', '.edit-nickname', (element) => {
element.preventDefault();
$('.hide-on-cancel').show();
$('.show-on-cancel').hide();
});
//for hiding edit field and display username
$(document).on('click', '.cancel-nickname', (element) =>{
element.preventDefault();
// alert('hii');
$('.hide-on-cancel').hide();
$('.show-on-cancel').show();
//(OPTIONAL CODE to ABOVE) IF I UNCOMMENT BELOW 3 LINE THAT WORKS BUT 4th and 5th LINE IS NOT WORKING
// $('#sd-close').addClass('d-none');
// $('#sd-check').addClass('d-none');
// $('#sd-edit').addClass('d-none');
// $('#sd-pen').removeAttr('style');
// $('#text-edit-nickname').removeAttr('style');
});
});

Send value from input via url PHP - JS

I want to send the value of one input text by a link to make and insert in other page. I don't wanna use a submit type because these elements are inside a form with submit for another page.
This is my code of devices_insert.php:
<div class="cp_oculta" id="plus1" name="new_fabricant">
<input type="text" id="add_fabricant" name="add_fabricant" placeholder="New Fabricant">
<a href="fabricants_insert.proc.php?link=<?php echo **SOLUTION** ?>" onclick="valor()">
<i class="fa fa-check-square-o fa-2x" aria-hidden="true"></i>
</a>
</div>
I can get the value with a function but I don't know how to send it via url.
<script>
function valor(){
var bla = $('#add_fabricant').val();
}
</script>
And I pretend to send to fabricants.insert.proc.php for make the insert:
<?php
$sql_insert = "INSERT INTO Property (PRP_PRP_TYP_Id, PRP_Value) VALUES ('2', '$_REQUEST[**SOLUTION**]')";
echo($sql_insert);
?>
I have checked before many solutions in stackoverflow but I think are not useful for my case.
I suggest you to use ajax, e.g.:
<script>
$('#add_fabricant').on('blur', function(){
$.post(url, {
'SOLUTION': $(this).val()
}).done(function(rst){
//to do
})
})
</script>
I have solved the problem in a easy way:
<script>
function valor(){
$('#fabricant_link').attr('href', 'fabricants_insert.proc.php?new='+$('#add_fabricant').val());
}
</script>
Now with this script send the variable with the url and I can receive it in the other page (fabricants_insert.proc.php) for insert in the database.
<div class="cp_oculta" id="plus1" name="new_fabricant">
<input type="text" id="add_fabricant" name="add_fabricant" placeholder="New Fabricant">
<a onclick="valor()" id="fabricant_link">
<i class="fa fa-check-square-o fa-2x" aria-hidden="true"></i>
</a>
</div>
I only need to add an id to the link to use the function.

jquery: toggle data from input to text and back

I'm pretty new to Jquery and javaScript, and I am trying to do the following:
I have a text field in a table. I want to be able to change it to a input field, and when the user clicks a button, save it in the db (by using a Ajax call) and change it back to text again.
I've been able to do exactly that, but the strange thing is that it only works once, after saving, you can not edit the same field again, unless I refresh the page.
The HTML is:
<table class="table table-bordered">
<tr>
<td>My data field :</td>
<td id="MyDataField">123 <i class="fa fa-pencil-square-o fa-fw" id="editMyDataField" style='float: right' /></td>
</tr>
</table>
The javascript is:
$('#editMyDataField').on('click', function() {
//First clikck, change the table cell into a input field, with the current text value and change icon
$('td#MyDataField').html($('<input />', {
'value': $('td#MyDataField').text()
}));
$('td#MyDataField').append('<i class="fa fa-check" id="editMyDataField" style="float: right"/>')
//Second click, do something with the vale (for instance Ajax call), change field back to text with the new value, and change icon
$('#editMyDataField').on('click', function() {
alert("Save value in db: " + $('td#MyDataField input').val())
$('td#MyDataField').html($('td#MyDataField input').val() + '<i class="fa fa-pencil-square-o fa-fw" id="editMyDataField" style="float: right"> ');
})
})
I've created a JSfiddle to demonstrate the problem: https://jsfiddle.net/2zkbvhoL/
I have a hunch that by repacing the icon, I'm somehow "losing" the connection to the click function, but am not sure how I should solve it.
I think changing the structure would be a better solution.
Instead of: 123 <i class="fa fa-pencil-square-o fa-fw" id="editMyDataField" style='float: right' />
Why not: <span class="text">123</span><input class="edit" type="text"><button type="button"><i ...></i></button>?
$(function(){
$(".edit-btn").click(function(){
var $field = $(this).closest(".field");
if (!$field.data("editing")) {
$field.data("editing", true);
$field.find(".edit-input").val($field.find(".text").text()).show();
$field.find(".edit-btn").hide();
$field.find(".ok-btn").show();
$field.find(".text").hide();
}
})
$(".ok-btn").click(function(){
var $field = $(this).closest(".field");
if ($field.data("editing")) {
$field.find(".edit-input").attr("disabled", true);
runAjax($field, function(){
$field.find(".edit-input").attr("disabled", false);
$field.data("editing", false);
$field.find(".edit-input").hide();
$field.find(".edit-btn").show();
$field.find(".ok-btn").hide();
$field.find(".text").show();
});
}
})
function runAjax($field, cb) {
//your ajax here. Below is just a delay for demoing
setTimeout(function(){
//If ajax OK, you would want to change the text to the input's value
$field.find(".text").text($field.find(".edit-input").val());
if (typeof cb === "function")
cb();
}, 1000);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div data-editing="false" class="field">
<span class="text">123</span>
<input class="edit-input" type="text" style="display:none">
<button type="button" class="edit-btn">Edit</button>
<button type="button" class="ok-btn" style="display:none">OK</button>
</div>
UPDATE:
See demo here
https://jsfiddle.net/2zkbvhoL/7/
Try using
$('table').on('click','#editMyDataField', function() {
// your code here...
}))
Instead of table you can also use document as well and change it at both the places.
So this code should work for you:
$('table').on('click','#editMyDataField', function() {
//First clikck, change the table cell into a input field, with the current text value and change icon
$('td#MyDataField').html($('<input />', {
'value': $('td#MyDataField').text()
}));
$('td#MyDataField').append('<i class="fa fa-check" id="saveMyDataField" style="float: right"/>')
//Second click, do something with the vale (for instance Ajax call), change field back to text with the new value, and change icon
$('table').on('click','#saveMyDataField', function() {
alert("Save value in db: " + $('td#MyDataField input').val())
$('td#MyDataField').html($('td#MyDataField input').val() + '<i class="fa fa-pencil-square-o fa-fw" id="editMyDataField" style="float: right"> ');
})
});
Changed editMyDataField to be saveMyDataField on the inside of the function.
Although this is just a quick fix to your solution. You can remove the nested event binding and attach the events separately to the both the buttons(the edit and save icons)

PHP & Jquery Refresh id with external file

I'm trying to refresh one ID of my page within the click of a button.
I've tried several ways but none of them work. Although I've created the button to refresh it, it keep the submission of the page (triggering the validation event). So, each time I click that button, he tries to submit the form, validation the inputs instead refresh that div.
Here's my code right now:
function refreshCaptcha() {
$("#captcha_code").attr('src','./inc/captcha.php');
}
<div class="form-group">
<div class="col-xs-4">
<button class="btn btn-sm btn-warning" id="refreshcap" name="refreshcap" onclick="refreshCaptcha();">
<i class="fa fa-refresh push-5-r"></i>
<img id="captcha_code" src="inc/captcha.php" />
</button>
</div>
<div class="col-xs-8">
<div class="form-material floating">
<input class="form-control" type="text" id="cap" name="cap">
<label for="cap">Captcha</label>
</div>
</div>
</div>
Can someone help me trying to get what's wrong?
Thanks.
Assuming that your button is inside the form,
add type in your button
which will stop button from submitting your form
<button type="button" class="btn btn-sm btn-warning" id="refreshcap" name="refreshcap" onclick="refreshCaptcha();">
<i class="fa fa-refresh push-5-r"></i>
<img id="captcha_code" src="inc/captcha.php" />
</button>
other than that you can use javascript return false; in your function end
with js
<script>
$(document).ready(function() {
$("#refreshcap").on("click",function(event){
event.preventDefault();
$("#captcha_code").attr('src','./inc/captcha.php');
});
});
</script>
with this you wont need to call on click event this will do it for you, no matter type is button or submit
I think your JS function should return false; in order to not submit the form.
<script>
function refreshCaptcha() {
$("#captcha_code").attr('src','./inc/captcha.php');
return false;
}
</script>

Audio wont play after loading contents with AJAX

First of all im new to jquery i have tried googling my problem , spent hours to fix this and i couldn't find any , so here i am .
In the below code i have fetched some information ( Songs details ) from database and loaded them to div via ajax .. Up to this point everything works just fine .
script using to load content via AJAX
$(document).ready(function() {
$("#results" ).load( "ajax/profile_ajax.php"); //load initial records
//executes code below when user click on pagination links
$("#results").on( "click", ".pagination a", function (e){
e.preventDefault();
$(".loading-div").show(); //show loading element
var page = $(this).attr("data-page"); //get page number from link
$("#results").load("ajax/profile_ajax.php",{"page":page}, function(){ //get content from PHP page
$(".loading-div").hide(); //once done, hide loading element
});
});
});
<div class="loading-div"><img src="../pagination/ajax-loader.gif" ></div>
<div id="results"></div><!-- content will be loaded here -->
Script im using to play audio
$(function () {
var curAudio;
$(".playback").click(function (e) {
e.preventDefault();
var song = $(this).next('audio')[0];
if (curAudio && song != curAudio && !curAudio.paused) {
curAudio.pause();
$(curAudio).prev().html('<i class="fa fa-play"></i> Play');
}
if (song.paused) {
song.play();
curAudio = song;
$(this).html('<i class="fa fa-pause"></i> Stop');
} else {
song.pause();
curAudio = undefined;
$(this).html('<i class="fa fa-play"></i> Play');
}
curPlaying = $(this).parent()[0].id;
});
});
I have above code to played the fetched music . Now the problem is None of the Buttons are functional even though my code worked fine before i use AJAX .
My Fecthed HTML is like this
<div id="4">
Track Name :- <b>Heros</b>
<br />By :- <a target="_blank" href="../members/profile.php?id=1">USER NAME</a>
<br />
<button class="playback btn btn-primary btn-sm hdnbtn"><i class="fa fa-play"></i> Play</button>
<audio src="../members/memberfiles/1/Heros.mp3">
Your browser does not support HTML5 audio.
</audio>
<a class="btn btn-sm btn-success hdnbtn" href="../members/downloader.php?fld=1&name=Heros.mp3" name="dwn"><i class="fa fa-download"></i> Download MP3</a>
<button class="sharer btn btn-sm btn-danger hdnbtn" type="button"><span class="fa fa-share-alt"></span> Share</button>
<a target="_blank" href="#" class="hide btn btn-sm btn-social btn-facebook socialhdn"><i class="fa fa-facebook"></i> Share on Facebook</a>
<a target="_blank" href="#" class="hide btn btn-sm btn-social btn-twitter socialhdn"><i class="fa fa-twitter"></i> Tweet this </a>
<a target="_blank" href="#" class="hide btn btn-sm btn-social btn-google-plus socialhdn"><i class="fa fa-google-plus"></i> Share on goole</a>
<br />
<i class="fa fa-minus"> Show Less</i>
<input type="hidden" value="Heros.mp3" name="file_name">
<input type="hidden" value="bWVtYmVyZmlsZXMvMS9IZXJvcy5tcDM=" name="link">
What i really need is to play the fetched content using the 2nd script (audio) i posted . i have no idea how to fix this . Tried hours of googling and various suggested methods. None of them worked for me . Please Point out what went wrong . i really appreciate it !
use below code to play audio . you also check Event delegation to attach event to dynamically created element. Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
$(function () {
var curAudio;
$(document).on('click',".playback",function (e) {
e.preventDefault();
var song = $(this).next('audio')[0];
if (curAudio && song != curAudio && !curAudio.paused) {
curAudio.pause();
$(curAudio).prev().html('<i class="fa fa-play"></i> Play');
}
if (song.paused) {
song.play();
curAudio = song;
$(this).html('<i class="fa fa-pause"></i> Stop');
} else {
song.pause();
curAudio = undefined;
$(this).html('<i class="fa fa-play"></i> Play');
}
curPlaying = $(this).parent()[0].id;
});
});

Categories

Resources