I have the following code reading an XML file and creating variables from some of the values. This is my jQuery:
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'https://status.clook.net/xml/status/harvey.xml',
dataType: 'xml',
success: function(xml){
var http = $(xml).find('http').text();
var ftp = $(xml).find('ftp').text();
var mysql = $(xml).find('mysql').text();
var pop = $(xml).find('pop').text();
var imap = $(xml).find('imap').text();
var smtp = $(xml).find('smtp').text();
var load = $(xml).find('load').text();
$('.http').html(http);
$('.ftp').html(ftp);
}
});
$.ajax({
type: 'GET',
url: 'https://status.clook.net/xml/status/email01.xml',
dataType: 'xml',
success: function(xml){
var ehttp = $(xml).find('http').text();
var eftp = $(xml).find('ftp').text();
var emysql = $(xml).find('mysql').text();
var epop = $(xml).find('pop').text();
var eimap = $(xml).find('imap').text();
var esmtp = $(xml).find('smtp').text();
var eload = $(xml).find('load').text();
$('.ehttp').html(ehttp);
$('.eftp').html(eftp);
}
});
});
This is then being used with the following HTML:
<div class="container">
<h3>Server Status Widget</h3>
<h4>Hosting Server</h4>
<p>
<strong>HTTP: </strong>
<span class="http"></span>
</p>
<p>
<strong>FTP: </strong>
<span class="ftp"></span>
</p>
<h4>Email Server</h4>
<p>
<strong>HTTP: </strong>
<span class="ehttp"></span>
</p>
<p>
<strong>FTP: </strong>
<span class="eftp"></span>
</p>
</div>
What I would like to do now is instead of outputting the variable, show an image based on the variable value. I would like to check if the variable value is OK, and if so display an image in the span, and then if the variable is anything other to show another image.
For instance if the variable http has the value OK, in span .http to show allgood.jpg. If the variable value is anything other than OK to show notgood.jpg.
if (ehttp == "ok") {
var imgsrc = '/images/' + ehttp + '.png';
var img = document.createElement("img");
var img.src = imgsrc;
var target = document.querySelector('.ehttp');
target.appendChild(img);
}
From what I understand of your objective, I'd do something like that.
You could write something like this, with a generalised showResult() function to avoid duplication of code.
$(document).ready(function() {
// Fixed data (adapt as necessary)
var OkText = 'OK';
var paths = {
'goodHttp': '/path/to/good/http/image/',
'badHttp': '/path/to/bad/http/image/',
'goodFtp': '/path/to/good/ftp/image/',
'badFtp': '/path/to/bad/ftp/image/'
};
// Generalised utility function
function showResult(containers, xml) {
var httpText = $(xml).find('http').text();
var ftpText = $(xml).find('ftp').text();
if(httpText === OkText) {
containers.http.html('<img src="' + paths.goodHttp + '"/>');
} else {
containers.http.html('<img src="' + paths.badHttp + '"/>');
}
if(ftpText === OkText) {
containers.ftp.html('<img src="' + paths.goodFtp + '"/>');
} else {
containers.ftp.html('<img src="' + paths.badFtp + '"/>');
}
}
// AJAX
$.ajax({
'url': 'https://status.clook.net/xml/status/harvey.xml',
'dataType': 'xml',
}).then(showResult.bind({
'http': $("span.http"),
'ftp': $("span.ftp")
}));
$.ajax({
'url': 'https://status.clook.net/xml/status/email01.xml',
'dataType': 'xml',
}).then(showResult.bind({
'http': $("span.ehttp"),
'ftp': $("span.eftp")
}));
});
Note the use of Function.prototype.bind() to cater for the differences between the two calls.
A better approach might be to hard code the <img> elements then change their src properties.
Related
I'm working at a comment system for a website.
I am using jquery to update the view after comment under post is posted.
The element I am pushing the comment after post is like this:
<p class="card-text new_comment_{{$i->id}}" style="display:none"></p>
So what I do is
//Manages post in view
jQuery(function ($) {
$(document).ready(function () {
$("body").on("submit", ".dynamic-form", function (e) {
var form_id = '#' + $(this).attr('id');
//removes the 'post_' part from id
var id = this.id.replace('post_', '');
var new_comment_class = '.new_comment_' + id;
var new_comment_class_removal = 'new_comment_' + id;
var comments_id = '#comments_' + id;
var form = $(this);
$.ajax({
url: form.prop('action'),
type: 'post',
dataType: 'json',
data: $(this).serialize(),
success: function (data) {
var resultStr = "";
resultStr = resultStr + "<a href=\"#\">" + data.user_name + " <\/a>" + data.body ;
$(comments_id).find(new_comment_class).html(resultStr).slideToggle(150).promise().done(function () {
$(new_comment_class).fadeIn("fast").toggleClass(new_comment_class_removal);
});
$(form_id).slideToggle(150).promise().done(function () {
$(form_id).fadeOut("fast");
});
}
});
e.preventDefault();
});
});
});
so after the javascript gets executed the element loses the class that permits me to find it in the view so that if the user posts again the body of the post doesn't get appended to that element. But now how do I put a new target element as the original one just above the newly creatded one? like this:
<p class="card-text new_comment_{{$i->id}}" style="display:none"></p>
<p class="card-text">This is the body of the comment</p>
solved using http://api.jquery.com/before/ and some temp variables
I want to append data into divs by passing their id as attributes in a script tag. In this example the first-div should get get 'test1' appended to it, and the second-div should get the 'test2' appended to it.
However, the result it that both 'test1' and 'test2' are appended to second-div. first-div is empty. I'm guessing it has to do with how document.currentScript is functioning. Is there any way to get the result I am looking for?
<div id="first-div"></div>
<div id="second-div"></div>
<script attr1="name1" attr2="name2" to-div="first-div" type="text/javascript">
var this_script = document.currentScript;
var attr1 = this_script.getAttribute('attr1');
var attr2 = this_script.getAttribute('attr2');
var append_div = this_script.getAttribute('to-div');
$.ajax({
url: "/dir?attr1=" + attr1,
type: 'GET',
success: function(data) {
$('#' + append_div).append("test1");
});
</script>
<script attr1="name3" attr2="name4" to-div="second-div" type="text/javascript">
var this_script = document.currentScript;
var attr1 = this_script.getAttribute('attr1');
var attr2 = this_script.getAttribute('attr2');
var append_div = this_script.getAttribute('to-div');
$.ajax({
url: "/dir?attr1=" + attr1,
type: 'GET',
success: function(data) {
$('#' + append_div).append("test2");
});
</script>
Also, in the solution, the scripts cannot have id attributes, which is why I am trying to use document.currentScript.
The reason for this is that the code will be hosted on my servers. The code will append information into the divs the user wants, given parameters passed through attributes on the script tag. In the end the user should be able to use:
<script attr1="var1" attr2="var2" to-div="custom-div" src="http://www.myurl.com/assets/script.js" type="text/javascript"></script>
To insert data into their custom-div based on code I run on my servers dependend on the parameters attr1 and attr2 they provide.
Your problem is that var append_div is a global variable and each time a new script tag is encountered it gets overwritten with the new value.
Since ajax is asynchronous , by the time the responses return the other script tags will have been evaluated so append_div will have the value of the last script tag.
You could fix this by creating a function that wraps the ajax
function doAjax(elementId, attr1) {
$.ajax({
url: "/dir?attr1=" + attr1,
type: 'GET',
success: function (data) {
$('#' + elementId).append("test2");
}
});
}
doAjax(append_div, attr1);
An even better solution as pointed out by #Rhumborl is to use an IIFE
(function( elementId, attr1){
$.ajax({
url: "/dir?attr1=" + attr1,
type: 'GET',
success: function (data) {
$('#' + elementId).append("test2");
}
});
}(elementId, attr1);
Or wrap all of your code in an IIFE and no arguments would need to be passed in.
(function(){
var this_script = document.currentScript;
var attr1 = this_script.getAttribute('attr1');
var attr2 = this_script.getAttribute('attr2');
var append_div = this_script.getAttribute('to-div');
$.ajax({
url: "/dir?attr1=" + attr1,
type: 'GET',
success: function(data) {
$('#' + append_div).append("test2");
}
});
}();
After searching here on SO and google, didn't find an answer to my problem.
The animation doesn't seem to trigger, tried a simple alert, didn't work either.
The function works as it is supposed (almost) as it does what i need to, excluding the success part.
Why isn't the success event being called?
$(function() {
$(".seguinte").click(function() {
var fnome = $('.fnome').val();
var fmorada = $('.fmorada').val();
var flocalidade = $('.flocalidade').val();
var fcodigopostal = $('.fcodigopostal').val();
var ftelemovel = $('.ftelemovel').val();
var femail = $('.femail').val();
var fnif = $('.fnif').val();
var fempresa = $('.fempresa').val();
var dataString = 'fnome='+ fnome + '&fmorada=' + fmorada + '&flocalidade=' + flocalidade + '&fcodigopostal=' + fcodigopostal + '&ftelemovel=' + ftelemovel + '&femail=' + femail + '&fnif=' + fnif + '&fempresa=' + fempresa;
$.ajax({
type: "GET",
url: "/ajaxload/editclient.php",
data: dataString,
success: function() {
$('.primeirosector').animate({ "left": "+=768px" }, "fast" );
}
});
return false;
});
});
you are trying to pass query string in data it should be json data.
Does your method edit client has all the parameters you are passing?
A simple way to test this is doing the following:
change this line to be like this
url: "/ajaxload/editclient.php" + "?" + dataString;
and remove this line
data: dataString
The correct way of doing it should be, create a javascript object and send it in the data like so:
var sendData ={
fnome: $('.fnome').val(),
fmorada: $('.fmorada').val(),
flocalidade: $('.flocalidade').val(),
fcodigopostal: $('.fcodigopostal').val(),
ftelemovel: $('.ftelemovel').val(),
femail: $('.femail').val(),
fnif: $('.fnif').val(),
fempresa: $('.fempresa').val()
}
$.ajax({
url: "/ajaxload/editclient.php",
dataType: 'json',
data: sendData,
success: function() {
$('.primeirosector').animate({ "left": "+=768px" }, "fast" );
}
});
Another thing shouldn't this be a post request?
Hope it helps
I have a few images, like
<img src="unstarred.png" class="unstarred-button" id="unstarred-1" />
<img src="unstarred.png" class="unstarred-button" id="unstarred-2" />
<img src="unstarred.png" class="unstarred-button" id="unstarred-3" />
<img src="unstarred.png" class="unstarred-button" id="unstarred-4" />
Then I bind this function:
$('.unstarred-button').click(function() {
id = $(this).attr('id').replace(/^unstarred-/, '');
url = '/star.php?id=' + id;
$.ajax({
type: 'GET',
url: url
}).done(function() {
// What should be put here?
});
});
Now I don't know how to go forward. I want to change the src attribute of the clicked image in the done() call, but $(this) doesn't return the image clicked for sure, as $(this).attr('id') is undefined according to alert().
Could someone help me out?
That's because this within the context of done doesn't refer to img. You need to save the context in the click event handler:
$('.unstarred-button').click(function() {
var self = $(this);
id = self.attr('id').replace(/^unstarred-/, '');
url = '/star.php?id=' + id;
$.ajax({
type: 'GET',
url: url
}).done(function() {
self.attr('src', 'something.jpg');
});
});
Also, you don't need jQuery to change the src or an id of a DOM element, you can change the attribute directly, i.e., this.src = 'something.jpg or this.id = 'new_id'.
$('.unstarred-button').click(function() {
var that = this;
var id = this.id.replace(/^unstarred-/, '');
var url = '/star.php?id=' + id;
$.ajax({
type: 'GET',
url: url
}).done(function() {
that.src = 'some/new/src.jpg';
});
});
Hi I have the following code in a javaScript file called songs:
var marchMD = new Array();
marchMD[0] = ["Save the Best for Last - Vanessa Williams"];
marchMD[1] = ["Informer - Snow"];
marchMD[2] = ["The Sign - Ace of Base"];
for (var i=0;i<marchMD.length; i++) {
songList = songList + '<p>' + marchMD[i] + '</p>';
}
$('#songs').html(songList);
Once this has been loaded, the follow javaScript in the file youtube reacts with the code above:
$(document).ready(function() {
$('#songs p').click(function(e) {
var $el = $(e.currentTarget);
var search = $el.html();
//alert(search);
//return;
var keyword = encodeURIComponent(search);
var yt_url = 'http://gdata.youtube.com/feeds/api/videos?q=' + keyword + '&format=5&max-results=1&v=2&alt=jsonc';
$.ajax({
type:"GET",
url: yt_url,
dataType: "jsonp",
success: function(response) {
if(response.data.items) {
$.each(response.data.items, function(i, data) {
var video_id = data.id;
var video_frame = "<iframe width='420' height='315' src='http://www.youtube.com/embed/" + video_id + "' frameborder='0' type='text/html'></iframe>";
$("#ytVid").html(video_frame);
});
} else {
$("#ytVid").hmtl("<div id='no'> No Video</div>");
}
}
});
});
});
The alert that I have in the code above was a test to see if it would return anything and it doesn't. However, if I remove the href html tag from the code this works. The reason I have it is so when someone clicks one of the songs, it takes them to the top of the page to view that song in youtube.
Thanks
If you know that the element that contains your link will only ever contain your link, you could use text() to strip out the HTML formatting, like this:
var search = $el.text();
When you have the <a> in there, var search = $el.html(); includes the tag as well, not just the text. Try this:
$('#songs p').click(function(e) {
var search = $(this).find('a').html();