Phonegap/Cordova - on("click") not firing - javascript

I'm creating a phonegap app.
This code is going to get by a json, the content on de database. Then I want to insert in the database the vote with the device.uuid. The problem is that the on("click") or on("touchstart") is not firing, not even in the alert(). Please help!!
$(document).ready(function() {
var url = "http://filmpix.esy.es/json.php";
$.getJSON(url, function(result) {
console.log(result);
$.each(result, function(i, field) {
var id = field.id;
$('.music-box').append("<button class='btn btn-default insert' value='" + id + "'>Votar</button>");
});
});
$(".insert").on("touchstart", function() {
alert("asdasd");
var music_id = $(this).val();
var dataString = "music_id=" + music_id;
$.ajax({
type: "POST",
url: "http://filmpix.esy.es/insert.php",
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function() {
$("#insert").val('A votar...');
confirm("Tens a certeza que queres votar nesta musica?");
},
success: function(data) {
if (data == "success") {
alert("inserted");
$("#insert").val('Votado');
} else if (data == "error") {
alert("Não foi possível votar");
}
}
});
return false;
});
});

The return false statement should come after the function's "}" on your touch event.

Related

Handling of click events in jQuery(For Like and Unlike button)

I am trying to create a Like-Unlike system using AJAX and jQuery. The "like" event seems to work properly, but when I want to "unlike" the event is not responding. Any suggestions to solve this problem is appreciated.
$(document).ready(function() {
$(".like").click(function() { //this part is working
var item_id = $(this).attr("id");
var dataString = 'item_id=' + item_id;
$('a#' + item_id).removeClass('like');
$('a#' + item_id).html('<img src="images/loader.gif" class="loading" />');
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(data) {
if (data == 0) {
alert('you have liked this quote before');
} else {
$('a#' + item_id).addClass('liked');
$('a#' + item_id).html(data);
}
}
});
});
$(".liked").click(function() { //this part is not working
var item_id = $(this).attr("id");
console.log(item_id);
var dataString = 'item_id=' + item_id;
$('a#' + item_id).removeClass('liked');
$('a#' + item_id).html('<img src="images/loader.gif" class="loading" />');
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(data) {
if (data == 0) {
alert('you have liked this quote before');
} else {
$('a#' + item_id).addClass('like');
$('a#' + item_id).html(data);
}
}
});
});
});
$(".like") and $(".liked") are retrieved when the document is ready but don't get updated when you add/remove classes from an element.
If you assign a more generic class the vote elements like 'like-toggle' you would be able to do the following:
$(document).ready(function() {
$('.like-toggle').click(function(event) {
if ($(event.target).hasClass('like') {
// Call your unlike code, replace like with liked.
} else {
// Call your like code, replace liked with like.
}
});
});
This will work because the like-toggle class never gets removed from the elements and thus the elements which are present when the document is ready will keep functioning.

Wordpress: Jquery submit event, page reloading instead of firing a document.location.href

So, I have a jQuery submit event handler, that on submit queries a database, and if no records are returned, prevents the form page from reloading, and if records were found, should then redirect the user to another page using document.location.href.
But what is actually happening is that records are being found, and instead of then redirecting the user to another page, the form page itself reloads.
What am I overlooking here?
jQuery('#MyForm').submit(function(e) {
console.log("getUserIDs is successfully hit.");
alert("The submit event has been hit");
var countryVal;
var cityVal;
var townVal;
var categoriesVal;
var serialized = jQuery('#MyForm').serialize();
var url = window.location.hostname;
countryVal = jQuery("#CountryList").val();
cityVal = jQuery("#CityList").val();
townVal = jQuery("#TownList").val();
if (typeof townVal == 'object') {
townVal = "object";
}
categoriesVal = jQuery("#CategoriesList").val();
jQuery.ajax({
cache: false,
type: "POST",
async: false,
url: gymRegions.ajaxurl,
data: {
action: "showcountries",
makeselection: "getUserIDs",
countryID: countryVal,
cityID: cityVal,
townID: townVal,
categoriesID: categoriesVal,
locationHref: url,
serialized
},
dataType: "json",
success: function(data) {
alert("Success of the submit event has been hit.");
localStorage.setItem('dataObjectTemp2', JSON.stringify(data));
var numericRecCount = parseInt(data.c);
jQuery.post('', function(data) {
document.location.href = window.location.hostname + '/index.php/anotherpage/';
});
},
error: function(data, status, error) {
alert("No records were returned for your search. Please make another selection.");
e.preventDefault();
return false;
console.log(data);
console.log(status);
console.log(error);
}
});
});
<form id="MyForm" method="Post">
<input type="submit" name="fl-button" id="fl-button" role="button" value="SEARCH" class="fl-button" disabled="disabled" value="Send" />
</form>
jQuery('#MyForm').submit(function (e) {
e.preventDefault();
var countryVal;
var cityVal;
var townVal;
var categoriesVal;
var serialized = jQuery('#MyForm').serialize();
var url = window.location.hostname;
countryVal = jQuery("#CountryList").val();
cityVal = jQuery("#CityList").val();
townVal = jQuery("#TownList").val();
if (typeof townVal == 'object') {
townVal = "object";
}
categoriesVal = jQuery("#CategoriesList").val();
jQuery.ajax({
cache: false,
type: "POST",
async: false,
url: gymRegions.ajaxurl,
data: serialized + '&action=showcountries&makeselection=getUserIDs&countryID=' +
countryVal + '&cityID=' + cityVal + '&townID=' + townVal + '&categoriesID=' +
categoriesVal + '&locationHref=' + url,
dataType: "json",
success: function (data) {
alert("Success!");
localStorage.setItem('dataObjectTemp2', JSON.stringify(data));
var numericRecCount = parseInt(data.c);
window.location.href = url + '/index.php/anotherpage/';
},
error: function (data, status, error) {
alert("No records were returned for your search. Please make another selection.");
}
});
return false;
});
jQuery('#MyForm').submit(function (e) {
e.preventDefault(); //use prevent default here
console.log("getUserIDs is successfully hit.");
alert("The submit event has been hit");
var countryVal;
var cityVal;
var townVal;
var categoriesVal;
var serialized = jQuery('#MyForm').serialize();
var url = window.location.hostname;
countryVal = jQuery("#CountryList").val();
cityVal = jQuery("#CityList").val();
townVal = jQuery("#TownList").val();
if (typeof townVal == 'object'){
townVal = "object";
}
categoriesVal = jQuery("#CategoriesList").val();
jQuery.ajax({
cache: false,
type: "POST",
async: false,
url: gymRegions.ajaxurl,
data:{action: "showcountries",
makeselection: "getUserIDs",
countryID: countryVal,
cityID: cityVal,
townID: townVal,
categoriesID: categoriesVal,
locationHref: url,
serialized},
dataType: "json",
success: function (data) {
alert("Success of the submit event has been hit.");
localStorage.setItem('dataObjectTemp2', JSON.stringify(data));
var numericRecCount = parseInt(data.c);
document.location.href = window.location.hostname + '/index.php/anotherpage/';
},
error: function (data, status, error) {
alert("No records were returned for your search. Please make another selection.");
console.log(data);
console.log(status);
console.log(error);
}
});
});

Issue with newElements function

I have a vote function in one of my projects. Please see following code.
$(function () {
$(".vote").click(function () {
var id = $(this).data("id");
var name = $(this).data("name");
var dataString = 'id=' + id;
//var dataId = id;
var parent = $(this);
if (name == 'up') {
$(this).fadeIn(200).html;
$.ajax({
type: "POST",
url: "vote_up.php",
data: dataString,
cache: false,
success: function (html) {
parent.parent().find(".display-vote").html(html);
}
});
} else {
$(this).fadeIn(200).html;
$.ajax({
type: "POST",
url: "vote_down.php",
data: dataString,
cache: false,
success: function (html) {
parent.parent().find(".display-vote").html(html);
}
});
}
return false;
});
});
and I'm using jQuery infinite scroll to load rest of the pages/posts. I'm using following code in main page and second page which i load rest of the data
('#left').infinitescroll({
navSelector: '#page-nav', // selector for the paged navigation
nextSelector: '#page-nav a', // selector for the NEXT link (to page 2)
itemSelector: '.post-box', //
}, function (newElements, data, url) {
$(".vote").click(function () {
var id = $(this).data("id");
var name = $(this).data("name");
var dataString = 'id=' + id;
//var dataId = id;
var parent = $(this);
if (name == 'up') {
$(this).fadeIn(200).html;
$.ajax({
type: "POST",
url: "vote_up.php",
data: dataString,
cache: false,
success: function (html) {
parent.parent().find(".display-vote").html(html);
}
});
} else {
$(this).fadeIn(200).html;
$.ajax({
type: "POST",
url: "vote_down.php",
data: dataString,
cache: false,
success: function (html) {
parent.parent().find(".display-vote").html(html);
}
});
}
return false;
});
});
Issue is after 2nd 3rd or any other page load, vote function is triggering twice. How can I fix this issue. Any help will be appreciated.
Maybe if you unbind the click event and then bind it
function(newElements, data, url){
$(".vote").unbind( "click" );
$(".vote").click(function() {
You need to unbind the click event before binding it again.
[...]
$(".vote").unbind('click').click(function()
[...]
or
[...]
$(".vote").off('click').click(function()
[..]
depending on the version of jQuery you are using.

Json data in a next and previous button

I have to use a AJAX call to get Json data after clicking next and previous buttons. Json data should contain blog content displayed after clicking next or previous. Any suggestions how my function should look like? So far I have only:
function getPrev() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json"
}).success(function (data) {
$.each(data, function (key, val) {
$('#blogcont').append(key+ val);
});
return false;
});
}
And my Json file is only a test file:
{"one":"test1", "two":"test2", "three":"test3" }
Sorry I am a beginner!!!!
Thanks
Your $.ajax() syntax is incorrect
function getPrev() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json",
success: function(data) {
var content = "";
$.each(data, function(key, val) {
content += "<p>" + key + ":" + val + "</p>";
});
$('#blogcont').html(content);
}
});
return false;
}
or
function getPrev() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json"
}).done(function(data) {
var content = "";
$.each(data, function(key, val) {
content += "<p>" + key + ":" + val + "</p>";
});
$('#blogcont').html(content);
});
return false;
}
Try this
function getPrev() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json"
}).done(function(data) {
var content = "";
$.each(data, function(key, val) {
content += '<p>' + key + ':' + val + '</p>';
});
$('#blogcont').html(content)
.find('p')
.hide()
.first().show();
$('button.next').click(function() {
$('#blogcont').find('p:visible')
.hide()
.next('p').show();
});
});
return false;
}
How about storing the JSON data as a variable, which you can then access using an index on click?
var jsonData;
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json",
success: function (data) {
jsonData= data;
}
});
var clickIndex = 0;
$('.prev').click(function() {
if(clickIndex > 0) {
clickIndex -= 1;
}
get(clickIndex);
});
$('.next').click(function() {
clickIndex++;
get(clickIndex);
});
Your get function would then accept the index and find the JSON property:
function get(i) {
var item = jsonData[i];
}
Note that you would need to add an if statement to check whether you have reached the index limit on click of .next. Also, this is fine for a test JSON file, but a better solution would be to be able to request just one relevant item from a web service returning the JSON.

when fast cliking on like button getting unknown likes

i am working on project which have like unlike function look like facebook but i am getting stuck when i click multiple time at once on like button or unlike button then its work like firing and if i have 1 or 2 like and i click many time fast fast then my likes gone in -2 -1. how i solve this issue ? if when click many time always get perfect result. below my jquery script
$(document).ready(function () {
$(".like").click(function () {
var ID = $(this).attr("idl");
var REL = $(this).attr("rel");
var owner = $(this).attr("owner");
var URL = 'box_like.php';
var dataString = 'msg_id=' + ID + '&rel=' + REL + '&owner=' + owner;
$.ajax({
type: "POST",
url: URL,
data: dataString,
cache: false,
success: function (html) {
if (REL == 'Like') {
$('.blc' + ID).html('Unlike:').attr('rel', 'Unlike').attr('title', 'Unlike');
$('.spn' + ID).html(html);
} else {
$('.blc' + ID).attr('rel', 'Like').attr('title', 'Like').html('Like:');
$('.spn' + ID).html(html);
}
}
});
});
});
It is because of the async nature of ajax request.... when you click on the element continuously... the click event will get fired before the response from previous request come back and the link status is updated to next one
Case:
Assume the rel is unlike, then before the response came back again another click happens so the rel is not yet updated so you are sending another unlike request to server instead of a like request
Try below solution(Not Tested)
$(document).ready(function () {
var xhr;
$(".like").click(function () {
var ID = $(this).attr("idl");
var REL = $(this).attr("rel");
var owner = $(this).attr("owner");
var URL = 'box_like.php';
var dataString = 'msg_id=' + ID + '&rel=' + REL + '&owner=' + owner;
if (REL == 'Like') {
$('.blc' + ID).html('Unlike:').attr('rel', 'Unlike').attr('title', 'Unlike');
} else {
$('.blc' + ID).attr('rel', 'Like').attr('title', 'Like').html('Like:');
}
//abort the previous request since we don't know the response order
if (xhr) {
xhr.abort();
}
xhr = $.ajax({
type: "POST",
url: URL,
data: dataString,
cache: false
}).done(function (html) {
$('.spn' + ID).html(html);
}).always(function () {
xhr = undefined;
});
});
});
Set a variable, we'll call it stop and toggle it.
$(document).ready(function () {
var stop = false;
$(".like").click(function () {
if (!stop)
{
stop = true;
var ID = $(this).attr("idl");
var REL = $(this).attr("rel");
var owner = $(this).attr("owner");
var URL = 'box_like.php';
var dataString = 'msg_id=' + ID + '&rel=' + REL + '&owner=' + owner;
$.ajax({
type: "POST",
url: URL,
data: dataString,
cache: false,
success: function (html) {
if (REL == 'Like') {
$('.blc' + ID).html('Unlike:').attr('rel', 'Unlike').attr('title', 'Unlike');
$('.spn' + ID).html(html);
} else {
$('.blc' + ID).attr('rel', 'Like').attr('title', 'Like').html('Like:');
$('.spn' + ID).html(html);
}
}
}).always(function() { stop = false; });
}
});
});

Categories

Resources