I have the following jQuery code and it is not getting triggered on the required actions, when I take out the first 2 $("body").on functions, the third one ie. ($("body").on("click", '.upvote', function(event){) gets triggered. When I put everything back in nothing works.
$(document).ready(function () {
//function 1
$("body").on("change", '.select', function (event) {
$('.row.replace').empty();
$('.row.replace').append("<br><br><br><br><p align='center'><img id='theImg' src='/media/loading1.gif'/></p><br><br><br><br><br><br><br><br>");
var filter = $(this).find(":selected").attr("name");
$.ajax({
type: "POST",
url: "/filter_home/" + filter + "/" + "TrendingNow" + "/",
data: {
'name': 'me',
'csrfmiddlewaretoken': '{% csrf_token %}'
},
//dataType: "json",
success: function (data) {
$('.row.replace').html("mem");
},
error: function (xhr, errmsg, err) {
alert(err);
}
}); //end ajax
return false;
}); //end onchange
//function 2
$("body").on("click", '.sorter', function (event) {
$('.row.replace').empty();
$('.row.replace').append("<br><br><br><br><p align='center'><img id='theImg' src='/media/loading1.gif'/></p><br><br><br><br><br><br><br><br>");
var sort = $(this).attr("name");
var filter = $('.select').find(":selected").attr("name");
$.ajax({
type: "POST",
url: "/filter_home/" + filter + "/" + sort + "/",
data: {
'name': 'me',
'csrfmiddlewaretoken': '{% csrf_token %}'
},
success: function (data) {
$('.row.replace').html(data);
},
error: function (xhr, errmsg, err) {
alert(err);
}
}); //end ajax
return false;
}); //end onclick
//function 3
$("body").on("click", '.upvote', function (event) {
var x = $(this).attr("name");
$.ajax({
type: "POST",
url: "/upvote/" + x + "/",
data: {
'name': 'me',
'csrfmiddlewaretoken': '{{csrf_token}}'
},
dataType: "json",
success: function (json) {
var y = "vote-count" + x;
$('i[class= "' + y + '"]').text(json.vote_count);
//flip button
$('.flip' + x).find('.card').toggleClass('flipped');
},
error: function (xhr, errmsg, err) {
alert("oops, something went wrong! Please try again.");
}
}); //and ajax
return false;
}); //end onclick
}); //end ready
The event handlers (functions 1,2,3) are all returning false. This stops the event from bubbling up the DOM. I'm guessing that they're not being triggered as expected because the first function to handle the event is stopping the propagation. Test this by removing the return statement.
Alternatively, you can try scoping the delegated event handler closer to the target.
Related
This is a very weird problem but I will provide as much detail as possible. This Javascript function is in a separate .js file and referenced into various HTML pages in a Cordova application. When a push notification, with 2 parameters: id, type, is received into the device, a function called LaunchFromNotif is executed with these 2 parameters passed as arguments.
function LaunchFromNotif(id, type) {
try {
var ebyidurl = url + "ReturnEByID";
var nbyidurl = url + "ReturnNByID";
if (type != null) {
if (type == "n") {
$.ajax({
type: 'GET',
url: nbyidurl,
data: { id: id },
dataType: 'json',
processdata: true,
success: function (data) {
//code here
},
error: function (xhr, status, error) {
alert('Error: ' + error);
}
});
} else if (type == "e") {
$.ajax({
type: 'GET',
url: ebyidurl,
data: { id: id },
dataType: 'json',
processdata: true,
success: function (data) {
//code
},
error: function (xhr, status, error) {
alert('Error: ' + error);
}
});
} else if (type == "a") {
combined(id);
}
}
} catch (exception) {
//window.location = "Warning2.html";
}
}
Combined(id) is another function with 2 Ajax calls. I used when and then, to make sure that the first ajax call completes before starting the second.
function combined(id) {
alert("combined");
$.when(
$.ajax({
type: 'GET',
url: nbyidurl,
data: { id: id },
dataType: 'json',
processdata: true,
success: function (data) {
alert("success of first ajax");
},
error: function (xhr, status, error) {
alert('Error 1: ' + error);
}
})
).then(function () {
$.ajax({
type: 'GET',
url: Verifytempurl,
data: { Username: localStorage.getItem('user') },
success: function (data) {
alert("success of second ajax");
},
error: function (xhr, status, error) {
alert('Error 2: ' + error);
}
});
});
The problem is that this is working well in only one HTML page. In 3 other pages in which I tried, it shows the "combined" alert and seems to never access the Ajax call. The logic seems to make sense, especially since it is in working order in one page. What could normally go wrong in something of the sort? I am left with few debugging possibilities, especially since this is a Cordova app and being tested on mobile devices.
Thanks in advance!
I have an href in an html page and i have an AJAX request in a method in a javascript file.
When clicking on href i want to call the JS function and I am treating the response to add it to the second html page which will appear
function miniReport(){
alert('TEST');
var client_account_number = localStorage.getItem("numb");
var request = $.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {client_language: client_language, PIN_code:pin,client_phone:number}
});
request.done(function(msg) {
//alert(JSON.stringify(msg));
});
if (msg.ws_resultat.result_ok==true)
{
alert('success!');
window.open("account_details.html");
}
request.error(function(jqXHR, textStatus)
{
//MESSAGE
});
}
I tried with , and also to write the function with $('#idOfHref').click(function(){}); not working.
All I can see is the alert TEST and then nothing happens. I checked several posts here but nothing works for me.
Function can be corrected as,
function miniReport(){
alert('TEST');
var client_account_number = localStorage.getItem("numb");
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {"client_language": client_language, "PIN_code":pin,"client_phone":number},
success : function(msg) {
//alert(JSON.stringify(msg));
if (msg.ws_resultat.result_ok == true)
{
alert('success!');
window.open("account_details.html");
}
},
error: function(jqXHR, textStatus)
{
alert('Error Occured'); //MESSAGE
}
}
});
1. No need to assign ajax call to a variable,
2. Your further work should be in Success part of AJAX request, as shown above.
It's a bad practice use an onclick() so the proper way to do this is:
Fiddle
$(document).ready(function(){
$('#mylink').on('click', function(){
alert('onclick is working.');
miniReport(); //Your function
});
});
function miniReport(){
var client_account_number = localStorage.getItem('numb');
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {
'client_language': client_language,
'PIN_code': pin,
'client_phone': number
},
success: function(msg){
if (msg.ws_resultat.result_ok==true)
{
alert('success!');
window.open("account_details.html");
}
},
error: function(jqXHR, textStatus)
{
//Manage your error.
}
});
}
Also you have some mistakes in your ajax request. So I hope it's helps.
Rectified version of your code with document .ready
$(document).ready(function(){
$("#hrefid").click(function(){ // your anchor tag id if not assign any id
var client_account_number = localStorage.getItem("numb");
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data:{"client_language":client_language,"PIN_code":pin,"client_phone":number},
success : function(msg) {
if (msg.ws_resultat.result_ok == true)
{
window.open("account_details.html");
}
else
{
alert('some thing went wrong, plz try again');
}
}
}
});
});
I am trying to set a button text to 'Email sent' on success or 'Emailed failed' on failure. I am using ajax to call a method in MVC.
The call to to MVC works fine, but my code calls setButtonSuccess and setButtonFailed even before the json is ran?
Here is my code:
$('input[type=button]').click(function () {
bookingID = $(this).closest('tr').attr('id');
sendEmail(bookingID, this);
});
function sendEmail(id, thisContext) {
var data = JSON.stringify({ 'id': id });
/*******
This calls setButtonSuccess AND setButtonFailed which is wrong
I want to execute only setButtonSuccess OR setButtonFailed depending on whether successful or not
*******/
jsonPOST("~Booking/ResendEmail", data, setButtonSuccess(thisContext, "Email Sent"), setButtonFailed(thisContext, "Email Failed"),false);
};
function setButtonSuccess(thisContext, buttonValue) {
$(thisContext).val(buttonValue);
$(thisContext).addClass("btn btn-success");
};
function setButtonFailed(thisContext, buttonValue) {
$(thisContext).val(buttonValue);
$(thisContext).addClass("btn btn-warning");
};
function jsonPOST (pWebServiceFunction, pData, pOnCallbackSuccess, pOnCallbackFailed, async) {
$.ajax({
type: "POST",
url: url + pWebServiceFunction,
data: pData,
contentType: "application/raw; charset=utf-8", dataType: "json",
async:async,
processdata: true,
success: function (msg) {
if (msg.success === true) {
pOnCallbackSuccess(msg);
}
else {
pOnCallbackFailed(url + pWebServiceFunction);
}
},
error: function (xhr, ajaxOptions, thrownError) //When Service call fails
{
pOnCallbackFailed(url + pWebServiceFunction, pData, xhr.status, xhr.statusText, xhr.responseText);
}
});
};
Thanks
You're calling the functions immediately instead of passing a function that will call them later. It should be:
jsonPOST("~Booking/ResendEmail", data, function() {
setButtonSuccess(thisContext, "Email Sent");
}, function() {
setButtonFailed(thisContext, "Email Failed");
}, false);
I am using the following code to prepend information into my list and it is working fine. On top of that, I want to send the 2 variable below (listDescription and payment) to a url too as follows :
http://mywebsite.com/public/user/spent/?amount=listDescription&account=payment
I am trying to use ajax and send the information over with the following code but it is not working and I get no response alerts either way. Can I get some help on this please. Thanks.
$(document).ready( function() {
var listDescription;
var payment;
//prepending - working fine
$('#add_list').click( function() {
listDescription = $('#list_description').val();
payment = $('#payment').val();
$('.expense_list').prepend('<div>' + "\u00A3 " + listDescription + "\t\t\t" + payment + "\t" + '</div>');
//This is not working
$.ajax({
url: "htttp://mywebsite.com/public/user/spent/",
data: {
amount: listDescription,
account: payment
},
type: "GET",
async:true,
cache:false,
success: function (data) {
alert("success");
},
error: function (xhr, status, error) {
alert("error");
}
});
$('#list_form')[0].reset();
return false;
});
});
$(document).ready( function() {
//prepending - working fine
var listDescription = $('#list_description').val();
var payment = $('#payment').val();
$('#add_list').click( function() {
$('.expense_list').prepend('<div>' + "\u00A3 " + listDescription + "\t\t\t" + payment + "\t" + '</div>');
//This is not working
$.ajax({
url: "htttp://mywebsite.com/public/user/spent/",
data: {
amount: listDescription,
account: payment
},
type: "GET",
async:true,
cache:false,
success: function (data) {
alert("success");
},
error: function (xhr, status, error) {
alert("error");
}
});
$('#list_form')[0].reset();
return false;
});
});
This should work :)
May be try to add data type JSON in your AJAX Request?
dataType:'json',
Hi all I need to do here is that when the selection is changed of a dropdown list, with the use of AJAX I want to call an action and pass some data. Here below you can find The code that I am using. I have searched a lot and dont get why it is not entering in the action. The data and url are correct. The Controller name is HomeController and the action name is getData.
<script type="text/javascript">
function submitform() {
var a = document.getElementById("tournaments");
var datad = a.options[a.selectedIndex].value;
var url = '/Home/getData';
var completeurl = window.location.host + url;
alert(completeurl);
$.ajax({
type: "GET",
url: completeurl,
data: {tournamentid : datad},
datatype: 'JSON',
success: function (data) { alert('got here with data'); },
error: function () { alert('something bad happened'); }
});
};
</script>
Dropdownlist:
<%: #Html.DropDownList("tournaments", null, new { name = "tournaments", title = "Please Select Tournament.", onchange = "submitform();",id = "tournaments"}) %>
Action:
[HttpGet]
public ActionResult getData(int? tournamentid)
{
//perform your action here
UserBl us = new UserBl();
int num = Convert.ToInt32(tournamentid);
Tournament tour = us.GetTournamentById(num);
return Json(tour, JsonRequestBehavior.AllowGet);
}
you would do it like this:
$(function(){ // document and jquery ready
$("#tournaments").on("change", function(e){
var dropValue = $(this).val();
$.ajax({
type: "GET",
url: '/Home/getData/' + dropValue,
datatype: 'JSON',
success: function (data) { alert('got here with data'); },
error: function () { alert('something bad happened'); }
});
});
});
There are two ways
one is (use selectedItem as tournamentId)
<script type="text/javascript">
$(function () {
$("#tournaments").change(function () {
var selectedItem = $(this).val();
submitform(selectedItem);
});
});</script>
Or
put javascript: for onchange attribute
onchange = "javascript:submitform();"
EDITED :
for that I would suggest
$.ajax({
cache: false,
type: "GET",
url: url,
data: { "tournamentid ": datad},
success: function (data) {
alert("succeded")
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed ');
}});