jquery code execution is happening in other code block - javascript

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.

Related

Ajax call not working in function

I have one function in java script. I want to send my form in ajax call after validation. I wrote ajax code for this but it's neither working nor giving any error on console even .
What can i do ?
javascript
function resetValidation(){
$(_reqForm).find('input, select, textarea, fieldset').removeClass('invalid');
$(_reqForm).find('.error-indicator').attr('aria-hidden', true);
$(_reqForm).find('#errorSummary').remove();
}
function handleSubmit(e){
e.preventDefault();
var formValid = true;
var errorMessages = [];
$.ajax({
type: "POST",
url: "quoteProcess.php",
data : $('#testform').serialize(),
success: function(data) {
alert(data);
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
}
});
$(_reqForm).find('#errorSummary').remove();
$(_reqForm).find('[data-do-validate="true"]').each(function(){
var validationResult = validateField($(this));
if (!validationResult.isValid) {
var fieldMsg = getFieldMessage($(this), validationResult.type);
errorMessages.push({ elem: $(this).prop('id'), msg: fieldMsg });
showFieldError($(this), fieldMsg);
formValid = false;
} else {
clearFieldError($(this));
}
});
if (!formValid) {
if (settings.showErrorSummary) {
showErrorSummary(errorMessages);
}
return false;
} else {
if (typeof(settings.submitFunction) !== 'undefined') {
settings.submitFunction();
} else {
_reqForm[0].submit();
}
}
}

How to hide current page

I have a connection with my DB and my DB sends me some integer value like "1","2" or something like that.For example if my DB send me "3" I display the third page,it's working but my problem is when it displays the third page it's not hide my current page.I think my code is wrong in somewhere.Please help me
<script>
function show(shown, hidden) {
console.log(shown,hidden)
$("#"+shown).show();
$("#"+hidden).hide();
}
$(".content-form").submit(function(){
var intRowCount = $(this).data('introwcount');
var exec = 'show("Page"+data.result,"Page' + intRowCount + '")';
ajaxSubmit("/post.php", $(this).serialize(), "", exec,"json");
return false;
})
function ajaxSubmit(urlx, datax, loadingAppendToDiv, resultEval, dataTypex, completeEval) {
if (typeof dataTypex == "undefined") {
dataTypex = "html";
}
request = $.ajax({
type: 'POST',
url: urlx,
dataType: dataTypex,
data: datax,
async: true,
beforeSend: function() {
$(".modalOverlay").show();
},
success: function(data, textStatus, jqXHR) {
//$("div#loader2").remove();
loadingAppendToDiv !== "" ? $(loadingAppendToDiv).html(data) : "";
if (typeof resultEval !== "undefined") {
eval(resultEval);
} else {
//do nothing.
}
},
error: function() {
alert('An error occurred. Data does not retrieve.');
},
complete: function() {
if (typeof completeEval !== "undefined") {
eval(completeEval);
} else {
//do nothing.
}
$(".modalOverlay").hide();
}
});
}
</script>
Thanks for your helping my code working fine now.The problem is occured because of the cache. When I clear cache and cookies on Google Chrome it fixed.
The second parameter passed into the show() method is a bit wrong:
"Page' + intRowCount + '"
Perhaps you meant:
'Page' + intRowCount
Edit: wait wait you pass in a string of code to ajaxSubmit? What happens inside it?
If ajaxSubmit can use a callback, try this:
var exec = function(data) {
show('Page' + data.result, 'Page' + intRowCount);
};
Assuming your html is:
<div id='Page1'>..</div>
<div id='Page2'>..</div>
<div id='Page3'>..</div>
add a class to each of these div (use a sensible name, mypage just an example)
<div id='Page1' class='mypage'>..</div>
<div id='Page2' class='mypage'>..</div>
<div id='Page3' class='mypage'>..</div>
pass the page number you want to show and hide all the others, ie:
function showmypage(pageselector) {
$(".mypage").hide();
$(pageselector).show();
}
then change your 'exec' to:
var exec = 'showmypage("#Page"+data.result)';
It would be remiss of my not to recommend you remove the eval, so instead of:
var exec = "..."
use a function:
var onsuccess = function() { showmypage("#Page"+data.result); };
function ajaxSubmit(..., onsuccess, ...)
{
...
success: function(data) {
onsuccess();
}
}

jQuery .ready() function use in other event

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");
}
});

jQuery MVC - Basic jQuery if else statement which CANT work?

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);
});

How to make nested call with jquery

I've below code in JS file:
$(document).ready(function() {
$("#key_verify").click(function () {
$("#errrmsg").html("<img src=\"/images/shim.gif\"/>");
if($.trim($("#key").val()).length != 0){
$.ajax({
type : "POST",
cache : false,
async : true,
url : "/issuekey?key="+$("#key").val(),
success : function(data) {
var json_obj = $.parseJSON(data);
if(json_obj === undefined || json_obj == null){
}else{
if(json_obj.result == "true"){
top.location.href="/register"
}else{
$("#errrmsg").html(invalid_key);
}
}
},
error : function(data) {
$("#errrmsg").html(invalid_product_key);
}
});
}
});
}
How can I invoke above code in below lines so that when user hits enter key, it should make a call on enter key as well??
$("#key_verify").keypress(function(e) {
if(e.which == 13){
??????
}
});
Thanks!
Make the function you are passing to the click handler into a named function like so:
var verify = function(e) {
// your current anonymous function
$("#errrmsg").html("<img src=\"/images/shim.gif\"/>");
// ... the rest of your function
}
Then pass it as an argument into your event handlers:
$("#key_verify").click( verify );
$("#key_verify").keypress(function(e) {
if(e.which == 13){
verify( e );
}
});

Categories