Im trying to create some sort of temporary alert messages using jQuery so a alert message appears (a div with some style and a message ) and then after X seconds dissapear.
If the user clicks again the alert will appear again...
Currently my script is not even removing the alerts. Removing the temp_alert_X name to temp_alert will make them dissapear after X seconds but then if the user clicks again on the button the alert wont come out again until refresh..
function createFarm(){
$.ajax({
url: "ajax/new_farm.php",
context: document.body
}).done(function(data) {
data = jQuery.parseJSON(data);
if(data.error == 1){
$('.sidebar_frame').append("<p><div id='alert_error' class='temp_alert_" + new_farm_error + "'> " + data.log + "</div></p>")
setTimeout(function() {
$('.temp_alert_' + new_farm_error + '').remove()
}, 200)
new_farm_error++;
}else{}
}).fail(function() {
alert( "Error while creating new farm 404." );
});
}
Note:
new_Farm_error = 0
Try to change these lines:
$('.sidebar_frame').append("<p><div id='alert_error' class='temp_alert_" + new_farm_error + "'> " + data.log + "</div></p>")
setTimeout(function() {
$('.temp_alert_' + new_farm_error + '').remove()
}, 200)
with, these:
var $errorMsg = $("<p><div id='alert_error' class='temp_alert_" + new_farm_error + "'> " + data.log + "</div></p>");
$('.sidebar_frame').append($errorMsg);
setTimeout(function() {
$errorMsg.remove();
}, 200)
note. 200 millisecond is a very short time.
You don't need to parse JSON if you use dataType : "json"
$.ajax({
dataType : "json"
//...
});
Related
I am writing some jQuery and Java code that sends an ajax call to my Java backend to do a procedure and then sends the results back to my jQuery. However, when I run a debug I notice that the information is being sent from Java to jQuery successfully, the issue is the jQuery is cutting off the remaing words after the first space. Below is my code and the result.
Jquery:
function fillInGPData() {
$.ajax({
type : "POST",
contentType : 'application/json; charset=utf-8',
dataType : 'json',
url : "/ajax/getGPdata",
data : JSON.stringify(""),
success : function(result) {
console.log("Result Selector: " + result);
console.log(result == null);
$.each(result, function(i, obj) {
console.log("Object: " + obj);
console.log("Tier: " + obj.tier);
console.log( "Selname: " + obj.selname);
console.log("Query: " + obj.query);
console.log("Description: " + obj.description);
console.log("Comment: " + obj.comments);
$(".tableBody1").append(
"<tr id=" + obj.selname + ">"
+ "<td class='sm-width-td'>"
+ obj.selname + "</td>" + "</tr>");
});
},
error : function(err) {
console.log(err);
}
});
}
Result:
<tr id="Windows" file="" share=""><td class="sm-width-td">Windows File Share</td></tr>
So its the obj.selname that is giving the issue. For example, if I pass Windows File Server, it will only show Windows for the ID. That where the problem is. I just need help figuring out why that is the case.
First, I think my title isn't very clear and very representative of what I want to achieve, but I couldn't make it clearer ...
Ok so I have a Leaderboard, created from this ajax call:
$.ajax({
url: '/handler',
dataType: 'json',
success: function(data) {
var tb = document.getElementById('Leaderboard');
while(tb.rows.length > 1) {
tb.deleteRow(1);
};
var keys = Object.keys(data);
for( key of keys) {
var username = data[key].username;
var score = data[key].score;
var row = $('<tr id = "row' + tb.rows.length + '"><td>' + username + '</td><td>' + score + '</td></tr>');
$('#Leaderboard').append(row);
if(tb.rows.length > 11){
tb.deleteRow(tb.rows.length -1);
}
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('Error: ' + textStatus + ' - ' + errorThrown);
}
});
So as you can see in the Leaderboard, when clicking on a username, it opens a new page with the result of a GET request (/leaderboard/:username). My question is how can I skin this page, or even better load an html file in this page, but while keeping accessible the result of the GET request to use it inside?
That may not be clear, and that's maybe a reason why my title is not really fitting ... But anyway if you have some ideas i'll take them !!
Thanks
I have a GET ajax call as follows :
var changeUrl = "changePriority?newValue=" + targetValue + "&justification=" + justification
if (dataInfo == "row") {
changeUrl += "&id=" + id
}
changeUrl += "&executedConfigId=" + executedConfigId + "&currUser=" + currentUser + "&productName=" + productName + "&eventName=" + eventName + "&alertDetails=" + JSON.stringify(alertArray);
//if the selected signal is not null then we show the product names
$.ajax({
url: changeUrl,
type: "GET",
success: function (data) {
for (var index = 0; index < checkedRowList.length; index++) {
var row = checkedRowList[index]
signal.list_utils.change_priority(row, targetValue);
}
$('#change-priority-modal').modal('hide');
if (applicationName == "Signal Management") {
signal.list_utils.set_value(parent_row, 'dueIn', id, signal.list_utils.get_due_in, applicationName);
$(parentField).html(targetValue);
}
location.reload();
},
error: function (exception) {
console.log(exception);
}
});
The value of changeUrl as I get in my browser's developer console is :
http://localhost:8080/signal/singleCaseAlert/changePriority?newValue=Medium&justification=test%20justification%20first.&id=6816&executedConfigId=6704&currUser=15&productName=Wonder%20Product&eventName=1.Pyrexia&alertDetails=[{%22alertId%22:%226816%22,%22event%22:%221.Pyrexia%22,%22currentUser%22:%2215%22}]
But I get a 400 bad request status and a http header parse error in the backend. Can someone help me resolve this?
On your JSON.stringify(alertArray) you'll need to also encodeURI();
encodeURI(JSON.stringify(alertArray));
A better solution would be send your JSON in the body of a POST request if thats feasible within your design
I have several areas in which I need to take information and append it to my main HTML document, from separate pages that are generated with a weather API.
For instance, in the Current Conditions section, I need to reference "http://api.wunderground.com/api/6905d444cd421efb/forecast/geolookup/conditions/q/CT/New_Haven.json" but in my Hourly Forecast, I would need to be drawing the JSON info from "http://api.wunderground.com/api/6905d444cd421efb/hourly/q/CT/New_Haven.json" and then I need to repeat that same process again in a third separate section with another url for a 10 day forecast. Each time I call to a new URL, I will be creating new variables and appending their results to the DOM.
The code that I have below works, but if I try calling to the ajax method a second or third time, it does not work and things either show up as "undefined" or absolutely nothing shows on the page in the other sections. The only thing that remains displayed on my web page is the Current Conditions.
$.ajax({
url : "http://api.wunderground.com/api/6905d444cd421efb/forecast/geolookup/conditions/q/CT/New_Haven.json",
dataType : "json",
success : function(parsed_json) {
var current_icon = parsed_json['current_observation']['icon_url'];
var current_weather = parsed_json['current_observation']['weather'];
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
var current_feels = parsed_json ['current_observation']['feelslike_f'];
var current_humidity = parsed_json ['current_observation']['relative_humidity'];
var current_windDirection = parsed_json ['current_observation']['wind_dir'];
var current_windMPH = parsed_json ['current_observation']['wind_mph'];
$("#icon").append("<img src=' " + current_icon + "' alt='weather icon'/>" );
$("#currentCond").append("Current Conditions: " + current_weather);
$("#currentLoc").append("Location: " + location);
$("#currentTemp").append(" Temp: " + temp_f + "ºF");
$("#currentFeel").append("Feels Like: " + current_feels + "ºF");
$("#currentHumid").append("Humidity: " + current_humidity);
$("#currentWindDir").append("Wind Direction: " + current_windDirection);
$("#currentWindMph").append("Wind Speed: " + current_windMPH + " MPH");
}/* Close Success */
}); /* Close Ajax */
I try adding something like this after the first call is closed out.
$.ajax({
url : "http://api.wunderground.com/api/6905d444cd421efb/hourly/q/CT/New_Haven.json",
dataType : "json",
success : function(parsed_json2) {
var hourly_icon = parsed_json2['hourly_forecast']['icon_url'];
var hourly_icons = parsed_json2['hourly_forecast']['icon'];
$("#icons").append("Icon Type: " + hourly_icons);
$("#icons").append("<img src=' " + hourly_icon + "' alt='weather icon'/>" );
}/* Close Success */
}); /* Close Ajax */
I add variable length list in a view with jquery.
$("#addItemday").click(function() {
$.get("/Course/AddDayNewRow", function(data) {
$("#DayEditorRows").append(data);
}).fail(function(xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
});
});
for every partialview, set a index value.for example
<input name="Days.index" autocomplete="off" value="96633b1d-9c0c-4760-9ca8-474ac28bd52a" type="hidden">
I want to add a script for every partialview.
var objCal1 = new AMIB.persianCalendar("objCal1", "dateid");
After append PartialView, i want to get last item added.
$("input[id*='Date']").last(function () {
var ??? = new AMIB.persianCalendar(???, $(this).attr('id'));});
How do i get last item addes, and set name for this variable?
Two questions, two answer:
1) To get the id of the last item that you added:
var last_id = $("input").last().attr("id");
Remember that you have to wait for your AJAX call to return before firing that, so add it within your AJAX function.
2) Name the variable whatever you like.
Here's an example of the total code:
$("#addItemday").click(function() {
$.get("/Course/AddDayNewRow", function(data) {
$("#DayEditorRows").append(data);
var last_id = $("input").last().attr("id");
var amib_var = new AMIB.persianCalendar(last_id);
// DO SOMETHING WITH THE AMIB_VAR
}).fail(function(xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
});
});