Creating error handling in jQuery - javascript

I am trying to create an error message from jquery for my document.
I have populated a <select> menu with JSON data, they link to external HTML files to display weather for their Location, what I need is for an error message to appear if there is no HTML file for the option.
For example the locations are London, New York, Paris and Rome, all except Rome have an HTML file that has weather data in it and displays fine but when Rome is selected...Nothing happens! and when Rome is selected after another location has been selected it stays on the current data!
I am using jQuery to pull the data etc. its my gut feeling that it needs an if() statement but I'm not sure of the conditions of the statement!
My jQuery code is here...
$(document).ready(function () {
// The below function pulls in the data from the external JSON file
$.getJSON('json/destinations.json', function (data) {
// attaches it to a variable
var destinations = data.Destinations;
$(destinations).each(function (id, destination) {
$('#destinations').append('<option value="' + destination.destinationID + '">' + destination.destinationName + '</option>');
});
$("#destinations").change(function () {
$('#weatherForecasts').load('raw_html/' + $(this).val() + '_weather.html .ngtable', function () {
$('#weatherForecasts').show("slow");
});
});
});
// Hide statements for our extra fields and also the weather forecast DIV
$('#weatherForecasts').hide();
$('#extraFields').hide();
$('.errorMessage').hide();
// Function that allows us to see the extraFields when a radio button is checked!
$("input[name='survey1']").change(function () {
$("#extraFields").show("slow");
});
$("input[name='survey1']:checked").change(); //trigger correct state onload
});

http://api.jquery.com/load/
at the bottom of the page there is an example for handling errors:
$( "#success" ).load( "/not-here.php", function( response, status, xhr ) {
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
So in your case
$("#destinations").change(function () {
$('#weatherForecasts').load('raw_html/' + $(this).val() + '_weather.html .ngtable', function (response, status, xhr) {
if (status == 'error'){
// do error things
}else{
$('#weatherForecasts').show("slow");
}
});
});

Related

Bootstrap modal ajax form submited many times

I call form in modal using ajax, and using a modal button .save-modal the form is submitted using ajax. There are many submissions for the form and I don't know why?
The following code in the page -form- requested by the modal:
```
#section('content')
<h1>kk</h1>
<div id="modal">
{!! Form::model('App\Solution',['url' => $actionPath, 'id' => 'sForm', 'class' => 'form-inline']) !!}
<div class="form-group">
{!! Form::label('title', __('Title')) !!}
{!! Form::text('title',$solution->title,['class' =>'form-control']) !!}
#php ($eleE = $errors->first('title'))
{{-- #include('layouts.form-ele-error') --}}
</div>
<div class="form-group">
{!! Form::label('description', __('Description')) !!}
{!! Form::textarea('description',$solution->description,['class' =>'form-control']) !!}
#php ($eleE = $errors->first('description'))
{{-- #include('layouts.form-ele-error') --}}
</div>
{!! Form::close() !!}
<script>
$(document).ready(function(){
$(".save-modal").click(function(e){
alert('many time alert') //
e.preventDefault();
$.ajax({
url: '{{$actionPath}}'+'/?'+Math.random(),
type: "POST",
data: $("#sForm").serialize(),
success: function(data){
$("#modal-body").html($(data).find('#flash-msg'))
$("#actions-modal").modal('hide')
//return true;
},
error: function(xhr, status, response){
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
// $( "#modal-body" ).html( msg + xhr.status + " " + xhr.statusText );
errors = xhr.responseJSON
console.log(errors)
$("#errors").html('');
$.each(errors,function(key, val){
console.log(key)
$("#errors").append('<span class="has-error help-block">'+val+'</sapn>')
//return false;
})
xhr.responseJSON = null;
}
return false;
}
})
return false;
})
});
</script>
</div>
#endsection
The alert after $(".save-modal").click(function(e){... is alerted many time, specially when closing the modal and open it again with repeating trying of save invalidated entries the increase in alert is not fixed i.e it is the sum of invalidated data submission trying in the previous opening of the modal.
The following is the modal code on the base page:
$(".action-create").click(function(e){
e.preventDefault();
alert($(this).attr('href'))
mhd = $(this).attr('title');//$(this).text()+' {{__("for Cavity")}}'+' '+$(this).attr('title');
href = $(this).attr('href')
//console.log(href)
$("#actions-modal").on('show.bs.modal', function(){
$("#modal-hd").html('<h4 style="display: inline">'+mhd+'</h4>');
$("#modal-body").html('<h4>{{__('Loading')}}<img src="/imgs/loading.gif" /></h4>')
gg(href)
})
$("#actions-modal").modal({
backdrop: 'static',
keyboard: false
});
});
$("#actions-modal").on('hidden.bs.modal', function(){
$("#modal-body").html('');
$(this).data('bs.modal', null);
//$(this).children('#errors').html('');
$("#errors").html('');
return false;
});
gg = function gg(){
$.ajax({
type: "GET",
url: href,
dataType: 'html',
success: function(data){
//console.log(data)
required = $(data).find("#modal");
$("#modal-body").html(required);
},
error: function(xhr, status, response ){
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#modal-body" ).html( msg + xhr.status + " " + xhr.statusText+ " With custom message:<br> "+ xhr.responseText );
//console.log(xhr)
}
}
});
return false;
}
I have tried to add return false in many parts of the code to cut any extra evaluation, I also tried to add random number to the ajax URL Math.random() but It seems that it executed many times.
There is also another form call on the same page called using the modal, and sometimes it be saved in addition to the called form!
When you call form using ajax then you should keep in mind that javascript/jquery code of document ready is executed every time you receive response.
so, when you first open you model ".save-modal" click event is binded. when close and reopen the model. again request goes to server ajax content loaded in browser window and again a click event is binded. This way you end up with multiple anonymous function binded to single event. all will execute on same event.
solution 1 (recomanded): Declare function in saperate js file or inline which is included in main page (not ajax). Then instead of binding click event using jQuery. call function from onclick property of your ".save-modal" button.
solution 2: declare a global variable "IsAjaxExecuting". Test if this variable is true then return from you save function (this will stop mutliple execution). if it is not true then make it true. execute you ajax function. when response received then make it false again. eg.
var IsAjaxExecuting= false; // new code
$(document).ready(function() {
$(".save-modal").click(function(e) {
if(IsAjaxExecuting) return; // new code
IsAjaxExecuting = true; // new code
alert('many time alert');
e.preventDefault();
$.ajax({
url: '{{$actionPath}}' + '/?' + Math.random(),
type: "POST",
data: $("#sForm").serialize(),
success: function(data) {
IsAjaxExecuting = false; // new code
$("#modal-body").html($(data).find('#flash-msg'))
$("#actions-modal").modal('hide')
//return true;
},
error: function(xhr, status, response) {
IsAjaxExecuting = false; // new code
if (status == "error") {
var msg = "Sorry but there was an error: ";
// $( "#modal-body" ).html( msg + xhr.status + " " + xhr.statusText );
errors = xhr.responseJSON
console.log(errors)
$("#errors").html('');
$.each(errors, function(key, val) {
console.log(key)
$("#errors").append('<span class="has-error help-block">' + val + '</sapn>')
//return false;
})
xhr.responseJSON = null;
}
return false;
}
})
return false;
})
});

Variable Scope Between JS Functions: Variable Not Defined

I am working on a script that uses jQuery get function to send information to another page and return the data as an alert on current page. I am trying to send the search field value from input form (this works), as well as the collector ID, which is a value generated by an option selected in a drop down menu above the search form.
Unfortunately, I keep getting "collector_id is undefined error" when I run the script. I think I am having an issue with the scope of the variable.. but have tried many options and can't seem to find the solution which keeps the value of collector_id for use in the get function.
$( document ).ready(function() {
$( ".search-field" ).keyup(function() {
//THIS FUNCTION UPDATES THE COLLECTOR ID VARIABLE FROM DROPDOWN MENU VALUE SELECTED BY USER
$( "select" )
.change(function () {
var collector_id = "";
$( "select option:selected" ).each(function() {
collector_id += $( this ).data('value') + " ";
});
})
.change();
//THIS FUNCTION DOES A SEARCH ON ANOTHER PHP SCRIPT PASSING search and collector_id values
if($(".search-field").val().length > 3) {
var search = $(".search-field").val();
$.get("query-include.php" , {search: search, collector_id: collector_id})
.done(function( data ) {
alert( "Data Loaded: " + data );
});
}
});
});
you just need to initialize collector_id outside of the change, so it will be in scope for the $.get
var collector_id = "";
$( "select" )
.change(function () {
$( "select option:selected" ).each(function() {
collector_id += $( this ).data('value') + " ";
});
})
.change();
//THIS FUNCTION DOES A SEARCH ON ANOTHER PHP SCRIPT PASSING search and collector_id values
if($(".search-field").val().length > 3) {
var search = $(".search-field").val();
$.get("query-include.php" , {search: search, collector_id: collector_id})
.done(function( data ) {
alert( "Data Loaded: " + data );
});
}
});

How to properly try and Catch in jQuery

I have the following function, that get a response from a web service. The response should be displayed on one section of the website.
That's working fine, but the thing is, in case of error, I've trying to get the error message and display it in the same way as the succesful response does, but I can't get that.
$(document).ready(function(){
$('.button').click(function(){
try {
var $resp = $.get("service url here", function(resp){
$('.response').append(resp.response.greeting + ", " + resp.response.Welcome);
});
}
catch (err){
$('.response').append(err.name + ", "+ err.message);
}
});
});
Try using .always()
$(document).ready(function(){
$(".button").click(function() {
$.get("service url here")
.always(function(resp, textStatus, jqxhr) {
$(".response")
.append(textStatus === "success"
? resp.response.greeting + ", " + resp.response.Welcome
: textStatus + ", "+ jqxhr
);
});
});

jQuery how to run ajax with hover option and use .ajaxerror to addClass removeClass individual div

I have a page that displays a calendar into with a attribute "data-date" that as a date like: "11/29/2014" and I need to check server if there's a log file for that date and change css for that div on mouse hover.
So far i get this code:
$(document).ready(function() {
var lab = $( ".label.day" ).hover(
function() {
dd = $(this).attr("data-date").split("/");
ddo = $(this).attr("data-date");
dday = ("0" + (dd[1])).slice(-2);
dmonth = ("0" + (dd[0])).slice(-2);
dyear = dd[2];
url = "logs/log." + dyear + "-" + dmonth + "-" + dday;
$.ajax({
type: 'HEAD',
url: url,
error: function(xhr, status, error) {
console.log(status)
},
success: function(xhr, status, error) {
console.log(status)
}
});
$(document).ajaxError(function(event, jqxhr, settings, thrownError) {
console.log(thrownError)
if ( thrownError == "Not Found" ) {
$(".label.day").filter(ddo).addClass( "error" );
}
});
}, function() {
$(".label.day").filter(ddo).addClass( "noerror" );
}
);
});
<div data-date="1/16/2014" class="label day " original-title="Quinta" style="display: block;">16</div>
I can't change the class for the individual , without the .filter it changes all and .attr("data-date") doesn't work also.
There are several issues with your script:
You are not passing any data to the URL specified, via the data object in the $.ajax() function. Also, you need to specify to expected type of data (dataType) received (is it in JSON, plain text or otherwise?).
Use deferred objects and promises to check the status of the AJAX call
Use context, i.e. $(this), in your hover function so you can dictate which elements to modify without doing any filtering.
HEAD is an invalid value for the type object in the AJAX call. You should use POST or GET instead, depending on how the destination script is written to handle incoming data. Here's a good guide to deciding between the two.
Listen to mouseover instead of hover, as you are adding classes based on the status of the AJAX request, not the toggling between mouseover and mouseout events.
Use var when declaring functions to contain/restrict them within the function's scope, otherwise you risk polluting global variables :)
An improved code is as follow, but might not work unless you furnish more details on how you're checking the server for information.
$(document).ready(function() {
$('.label.day').on('mouseover', function() {
// Cache $(this)
var $t = $(this);
// Reset class
$t.removeClass('error noerror');
// Declare variables within function scope (not global)
var dd = $t.attr("data-date").split("/"),
ddo = $t.attr("data-date"),
dday = ("0" + (dd[1])).slice(-2),
dmonth = ("0" + (dd[0])).slice(-2),
dyear = dd[2],
url = "logs/log." + dyear + "-" + dmonth + "-" + dday;
// Perform AJAX call
var $check = $.ajax({
type: 'POST', //or "GET"
url: url;
});
// jQuery deferred object
$check.fail(function(jqXHR, textStatus) {
// If AJAX request failed and returned an error
console.log(textStatus);
$t.addClass('error');
}).done(function(data) {
// If AJAX request is successful
console.log(data);
$t.addClass('noerror');
});
});
});

How to encode URL being passed to div.load()?

I am using a URL rewrite and using
$('#somediv').load(query, function (response, status, xhr) {
if (status == "error") {
var msg = "Sorry there was an error: ";
$("#somediv").html(msg + xhr.status + " " + xhr.statusText);
}
});
But the div.laod() wont work when my query has character like '?','&' and '='.
As in when I pass parameters as shown beloew, div rendering wont happen .
query ="http://vmsbawcm001.ed.cps.something.com/content/pms/Snapshot.html?date=2011-09-30&email=something#gmail.com&view=external"
But this works!
query ="http://vmsbawcm001.ed.cps.something.com/content/pms/Snapshot.html"
So How do I pass parameters in some encoded way? or any other solution for this is welcome, coz I am clueless..
After some more research, I have a doubt that it is only the # symbol which is creating the problem. Is it so? If yes, what is the possible solution fro that?
Thanks,
Adarsh
The second parameter in .load() is for passing query data. Here's the reference: http://api.jquery.com/load/.
Demo: http://jsfiddle.net/ThinkingStiff/EKHbQ/
HTML:
<div id="somediv"></div>
Script:
var uri = 'http://vmsbawcm001.ed.cps.something.com/content/pms/Snapshot.html',
data = {date:"2011-09-30",email:"something#gmail.com",view:"external"};
$( '#somediv' ).load( uri, data, function ( response, status, xhr ) {
if ( status == 'error' ) {
var msg = 'Sorry there was an error: ';
$( '#somediv' ).html( msg + xhr.status + ' ' + xhr.statusText );
};
});

Categories

Resources