I'm having some trouble with my jquery ajax code.
I have 2 functions, one that will submit a value and other that will update the values in real time.. At least that's what it is supposed to do. :P
So, I have a list that is created throught some PHP code:
<div id="votos">
<ul class="yourvotes">Your votes: 0</ul>
<li class="votesofothers">
User Votes: (0)</br>
User2 Votes: (0)</br>
</li>
</ul>
</div>
And then I have a Ajax call to update the database when one of the links is pressed:
$(function(){
$('.votar').click(function(){
var elem = $(this);
$.ajax({
type: "GET",
url: "votar.php",
data: "id="+elem.attr('iduser'),
dataType:"json",
success: function() {
window.location.reload(true);
}
});
$(document).ajaxStop(function(){
window.location.reload();
});
return false;
});
});
And this would be the code to update the values that appear in "real-time":
function mostrarvotos() {
$('#votos').load('votos.php');
setTimeout('mostrarvotos()',1000);
}
mostrarvotos();
(I originally wanted to update each of the user votes instead of updating the whole div but I couldn't manage to do it.)
So my problem is that when I add the "mostrarvotos()" function to my code the links stop working and just add a # to the url, but if I remove it everything works fine.. If you could help me with this I would greatly appreciate.
That's because you are not prevent the link's original action. The click handler won't catch the event when you refreshed the content with an AJAX request. Try document.on instead of your current handler:
$(document).on('click','.votar',function(e){
e.preventDefault(); //Prevent the default action
var elem = $(this);
$.ajax({
type: "GET",
url: "votar.php",
data: "id="+elem.attr('iduser'),
dataType:"json",
success: function() {
window.location.reload(true);
}
});
$(document).ajaxStop(function(){
window.location.reload();
});
return false;
});
Also note the preventDefault which prevents the defauls link action (the # in your address bar).
You need to delegate your click function because you are adding those links dynamically.
So do something like:
$(function () {
// delegate your dynamically loaded links
$('#votos').on('click', '.votor', function () {
var elem = $(this);
$.ajax({
type: "GET",
url: "votar.php",
data: "id=" + elem.attr('iduser'),
dataType: "json",
success: function () {
window.location.reload(true);
}
});
$(document).ajaxStop(function () {
window.location.reload();
});
return false;
});
});
Related
How can we confirm the deletion of an array element result of an ajax call?
I have an array :
$.ajax({
url: "recursive.php",
method:"POST",
dataType: "json",
success: function(data)
{
$('#treeview').treeview({
data: data
});
}
});
In my recursive.php I have this code:
$arr = array(
'text' => '<img src="img/pdf.png">'.$sub_data["n_doc"].'
'
);
In this <a href, I need to confirm before deleting.
in delete.php i have:
$sql = mysqli_query($conn, ' DELETE FROM saisie WHERE code = "'.$doc.'" ') or die (mysqli_error());
Make another ajax call in the success function:
$(document).ready(function(){
$.ajax({
url: "recursive.php",
method:"POST",
dataType: "json",
success: function(data)
{
$(document).on('click', '.btn_supp', function(){
if(confirm("do you want to delete this file?")){
$.ajax({
url: "delete.php",
method:"POST",
dataType: "json",
success: function(data)
{
alert("deleted");
});
}
});
}
});
$('#treeview').treeview({
data: data,
selectedBackColor: 'rgb(211,211,211)',
selectedColor: '#4A4A49',
enableLinks:true,
collapsedall: true
});
}
});`
The easiest method of accomplishing displaying a confirmation when AJAX adds to the DOM, would be to bind a delegated event listener in your view's DOMReady function.
Since jQuery binds event handlers during the DOMReady state, it will not bind additional elements in the ajax.success function, unless the response includes javascript and the dataType is 'script' or you parse the data variable from the success function and an event is manually added.
This assumes an element with an id="treeview", already exists.
<script type="text/javascript">
jQuery(function($) {
$(document).on('click', 'a[href^="delete.php"]', function(e) {
return window.confirm('Are you sure you want to delete this file?');
});
$.ajax({
url: "recursive.php",
method:"POST",
dataType: "json",
success: function(data) {
$('#treeview').treeview({
data: data,
selectedBackColor: 'rgb(211,211,211)',
selectedColor: '#4A4A49',
enableLinks:true,
collapsedall: true
});
}
});
});
</script>
<div id="treeview"></div>
This works by telling jQuery to monitor all of the clicks inside of the #treeview element, for a triggering element of <a href="delete.php">. Specifically href^="delete.php" means an <a> element, with an href that begins with delete.php. If one is found, the callback function is executed and the confirmation dialog is displayed.
If you add a class attribute to your recursive.php anchor element, you can replace a[href^="delete.php"] with a.classname.
Example https://jsfiddle.net/ub1hw9tn/
$arr = array(
'text' => '<img src="img/pdf.png"><a class="delete" href="delete.php?doc='.$sub_data["code"].'" target="_blank">'.$sub_data["n_doc"].'</a>'
);
Then in your javascript
$(document).on('click', 'a.delete', function(e) {
if (!window.confirm('Are you sure you want to delete this file?')) {
e.preventDefault();
}
});
I am trying to update the user input ratings through ajax call. This one alert(performance_rating) returned the user input ratings properly. But, I have a problem with my url. it won't call user_ratings.php. I don't know why? I have tried alert function in user_ratings.php page. But, it won't alert.
I have the user_ratings.php file in siteurl.com/include/pages/user_ratings.php
How do I call my php file properly?
ajax request
$(function () {
$('#form').on('submit', function (e) {
performance_rating = $('input:radio[name=rating]:checked').val();
e.preventDefault();
$.ajax({
type: 'POST',
url: 'user_ratings.php',
data: {
rating: performance_rating
},
success: function() {
alert(performance_rating);
}
});
});
});
If you are sending your ajax request from localhost to your domain, then you have to use full site url in your ajax call as follows
$(function () {
$('#form').on('submit', function (e) {
performance_rating = $('input:radio[name=rating]:checked').val();
e.preventDefault();
$.ajax({
type: 'POST',
url: 'http://domain.com/include/pages/user_ratings.php',
data: {
rating: performance_rating
},
success: function() {
alert(performance_rating);
}
});
});
});
first its better you do this
define("URL", "http://siteurl.com/");
Then in the ajax url section write
url: '<?php echo URL ;?>includes/pages/user_ratings.php',
Put your FQDN (e.g. www.yoururl.com) before the user_ratings.php in your jQuery Ajax call. So change to this:
$(function () {
$('#form').on('submit', function (e) {
performance_rating = $('input:radio[name=rating]:checked').val();
e.preventDefault();
$.ajax({
type: 'POST',
url: 'http://www.yoururl.com/user_ratings.php',
data: {
rating: performance_rating
},
success: function() {
alert(performance_rating);
}
});
});
});
I have a page with 2 divs..each div have to call an ajax function on load. However, after I open either one of the divs, the ajax of the other div will not work.
*#div_remove lets the user delete a user from the system and display the existing ones in another div within #div_remove thru ajax.
#div_logs displays all transactions done in the system and displays them on another div within #div_logs through ajax.*
Here is the jQuery code:
$("#remove_admin").on("click",function(){
$("#light").fadeIn("slow");
$("#div_remove").slideDown("slow");
showtable();
event.preventDefault();
$("#btnRemove").click(function(){
var text = $.ajax ({
type: "GET",
url: "delUserProcess.php?keyword="+$("#txtRemove").val()+"&table=users&field=username",
async: false,
}).responseText;
alert(text);
showtable();
event.preventDefault();
});
});
//VIEW USER LOGS
$("#logs").on("click",function(){
$("#light").fadeIn("slow");
$("#div_logs").slideDown("slow");
showLogs();
event.preventDefault();
});
$("#txtUser").on("keyup",function(){
showLogs();
event.preventDefault();
});
$(".date").on("change",function(){
showLogs();
event.preventDefault();
});
});
function showtable(){
$.ajaxSetup ({
cache: false
});
$.ajax({
type: "GET",
url: "showAdmin.php",
async: false,
success:function(text){
$("#tblUsers").html(text);
}
});
}
function showLogs(){
$.ajaxSetup ({
cache: false
});
var cBy = $("#txtUser").val();
var sDate = $("#startDate").val();
var eDate = $("#endDate").val();
$.ajax({
type: "GET",
url: "showLogs.php?sDate="+sDate+"&eDate="+eDate+"&createdBy="+cBy,
async: false,
success: function(text){
$("#tblHistory").html(text);
}
});
}`
the original code used .click(), .keyup() and .change().. I already tried using .live() and .on() but it is still not working. please help.
You need to bind the events under the showLogs file.
Because whenever you call the delete or other events, it replace the html with the updated one. and the events lots it existance. So you need to call them in the showLogs file.
I'm using jquery to load an external page and display it in a DIV called View.
I have 2 buttons Go & Stop.
This is working, but when I click stop it can take a few seconds.
Any way to make it stop straight away ?
$("#Go").click(function () {
$("#view").load("test.php");
refreshId = setInterval(function() {
$("#view").load("test.php"); }, 1000);
});
$("#Stop").click(function () {
clearInterval(refreshId); $("#view").stop();
$.ajax({ url : 'new.php' });
} });
Thanks :)
you can try:
var xhr = $.ajax({
type: "POST",
url: "test.php",
data: "name=John&location=Boston",
success: function(msg){
$("#view").html(msg);
}
});
and stop call:
//kill the request
xhr.abort()
I created a simple voting system (+ and -) on Ajax for users comments. One page have 50 posted comments and you can vote for each "plus" or "minus". This data sent through the PHP script to the database. However, if a user votes, the PHP script is called 50 times - it is visible in Chrome developer tool. There are errors - more value than expected. Here is my code (two DIV buttons and the script).
Tell me please how to change the code to the script (up_vote.php or down_vote.php) is called only once.
<script type="text/javascript" src="raitings/jquery.js"></script>
<script type="text/javascript">$(function() {$(".vote").click(function() {
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if(name=='down')
{
$(this).fadeIn(200).html('<img src="raitings/dot.gif" align="absmiddle">');
$.ajax({type: "POST", url: "raitings/down_vote.php", data: dataString, dataType : "html", cache: false, success: function(html)
{ parent.html(html);}
});
}
else
{
$(this).fadeIn(200).html('<img src="raitings/dot.gif" align="absmiddle">');
$.ajax({type: "POST", url: "raitings/up_vote.php", data: dataString, dataType : "html", cache: false, success: function(html)
{ parent.html(html);
} });
}
return false;
});
});
</script>
//php code below;
echo "<div class=\"box1\"><div class=\"up\">".$up."</div>"
."<div class=\"down\">".$down."</div></div>\n";
Using jQuery, it's important to know that events are stackable, even if the event is exactly the same. For example:
$(".vote").click(function() { alert("hi"); });
$(".vote").click(function() { alert("hi"); });
$(".vote").click(function() { alert("hi"); });
If we ran these three lines verbatim, we'll have 3 different events attached. That is, we would get 3 alerts one after the other by clicking in an element with the vote class.
In addition, oftentimes it happens that pages being loaded through ajax carry the same <script></script> block of the parent page, and when this is the case, the code is inadvertently being processed again and again with every ajax call.
While I was not able to pinpoint exactly how is this happening by the code you provided, it seems this is the most likely scenario: your click handler event is being loaded several times, and as a result one click triggers several ajax calls.
The quick and dirty solution when this presents as I mentioned in the comments is replacing:
$(".vote").click(function()
By:
$(".vote").unbind("click").click(function()
Which thanks to the unbind function forces it to discard previously attached events every time a new one is attached, thus preventing it from having more than one event attached no matter how many times the code is processed.
While this will work, the better solution is, of course, to locate where is the js code being loaded multiple times and make sure it is loaded just once.
$(".vote").each(function () { $(this).click( clickHandler .... etc should solve your problem.
I don't fully understand how your version works but I would do it similar to this:
+
-
Where 200 would be the unique id of the comment.
Then have a vote_up() and vote_down() function defined in a JavaScript and add your ajax requests there.
That way it should not call the script more than once when +/- button is clicked.
You can disabled button before send you ajax request.
// Sample:
$(function() {
$(".vote").click(function() {
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
parent.fadeIn(200).html('<img src="raitings/dot.gif" align="absmiddle">');
if(name=='down')
{
$.ajax({
type: "POST",
url: "raitings/down_vote.php",
data: dataString,
dataType : "html",
cache: false,
beforeSend: function() {
parent.attr("disabled", true);
},
success: function(html) {
parent.html(html);
}
});
} else {
$.ajax({
type: "POST",
url: "raitings/up_vote.php",
data: dataString,
dataType : "html",
cache: false,
beforeSend: function() {
parent.attr("disabled", true);
},
success: function(html) {
parent.html(html);
}
});
}
return false;
});
});