Jquery ajax running twice - javascript

So, I have this problem. I am using a plugin named jRating, it is esentially a rating system in jquery. My problem is, that onClick, the ajax request fires twice.
After searching a lot, I tried those things:
I checked and double checked that the $(document).ready(function(){} and the jQuery shortcut $(function() {}); is not twice in the page.
I also checked that the id of the call is unique.
So, here is my code:
jQuery:
$("#rating").jRating({
step:true,
length : 5,
canRateAgain : true,
nbRates : 3,
onClick : function(element,rate) {
var data = (rate, 1);
$.ajax({
url: 'application/index/rate',
type: 'POST',
dataType: 'x-www-form-urlencoded',
async:false,
contentType: 'application/x-www-form-urlencoded',
data: rate,
success: function () {
console.log('SUBMIT WORKS');
},
error: function () {
console.log('There is error while submit');
}
});
}
});
pHTML:
<div id="rating" data-average="<?=$average //note that this is working everytime!?>" data-id="1"></div>
Thanks for any inputs!
EDIT: JsFiddle: http://jsfiddle.net/Je79U/ ;
To recreate the problem, click run, then go to console/network, clear all contents, then click anywhere on the yellow/orange bar, to rate, and see what happens. Thanks again for your time!

with reference of http://demos.myjqueryplugins.com/jrating/ , already jRating will work as ajax. So, that it takes ajax running twice
Please check their demo website clearly.
In that once you rate it will update the records to http://demos.myjqueryplugins.com/jrating/php/jRating.php
and use the following version of jRating
https://github.com/alpixel/jRating

Related

ajax post working on chrome but not working on firefox and safari

I've encountered an issue where a jquery ajax post method works on chrome but does not work on safari or firefox. I've looked through all the other similar posts and they don't solve the problem. Whenever I run the ajax code, it just returns the entire HTML of the page the form is found on.
Here's my javascript:
$("#piece-form").submit(function(e)
{
e.preventDefault();
// gets which submit button was clicked
var selectedButton = $(this).find("input[type=submit]:focus");
var url = selectedButton.attr("name");
var formData = new FormData(this);
$.ajax
(
{
type: "POST",
url: url,
data: formData,
cache: false,
processData: false,
success: function(data)
{
if(data == "Success!")
{
$("#error-box").css("display", "none");
$("#success-box").html("Success! Publishing...");
$("#success-box").css("display", "block");
}
else
{
$("#success-box").css("display", "none");
$("#error-box").html(data);
$("#error-box").css("display", "block");
}
}
}
)
});
No matter the content of the PHP file the function points to, it doesn't work as planned. I've tried making a PHP file with a single echo line and I still run into the same problem. I've implemented an error block in the ajax as well and it returns nothing. I also don't receive an error in the console other than: "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience. For more help http://xhr.spec.whatwg.org/" in Firefox
Edit: I've added contentType:false and it still isn't functioning properly on Firefox and Safari
Have you tried wrap your code in document ready?
Also as much as i know now it is correct to use on():
$( document ).ready(function() {
$("#piece-form").on('submit', function(e){
//your main code here
});
});
For now it does not looks like there would be any issue. ..
I finally found the answer.
The error is in the following line of code:
var selectedButton = $(this).find("input[type=submit]:focus");
var url = selectedButton.attr("name");
For some reason, Firefox and Safari don't properly get the value of "selectedButton" (although Chrome does) resulting in the url variable being incorrectly set. In order to circumvent this, I did the following:
$(".piece-button").click(function (){
url = $(this).attr("name");
})
I needed the submittedButton method because I had two submit buttons for the form and was trying to find which one was clicked. This alternate method does that and is transferrable across all three browsers I have tested. This may not be an optimal solution to the two button submit issue but it worked for me and now the ajax works without a hitch.
Though you have got the solution but from interest I am sharing mine as I have just encountered same problem and got the workaround by adding event.preventDefault(); after success. Example code is given
$(document).ready(function() {
$('form').on('submit', function(event) {
$.ajax({
data: {
name: $('#nameInput').val(),
email: $('#emailInput').val()
},
type: 'POST',
url: '/post_for_db',
success: function(data) {
console.log(data)
$("body").html(data);
// This will navigate to your preferred location
document.location = '/render_table_from_db';
},
event.preventDefault(); // solution is this for me
});
});

jQuery AJAX with PHP Session

I have a PHP page with a table. Some rows may have a clickable .ggcam "td" element.
This is the jQuery code:
$(".ggcam").click(function(){
$('#campagne').load(document.URL + ' #campagne');
var id = $(this).attr('id');
$('.loader').show();
$.ajax({
type: "POST",
url: "gestione_commesse/redirect.php",
data: {'tag': id},
success: function(whatigot) {
},
complete: function(){
$('.loader').fadeOut();
}
});
});
The code in "redirect.php" is the following:
session_start();
$_SESSION['tag']=array();
unset($_SESSION['tag']);
$_SESSION['tag']=$_POST['tag'];
This code works well, the value is stored correctly in $_SESSION variable.
The problem is that it does not always work. I don't understand, the array variable $ _SESSION is not updated on every click, and I think it's a problem of the ajax call.
Thank you for help!
I think I found the solution.
I moved the load() call after the ajax call.
It seems to work, thanks for support.

From AJAX var to PHP variable getting the success code right

I have been working on this for a while and posted several related topics about it, but this is slightly different question. I have the following AJAX code with some html forms below it with in #container and .myselect is the class of a drop-down box. When I change the value in the box I want to be able to then use that value on other fields below the select. The AJAX code kinda works in that the alert shows the right value when changed but as you can see I have tried lots of success functions but no luck. The closest is
$('#reloadtest').html(data); which will show the value in my PHP and every time I change the value from then on it will change alot, but it reloads the page within the container.
Basically I want to know how I can reload the data but not the whole html/page so I can use the value of the drop down in my PHP.
$(document).ready(function(){
$('#container').on( 'change', '.myselect', function() {
var orderidVal = $(this).val();
alert(orderidVal);
$.ajax({
type: "POST",
data: { orderidType : orderidVal },
success: function(data) {
//$('#container').reload('#container', function() {});
//$('#quoteselect').reload('#quoteselect', function() {});
//$('#container').load('orders.php #container', function() {});
//$('#quoteselect').load('orders.php #quoteselect', function() {});
//$('#testreload').reload('#testreload', function() {});
//location.href = "test2.php"
$('#reloadtest').html(data); //this allows me to use the variable but reloads the whole page within the page
}
})
});
});
If you are doing an ajax-request you have to allocate an URL where to send the request.
If you don't Request anything jQuery reloads the page. As you can see here in the jquery-api-docu the URL is the very first and most important parameter of the request.
$.ajax({
url: "/url/to/the/php/script.php",
success: function(data){
//do something ... with data parameter
}
});
would be the simple way of using ajax-request with javascript.
use two divs - one in which you can put ajax response and in other the remaining HTML code
it reloads your page because you have not specified what page to request.
use the code below and replace /path/to/script to your actual script path
$(document).ready(function(){
$('#container').on( 'change', '.myselect', function() {
var orderidVal = $(this).val();
alert(orderidVal);
$.ajax({
cache: false,
async: true,
type: "POST",
url: '/path/to/script',
data: { 'orderidType' : orderidVal },
success: function(data) {
$('#reloadtest').html(data);
}
});
});
});

Ajax working on pageload but not on button click

I have an ajax query that's working if I call it from onpageload but not if I call it from a button click. Any reason why?
Edit: I've added the events as requested, please be aware I have debugged this and it is getting to the AJAX but just silently skipping it. It will call a failure function if I add one.
function detailsQuery(crn, semester, year, questionId, clickedButton)
{
$.ajax({
url: somebigurlwithnocallback (same domain),
type: "GET",
dataType: "json",
success: function (data) {alert(data)}});
}
-
$(function() {
$(document).delegate(".button", "click", function(){detailsQuery(CRN,Semester,Year,QuestionID, this);});
});
window.onload=(function() {detailsQuery(CRN,Semester,Year,QuestionID, this);});
Did you attempt to check if the click event was even working ? Try this code:
$(".button").live("click", function(){
function detailsQuery(crn, semester, year, questionId, clickedButton)
{
$.ajax({
url: somebigurlwithnocallback (same domain),
type: "GET",
dataType: "json",
success: function (data) {alert(data)}
});
});
});
This appears to be an issue with Google Chrome. If an HTML file is modified and only refreshed (even with ctrl+f5) Chrome does not always process the modified AJAX call properly. I don't have access to server side code so I can't see what's going on there, being a 'GET' not much can be going on. I can only see that it returns 'error'. Closing chrome and re-opening resolves the issue. Why it only happens when the AJAX occurs on a button click is beyond me.
Do this:
Change
$(function() {
$(document).delegate(".button", "click", function(){detailsQuery(CRN,Semester,Year,QuestionID, this);});
});
to
$(document).ready(function(){
$(".button").bind({"click": function(){
function(){detailsQuery(CRN,Semester,Year,QuestionID, this);}
}
});
});
That should resolve the issue.
Hope the explanation is clear and this helps.

multiple jquery html() assignment not working

I want to show the user a "loader" before and during the ajax call. Here's the code (simplified version...)
$(document).ready(function() {
$("#btn").click(function(){
$("#log").html("loading ajax call...");
anotherFunc();
});
});
function anotherFunc(){
$.ajax({
type: "GET",
url: correct_url,
data: data_to_send,
dataType: "jsonp",
success: function(data){
$("#log").html("new html");
}
})
}
the problem is that "loading ajax call..." never appears. I only see "new html" displayed. the singles ajax #log modification call work perfectly alone (without the other)
is there another way to do?
what am I doing wrong?
ps. I also tryed to write in another id (#log2) with the same result.
Most likely everything works just fine, but the AJAX call returns very quickly (especially if you are testing locally). To see if that is the case, just do the following:
$(document).ready(function() {
$("#btn").click(function(){
$("#log").html("loading ajax call...");
setTimeout(function(){anotherFunc();},2000);
});
});

Categories