Ajax success/error message only displaying once - javascript

I have created a form using php ajax and JavaScript.
With ajax I successfully managed to display an error/success message while staying on the same page.
It works alright if I use console.log to display the error/success message.
But I don't want to display the error message on the console.log
so this is what I did:
$('form.form-style-4').on('submit', function() {
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: method,
data: data,
success: function(response) {
console.log(response);
$('#success-message').html(response);
setTimeout(function() {
$('#success-message').fadeOut('slow');
}, 3000);
}
});
return false;
});
As you can see I created a div called #success-message the reponse is displayed in this div.
My problem now is It only shows the error or success message just once, unless I reload the page.
So my first idea was to reload the entire page every time someone clicks on submit, with javascript like this:
setTimeout(function() {
window.location.reload(1);
}, 2000);
But I don't think that is the way to go.

You have to show your message success-message first
$('#success-message').html(response).show();

Related

jQuery html() is not rendering the content in a div more than once

I am having a div to show the error-popup-message.
<div id="popup-msg"></div>
And, I am making an AJAX POST call to submit login-form and if the server returns success then I am redirecting to other page, otherwise I am showing the error-popup-message. Currently, the html() is rendering the content only once when I am getting error-message from server. But when I again test it (Without reloading the page), the html() is not rendering the content, even though I am getting the error-message from server.
var getErrorPopUpHTML = function (response) {
var html_content = "";
// It returns the html string after processing the response object.
return html_content;
};
var submitSignInForm = async function () {
$("#sign-in-btnn").off("click");
$("form").submit(function (evt) {
var SIGNIN_ROUTE = getSignInEndpoint(); // This fetch the login-endpoint
evt.preventDefault();
var payload = {
email: $("#sign-in-email").val(),
password: $("#sign-in-password").val(),
};
$.ajax({
url: SERVER + SIGNIN_ROUTE, // Endpoint to make the POST call
method: "POST",
data: payload,
async: false,
dataType: "json",
success: function (response) {
resetSignInFormProperties();
if (response.statusCode === 200) {
window.location = response.values[0].link; // Redirecting to other page upon getting success from server
}
},
error: function (response) {
resetSignInFormProperties();
response = $.parseJSON(response.responseText);
var html_file = getErrorPopUpHTML(response);
$("#popup-msg").html(html_file).fadeOut(8000); // Rendering html content on the div: popup-msg
},
});
return false;
});
};
$(document).ready(function () {
$("#sign-in-btnn").on("click", submitSignInForm);
}
Could anyone please point the mistake here?
Thank you!
You fade out the div after showing the error message but never fade it in again. So only the first message is shown.
Fade div in before showing message
$("#popup-msg").fadeIn(0).html(html_file).fadeOut(8000)

AJAX query not always updating information consistently

I am experiecing some issues with AJAX updating the page. The actual data in the database is updated but this is not always reflecting in real time on the web page.
For example, I have the following event:
$("#add_note").click(function(e) {
//e.preventDefault();
$("#add_note_form").validate({
rules: {
contact_note: {
required: true
}
},
submitHandler: function(form) {
contact.modal_update({
'obj' : $('#add_note_form'),
'uri' : '/contact/add_note/'
});
}
});
});
This function when a new note is created calls a callback to validate the form fields first and then if successful calls a callback inside a seperate class to conduct the update. See the modal_update class below:
// Update modal
this.modal_update = function(data)
{//
// Declare a few variables for the data object we've received
obj = data.obj // The form element to serialize
uri = data.uri;
// Get the form ID from the data-target attribute
id = obj.attr('data-target');
// URL to send to
url = this.site_url + uri + id;
// The form object
this.post_data(obj.serialize(),url);
// Hide Modal
obj.closest('.modal').modal('hide');
// Refresh
this.refresh();
}
This then figures out the correct route to ajax and calls a ajax call back inside the same class:
// AJAX post
this.post_data = function(obj,uri)
{
$.ajax({
data: obj,
dataType: 'json',
type: 'post',
url: uri,
headers: { "cache-control": "no-cache" },
cache: false,
success: function (response) {
if (response.success == true)
{
$("#alert_success .msg").html(response.message);
$("#alert_success").fadeIn(200).delay(2000).fadeOut(200);
}
else
{
$("#alert_error .msg").html(response.error);
$("#alert_error").fadeIn(200).delay(2000).fadeOut(200);
console.log(response.error);
}
}
});
}
I am then running another class callback to "refresh" the data in all the elements on the page:
this.refresh = function()
{
// Refresh the ajax requests
this.get_contact_data();
this.get_notes();
this.get_contact_log();
this.get_contact_tasks();
}
This class re loads the functions which run on page load to get the inial data into the tables/fields on the page. See "get_notes" below:
// Get notes
this.get_notes = function()
{
// Get all notes and populate table
var log_uri = this.site_url + "/contact/get_notes/" + this.contact_id;
this.get_data(log_uri,function(data) {
notes = $("#contact_notes ul");
notes.empty("");
// Populate the contact fields, assuming there is a result to play with
if (data != false) {
//alert(JSON.stringify(data));
$("#notes-tab .count").html("(" + data.length + ")");
$.each( data, function( key, value ) {
notes.append("<li class='list-group-item' modal-id='editNoteModal' data-target='" + value.ID + "'><div class='row'><div class='col-lg-3'><i class='fa fa-sticky-note mr-3'></i>" + value.timestamp + "</div><div class='col-lg-7'>" + value.note + "</div><div class='col-lg-2'><a href='#' class='edit mr-3'><i class='fa fa-edit mr-1'></i>Edit</a><a href='#' class='delete'><i class='fa fa-times mr-1'></i>Remove</a></div></div></li>");
});
console.log('Notes loaded');
} else {
notes.append("<li>There are currently no notes for this contact</li>");
}
});
}
Now the problem:
For some reason this does not update consistently in real time. The data is updated fine on the server side but on the client side the update/refresh does not always update. I might add a note and get a correct update response but the refresh method seems to be receiving the old data and always be one note behind. So the next time I add a note, the one I added before then appears and so forth.
Another problem I am experiencing is the methods seem to stack on each event so if I add one note (or one of the other methods) I will see the console say "notes loaded" but on the second note it says "notes loaded" twice, then on the 3rd note added 3 times and so forth.
I am sure there must be something fatal flaw in the design of my code here but I am not experienced enough with javascript/jquery to notice what direction I am going wrong so I can fix it.
I thought that this was an issue with ajax caching and not refreshing the result so I have adjusted the ajax request as cache none and also to send no cache headers. I am running in wamp.
In your case, your refresh code will always run before your data got updated. Because ajax is asynchronous so the code behind and below ajax will always execute nearly the time your ajax running.
At the time you run your post_data function to call the API, the refresh function got run too. So it's done before your data got updated.
You should run refresh function inside ajax callback. For example:
this.post_data = function(obj,uri, callback)
{
$.ajax({
data: obj,
dataType: 'json',
type: 'post',
url: uri,
headers: { "cache-control": "no-cache" },
cache: false,
success: function (response) {
if (response.success == true)
{
$("#alert_success .msg").html(response.message);
$("#alert_success").fadeIn(200).delay(2000).fadeOut(200);
}
else
{
$("#alert_error .msg").html(response.error);
$("#alert_error").fadeIn(200).delay(2000).fadeOut(200);
console.log(response.error);
}
callback();
}
});
}
And in modal_update, you pass refresh function to post_data as a callback:
this.modal_update = function(data)
{//
// Declare a few variables for the data object we've received
obj = data.obj // The form element to serialize
uri = data.uri;
// Get the form ID from the data-target attribute
id = obj.attr('data-target');
// URL to send to
url = this.site_url + uri + id;
// The form object
this.post_data(obj.serialize(),url, this.refresh);
// Hide Modal
obj.closest('.modal').modal('hide');
}
You should read more about asynchronous ajax. You can use other tricky solution is setTimeout to run this.refresh but I do not recommend that because you not sure when the update is done.

Why does my ajax request show error then disappear immediately from firebug console?

I am using ajax to submit form (which is in bootstrap modal) data so after from submit in firebug I error disappear immediately.
$('button#submit').click(function () {
var id = $('#id').val();
var lang = $('#elang').val();
var from = $('#from').val();
var to = $('#to').val();
var subject = $('#subject').val();
var message = $('#message').val();
var file = $('#file').val();
$.ajax({
type:'POST',
url:'http://10.10.1.83/services/mail.php',
data: {
'from': from, 'to': to, 'id': id
},
success: function(msg) {}
});
});
you can use Debug mode to do step by step and get time to see Error,
In developer tools, click the network tab, and make sure that "preserve log" is ticked.

AJAX GET Request to API(Same origin policy does not apply)

I am making an attempt to do a GET through an AJAX request towards an API. I am aware of the same origin policy. But the web service gave me a special API key to perform the GET AJAX request to the API. The problem is that I am not getting either a alert(data) success or alert(boom) error. Nothing is being displayed. The jquery function is taking the value from the textbox and then using that data to perform the api call.
<script>
$(document).ready(function () {
var timer = null;
var $new_result=$("#entry");
var $api = $new_result.data('url',$new_result.val());
function submitForm( input ) {
$.ajax({
type: "GET",
url: $api,
success: function(data) {
alert(data);
},
error: function() {
alert("boom");
}
});
return false
}
$("#entry").on("change", function() {
var input = $(this).val();
clearTimeout(timer);
timer = setTimeout(function(){
submitForm(input) ;
}, 1000);
})
});
</script>
<input type="text" id="entry" name="entry" style="width: 1000px;" value="http://somesite.com/apikey?123658744sdfs88f7></br>
This doesn't look correct at all:
var $new_result=$("#entry");
var $api = $new_result.data('url',$new_result.val());
Rather, if you want to get the value from the input, as you stated, you should use the following:
var api = $("#entry").val();
Unless you've explicitly set the url value on the data object on that input somewhere else in your code, nothing is going to exist there, which may be the cause of your problem.

passing ajax data another page.

I was following an on-line tutorial on JSON. I want to be able to pass the returned data to a results page however I cant get it to work. It just returns null. I am getting the data back because it shows up in the console. N00bie, Help please =)
success: function(data) {
console.log(data);
if(data.success){
resultObject.formSubmitionResult = data;
$.mobile.changePage("#results");
.
$(document).on("pageinit", "#results", function() {
console.log('pageinit event - #results only');
$('#results [data-role="content"]').append('This is a result of form submition: ' + resultObject.formSubmitionResult);
});
var resultObject = {
formSubmitionResult : null
};

Categories

Resources