I got an if-else script:
$('#favitem').live('click', function () {
var fid = $(this).parent().attr('id');
if (isFav(fid)) {
alert("Do you want to remove from favorite?");
}
else {
alert("Add to favorite?");
}
});
calling the isFav script function:
function isFav(fid) {
$.ajax({
url: '/Stock/IsFav',
type: 'GET',
data: { id: fid },
success: function (result) { return result; }
});
}
which in turn calling my controller action:
public Boolean IsFav(int id)
{
var food = dbEntities.FOODs.Single(f => f.FoodID == id);
if (food.FavFlag == 1)
{
return true;
}
else
{
return false;
}
}
Everything seems works fine, I get a true from firebug, BUT i get the alert message from the else statement. The if statement just never being entered.
I cant get what is wrong here. Any idea?? Please help..
The ajax request in isFav is async and the isFav method will return before it is completed.
This is probably how I would solve it:
function isFav(fid, callback) {
$.ajax({
url: '/Stock/IsFav',
type: 'GET',
data: { id: fid },
success: function (result) { callback(result); }
});
}
$('#favitem').live('click', function () {
var fid = $(this).parent().attr('id');
isFav(fid,function(result){
if(result && result.toLowerCase() == "true"){
alert("Do you want to remove from favorite?");
} else {
alert("Add to favorite?");
}
});
});
You want to make sure that the code in the if-block is run after the ajax request is done. In this snippet this is solved by the callback method that is called when the ajax success function is executed.
You're not really returning true from within isFav function. Also ajax is asynchornous, so your code (if statement) actually continues to execute until ajax finishes, so at the moment of execution the result of isFav is undefined. So that's why else is being executed.
You're gonna need some remodeling.
function isFav(fid) {
$.ajax({
url: '/Stock/IsFav',
type: 'GET',
data: { id: fid },
success: function (result) {
if(result == 'favorite') alert("Do you want to remove from favorite?");
else alert("Add to favorite?");
}
});
}
$('#favitem').live('click', function () {
var fid = $(this).parent().attr('id');
isFav(fid);
});
Related
I am using a DataTable and an onclick event that checks if im clicking a certain td, then im validating the selection with a yes no. If i place DataTable.row().remove() here it works fine. But if i move the same item on the ajax success function it does not work - im sure im not understanding how java functions work, see code below - please help :)
<script>
var table = $('#notesTable').DataTable({
searching: false,
"pageLength": 15
});
$('#notesTable tbody').on('click', 'td', function (table) {
var noteIDObject = this.parentNode.cells[0];
var noteID = noteIDObject.id;
var currentRow = event.currentTarget.parentNode.rowIndex;
if (this.id == "trashRow") {
let confirmAction = confirm("Are you sure you want to delete this record?");
if (confirmAction) {
var p = $('#notesTable').DataTable();
p.row($(this).parents('tr')).remove().draw();
$.ajax({
type: "POST",
url: "/ClientDetails/DeleteNote/",
data: { noteID },
success: function (response) {
if (response == 200) {
console.log(200);
//would like to remove the row here on a successfull response
}
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
} else {
}
} else { }
});
I have made this custom ajax function to avoid writing ajax code multiple times. My issue is that if there is no option passed for failcmds variable & obj.status is "failure", then also code execution moves to the succcmds code block & execute available commands. e.g. reload(2500) in the example code.
Pls help me to identify the missing part.
Custom Ajax function
function gr(url, varr, succcmds, failcmds, divid, drestype) {
$.ajax({
url: url,
type: "POST",
data: varr,
beforeSend: function(){
$('#loadingDiv').show();
},
complete: function(){
$('#loadingDiv').hide();
},
success: function(response){
if(response){
var obj = $.parseJSON(response);
if(obj.status == "failure") {
console.log('failcmds : ' + failcmds);
if(obj.message) {
gm("e",obj.message);
}
if(typeof failcmds === "undefined") {
return;
}else {
$.each(failcmds,function(index, value) {
value;
});
}
}else if(obj.status == "success"){
if(obj.message) {
gm("s",obj.message);
}
if(succcmds && succcmds !== null) {
$.each(succcmds,function(ind, val) {
val;
});
}
if (divid && divid !== null){
if(drestype && drestype == "html"){
$("#"+ divid).html(obj.data);
}else{
$("#"+ divid).append(obj.data);
}
}
}
}else{
gm("e", "Invalid Request");
}
},
error: function(){}
});
}
Sample usage of function
$(document).on("click", '.xyz', function() {
var d = $(this).prop('id');
var data = 'd='+ $(this).prop('id') + '&typ=sts';
gm('c','Are you sure you want to do this?');
$(document).on("click", '#btnYes', function() {
var sarr = [reload(2500)];
gr(basepath + "deletereq?", data, sarr);
});
});
then also code execution moves to the succcmds code block & execute available commands
No it doesn't. You executed those commands before you even called your function:
var sarr = [reload(2500)];
This will execute reload(2500) and put the result of that execution in the sarr array.
Instead, wrap that in a function:
var sarr = [function () { reload(2500); }];
Then you can later execute that function where you like:
$.each(succcmds,function(ind, val) {
val();
});
Basically you want your "commands" to be executable functions, not the results of executed functions.
Below is my .ready() function:
$(document).ready(function()
{
var Semester = $('#Semester').find(':selected').val();
var StudentID = "<?php echo $_GET['id'];?>";
$.ajax(
{
type: 'POST',
url: 'ajax_get_report_for_edit.php',
data: {Semester:Semester, StudentID:StudentID},
dataType: 'text',
success: function(data)
{
if(data['error'] == null)
{
if(data['no_result'] == null)
{
$('#display').html(data);
}
else
{
//error msg
}
}
else
{
alert("Error: " + data['error'])
}
},
error: function(ts)
{
alert("AJAX Error: \n" + ts.responseText);
}
});
});
This function will run when the page load, but I would like to use this function in other event like .click(). Do I need to rewrite the function?
Just create the function with a name, and use it everywhere! Example:
$(document).ready(function(){
function yourFunction(){
var Semester = $('#Semester').find(':selected').val();
var StudentID = "<?php echo $_GET['id'];?>";
$.ajax(
{
type: 'POST',
url: 'ajax_get_report_for_edit.php',
data: {Semester:Semester, StudentID:StudentID},
dataType: 'text',
success: function(data)
{
if(data['error'] == null)
{
if(data['no_result'] == null)
{
$('#display').html(data);
}
else
{
//error msg
}
}
else
{
alert("Error: " + data['error'])
}
},
error: function(ts)
{
alert("AJAX Error: \n" + ts.responseText);
}
});
}
yourFunction();
$('#element').click(function(){
yourFunction();
});
});
name the function and call that function on your click event.
sample:
<button id='btn'> click me </button>
$(document).ready(function(){
foo();
$("#btn").click(function(){
foo();
});
function foo(){
alert('data');
}
});
JSFIDDLE DEMO
This function will run when the page load, but I would like to use
this function in other event like .click().
Try using array of functions as parameter to .ready() , name first function in array , set named function to property of this:document within first array ; named function should be available at second function within array as property of this:document
$(document).ready([
function fn() {
this.fn = fn;
console.log(this)
},
function() {
$("div").click(this.fn)
}
])
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div>click</div>
First Create a function that will be called on your click event. Please see below example.
$(document).ready(function(){
$("#samplebutton").on("click",function(){
example();
});
function example(){
alert("clicked");
}
});
Sorry for the title but I had no idea how to call it.
I got some ajax call function that on success adds some HTML elements to the page:
function ajax_submit_append(form_data, url, result, complete) {
$.ajax({
url: url,
type: 'POST',
data: form_data,
success: function(msg) {
var res = $(msg).filter('span.redirect');
if($(res).html() != null){
window.location.replace($(res).html());
return false;
}
$(result).append(msg);
},
complete: complete()
});
};
Function does something on success where the most important is the .append and then this ajax function is called in some button .click function like this:
$(function() {
$("#product_list_add_btn").click(function(e){
ajax_submit_append(
form_data = {
product_name: $('.selectpicker option:selected').val(),
amount: $('#amount').val()},
"<?php echo site_url('admin_panel/new_order/add_product'); ?>",
'#add_product_result',
calculateSum
);
return false;
});
});
What I want to achieve is that calculateSum function (sums table columns) is called after .append is done via ajax.
For now, when I add calculateSum to ajax complete event it is still called before new row is added to the table with .append
Edit: I present You calculateSum, but I believe there is nothing faulty there.
function calculateSum() {
var sum = 0;
// iterate through each td based on class and add the values
$(".countit").each(function() {
var value = $(this).text();
// add only if the value is number
if(!isNaN(value) && value.length != 0) {
sum += parseFloat(value);
}
});
$('#total_price').text(sum);
alert("test");
};
If I had to guess, I would say its something with click event?
How to fix this?
Try using jqXHR's done() method:
function ajax_submit_append(form_data, url, result, complete) {
$.ajax({
url: url,
type: 'POST',
data: form_data,
success: function(msg) {
var res = $(msg).filter('span.redirect');
if($(res).html() != null){
window.location.replace($(res).html());
return false;
}
$(result).append(msg);
}
}).done(complete);
};
I have a function:
function validateForm() {
var result = ''
$.get(
'/auth_validate_username/',
{ 'result': result },
function(data) {
if (data!=='') {
// make function validateForm return false
}
}
);
};
I would like to know if there is a way to do something in my condition that will apply to the function above the get request.
What I want to do exactly is that if my condition is met in my get request, then the function validateForm() return false.
Is there a way to accomplish that?
EDIT:
Here is what I tried
js:
var validateResult;
$('#but_id').click(function(event){
validateForm().done(function(){
if(!validateResult)
event.preventDefault();
});
})
function validateForm() {
var result = ''
return $.get(
'/auth_validate_username/',
{ 'result': result },
function(data) {
if(data!==''){
validateResult = false;
}
}
);
};
html:
<form method="post" onsubmit="return validateForm();">
<input id='username' type="text" name="username"/>
<button type="submit" id='but_id'>Submit</button>
</form>
I assume you're trying to do something like this:
if (validateForm()) {
doSomething();
}
else {
displayError();
}
Instead, simply do this:
function validateForm(){
//...
$.get(
'/auth_validate_username/',
{ 'result': result },
success: function(data) {
doSomething();
},
error: function(data) {
displayError();
}
);
}
You just have to make sure that your server responds accordingly. I.e., your server shouldn't be generating a successful 200 response for every request to /auth_validate_username.
$.get is just a shorthand for $.ajax(). Read more about the callbacks in the docs.
Per your comment!
function doSomething(data, textStatus, jqXHR) {
$('form').submit();
}
function displayError(jqXHR, textStatus, errorThrown){ ... }
function validateForm(event){
$.ajax(
url: '/auth_validate_username/',
data: {"result": result},
success: doSomething,
error: displayError
);
return false; // prevent default form submit
}
$('form').submit(validateForm);
It would've been nice to know this was your goal from the start.
Use a sync call may implement what you want with 'async: false' when start a ajax call.
Tried in Chrome console and works.
function validateForm() {
var result = ''
var retval=true;
$.ajax(
'/auth_validate_username/',
{
async: false,
data: { 'result': result }
}
).done(function ( data ){
if(data !== ''){
retval = false;
}
});
return retval;
};
The ajax will complete after the function completes. So there is no way to do what you are looking for. Re-arrange your design or submit the form from the success function in the get.
Here is my crazy approach at a workaround
var validating = false;
var safeSubmit = false;
function validateForm()
{
validating = true;
$("#formElementId").ajaxStop(function () {
if( !validating ) return;
if( safeSubmit ) $(this).submit();
validating = false;
$(this).unbind("ajaxStop");
});
var result = ''
$.get(
'/auth_validate_username/',
{ 'result': result },
function(data) {
if (data!=='') {
// make function validateForm return false
}else{
safeSubmit = true;
//this could also simply be
//$("#formElementId").submit();
}
}
);
return false;
}
Try using done with your function call.
In html
<input type ="button" id="yourButtonId" value="submit" />
In javascript
var validateResult;
$('#yourButtonId').click(function(event){
validateForm().done(function(){
//your code
if(!validateResult)
event.preventDefault();
});
})
function validateForm() {
var result = ''
return $.get(
'/auth_validate_username/',
{ 'result': result },
function(data) {
if(data!==''){
// make function validateForm return false
validateResult = false;
}
}
);
};