I m facing a strange issue. i have used alertify library to show messages to user, but in this case alertify is not working. Here is the success portion of my ajax call.
success: function(data) {
if (data.status == 'success') {
alertify.success(data.msg);**// this line should dislay a message but instead of calling this , it directly calls employee_details(), data.msg is "Data saved Successfully"**;
data.user_type =3;
if(data.hasOwnProperty('user_type')){
if(data.user_type==2){
employeeDetails(data.id, tab_id);
}else{
employee_details(data.id);
}
} else {
return false;
}
}
}
if i remove employee_details(data.id), this works perfectly.
Related
I have a HTTP handler (ASHX) which I am calling from UI side using an AJAX function. The following is what needs to happen in this call:
When the section loads, it will display the status of the short code on the server in the shortcodestatus span. It will either say on or off:
<a class="btn btn-default" id="toggleshortcode">Short Code <span id="shortcodestatus"></span></a>
This is the function for getting the status of the short code and this works properly. I can manually change the status of the short code and the changes reflect properly on the div when I reload the page:
function ShortCodeStatus() {
$.ajax({
type: "GET",
url: "Handler.ashx?action=shortcodestatus",
success: function (output) {
console.log("getShortCodeStatus: " + output);
$("#shortcodestatus").empty();
if (output == "true") {
$("#shortcodestatus").text("ON");
$("#shortcodestatus").addClass("btn btn-success");
}
else {
$("#shortcodestatus").text("OFF");
$("#shortcodestatus").addClass("btn btn-danger");
}
}
});
};
This is the short code status code from the handler:
case "shortcodestatus":
{
output = ShortCodeStatus() ? "true" : "false";
}
break;
I want to be able to click on the toggleshortcode div to fire off this event through the handler. The functions for disabling and enabling the short code are working properly:
case "toggleshortcode":
{
if (ShortCodeStatus() == true)
{
DisableShortCode();
output = "false";
}
else
{
EnableShortCode();
output = "true";
}
}
break;
Here is the ajax call for the short code toggle:
$('#toggleshortcode').click(function () {
$.ajax({
type: "POST",
url: "Handler.ashx?action=toggleshortcode",
success: function (output) {
console.log("toggleshortcode: " + output);
ShortCodeStatus();
}
});
});
I'm hitting the URLs correctly and I'm getting the correct responses from each function. However the change to the short code does not seem to be happening.
For example, if the short code is off, the ShortCodeStatus function will return false and thus render the OFF button. When I click on the toggleshortcode button, the output is true (I want to turn on short code) which is correct but when the ShortCodeStatus function fires again in the success, it will still say false. The ajax functions seem correct but I can't figure out why the toggleshortcode on the handler is not firing properly.
Thank you so much for your time!
I'm seeing 2 cases that you can check.
First, in the ajax call for 'toggleshortcode', you are calling the function 'getShortCodeStatus()', and base on your example the correct name of the function is 'ShortCodeStatus()'.
Second, in the call to 'Handler.ashx?action=toggleshortcode', you are already returning the status (true or false), I suggest you make a javascript function named SetShortCodeStatus(status) , and use this inside of the success of both ajax request 'Handler.ashx?action=shortcodestatus' and 'Handler.ashx?action=toggleshortcode'.
function SetShortCodeStatus(status) {
$("#shortcodestatus").empty();
if (status == "true") {
$("#shortcodestatus").text("ON");
$("#shortcodestatus").addClass("btn btn-success");
}
else {
$("#shortcodestatus").text("OFF");
$("#shortcodestatus").addClass("btn btn-danger");
}
}
function ShortCodeStatus() {
$.ajax({
type: "GET",
url: "Handler.ashx?action=shortcodestatus",
success: function (output) {
console.log("getShortCodeStatus: " + output);
SetShortCodeStatus(output);
}
});
};
$('#toggleshortcode').click(function () {
$.ajax({
type: "POST",
url: "Handler.ashx?action=toggleshortcode",
success: function (output) {
console.log("toggleshortcode: " + output);
SetShortCodeStatus(output);
}
});
});
I'm using a simple if else statement to check for response from a POST form.
This is weird: I can check for response in form of error. Using elseif: or else: just does absolut nothing. Even though the response is valid.
Current code:
post_data = {
'someData': someData
}
// Ajax post data to server
$.post('register.php', post_data, function(response) {
if (response.type == 'error') {
if (response.errorType == 'something') {
$("#someThing").addClass('has-error');
}
} else {
window.location.reload(true);
}
}, 'json');
This is so weird. I've tried to insert alerts to really check if the else statement ran in background or something.
When the response is: "error" the error statement is executed.
However when the response is: success/done/cleared/failed etc. (whatever i try) nothing happens.
I receive the respond in console - but JQuery doesnt run the } else { ... statement.
Actually its not what you think.
The function is only called on Success. For error handling you have to chain another function
For example try this:
post_data = {
'someData':someData
}
// Ajax post data to server
$.post('register.php', post_data).done(function (response) {
// This is your success function
window.location.reload(true);
})
.fail(function (xhr, textStatus, errorThrown) {
console.log("Post error: " + errorThrown);
$("#someThing").addClass('has-error');
});
I hope this help you to understand that weird behavior :P
jQuery documentation have different handling functions for different jQuery version. so better to use $.ajax
I'm facing a weird error using JavaScript.
I have a file add_account.js in my project that it throw JQuery error, when my AJAX function is inside a function.
It occurs the same problem when I use components like bloodhound and typehead.
By the way it's not throwing even the error set up by AjaxSetup. It stops and no alert.
Error:
TypeError: e is undefined
setRequestHeader:function(e,t)
{var n=e.toLowerCase();return x||(e=v[n]=v[n]...
jquery-....min.js (line 5, col 11629)
var testAjaxRun = function(){
$.ajaxSetup({
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
$.ajax({
type: "GET",
dataType: "json",
url: "../controllers/fde.php",
success: function(data) {
alert('success');
return data;
}
});
//...
}
// outside function and in the end of file
$(document).ready(function() {
testAjaxRun();
});
If I remove the AJAX instructions to outside function it works normally.
Error:
TypeError: e is undefined
setRequestHeader:function(e,t)
{var n=e.toLowerCase();return x||(e=v[n]=v[n]...
jquery-....min.js (line 5, col 11629)
Any idea of this problem? All the rest inside the script is working perfectly.
It is project I'm migrating from Java to PHP. The javascript file into the Java Project works normally as well.
Folks,
I found the problem. Actually there is nothing wrong with the javascript.
The problem was that the project had another file.js that had this instruction which screwed up my ajax call.
Then I commented _jquery.init and all works. After 2 nights without sleeping and testing all the other things I got the error. :)
_jquery.init()
_jquery = {
init: function () {
$(document).ajaxSend(function (e, xhr, options) {
xhr.setRequestHeader(sync.csrfHeader, sync.csrf);
});
} };
Java project probably is treating this field, but I don't need it for now.
Comment Form is submitting and also data getting saved to the database. But not displaying on the browser without refreshing the page.
here is the code:
$("#post_reply").click(function (event) {
$("#data_status").html("");
$('#ajax_loading').show();
event.preventDefault();
if (document.getElementById('_comment').value.trim() == "") {
return false;
}
$.post('../services/leave_comment.php', $("#open_status").serialize(), function (data) {
$('#ajax_loading').hide();
if (data.split("::")[1] == true) {
$("#data_status").html("Commented Successfully..");
$("#data_status").fadeOut(3000);
document.getElementById('_comment').value = '';
$('#_comment').html("");
} else if (data.split("::")[1] == false) {
$("#data_status").html("Error occured in Comment Submission.. TryAgain..");
$("#data_status").fadeOut(3000);
}
});
});
EDIT:
All i can understand is i haven't published the data with ajax??
Is this what i need to do??
$("#post_reply").click(function (event) {
$("#data_status").html("");
$('#ajax_loading').show();
event.preventDefault();
if (document.getElementById('_comment').value.trim() == "") {
return false;
}
$.post('../services/leave_comment.php', $("#open_status").serialize(), function (data) {
$('#ajax_loading').hide();
if (data.split("::")[1] == true) {
$("#data_status").html("Commented Successfully..");
$("#data_status").fadeOut(3000);
document.getElementById('_comment').value = '';
$('#_comment').html("");
$.ajax({
type: 'POST',
url : 'http://localhost/tech1/services/get_more_comments.php',
data: 'last_id='+last_id,
success: function(data){
$('.view_container').append(data);
},
complete: function(){
console.log('DONE');
}
});
} else if (data.split("::")[1] == false) {
$("#data_status").html("Error occured in Comment Submission.. TryAgain..");
$("#data_status").fadeOut(3000);
}
});
});
All your code does is post the data to the server. There is nothing that fetches the new comments from the server or manually appends the posted comment. You can either use ajax again to refresh comments or more simply append a comment with the posted content.
I would say to search the web for jQuery's .load :
example:
function updateShouts(){
// Assuming we have #shoutbox
$('#shoutbox').load('latestShouts.php');
}
in this case shoutbox would be the containing div with your comments,
you would call this function on the success of your ajax post
latestshouts.php would only contain the content of that div.
kinda hard to explain, i hope it makes sense to you
link: http://api.jquery.com/load/
On the event of a form submit, I have a jquery ajax function that queries for the amount of data uploaded from a file that I can use in making a progress bar. This is my js file:
var submitted = '';
var counter = 0;
$('#webfileuploadform').submit(function(){
if(submitted == 'submitted') return false; // prevents multiple submits
var freq = 1000; // freqency of update in ms
var progress_url = '/upload_progress/' + $('#id_progress_id').val(); // ajax view serving progress info
update_progress_bar();
function update_progress_bar(){
$.ajax({
dataType:"json",
url: progress_url,
success: function(data){
counter ++
console.log('hit success ' + counter);
},
complete: function(jqXHR, status){
if (status == 'success'){
console.log('hit complete', status == success')
} else {
console.lot('hit complete', status == something else')
}
}
});
setTimeout(function(){update_progress_bar()}, freq);
}
submitted = 'submitted'; // marks form as submitted
});
So, the user will use the form to select the file then click submit. This all happens just fine. The form submits, the file is uploaded, and the progress shows just fine when I open my ajax view in a separate tab and keep refreshing it. What I don't understand is why the update_progress_bar function runs once until I stop the page. I'll upload a file but until I click the 'x' on my browser I won't get any of the 'hit success' in my console. After I hit stop, the console spits out the 'hit success ' plus the counter. But I shouldn't have to hit stop to do this. I need this to work when the file is uploading.
Any ideas what my problem is?
**
EDIT
**
Not sure if it makes a difference, but I am doing all this on a django development server. Which I think shouldn't have a problem with two XMLHTTPRequests in the same session.
Try this:
var $submitted = '';
$('#webfileuploadform').submit(function(){
if($submitted == 'submitted') return false; // prevents multiple submits
var freq = 1000; // freqency of update in ms
update_progress_bar();
function update_progress_bar(){
var progress_url = '/upload_progress/' + $('#id_progress_id').val(); // ajax view serving progress info
$.ajax({
dataType:"json",
url: progress_url,
success: function(data){
console.log("hit success");
},
complete:function(jqXHR, status) {
if (status == 'success') {
setTimeout(update_progress_bar, freq);
}
}
});
}
$submitted = 'submitted'; // marks form as submitted
});
As it stands, the code looks good to me. I would add some more console logging to make sure the ajax call is returning with the status you expect:
complete:function(jqXHR, status) {
console.log('got to complete, status: ', status);
if (status == 'success') {
console.log('status is success, calling setTimeout.');
setTimeout(update_progress_bar, freq);
}
}
In the ajax function I set the async setting to false:
$.ajax({
async: false,
...
});
This has solved the problem. I have no idea how. From what I understand, this setting forces the ajax request to wait until all other http requests are finished before allowing it to continue. With that being the case, I have no idea how this works. I'll keep from answering my own question in case someone knows why this is working this way...