Hello I am trying to parse a .json file.. it only has 1 set of data I don't think the $.each is the best approach but it's all I can find....
Here is my code:
<script type="text/javascript">
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
var url = 'http://f.cl.ly/items/1L2k221B183J1e1G411j/200.json';
/* <![CDATA[ */
$(document).ready(function(){
$.getJSON(url, function(data){
$.each(data.test, function(i,test){
content = '<h1><p class="p1"><span class="s1">' + test.name + '</span></p></h1><table class="table table-bordered"><tbody><tr><td>Section:</td><td>Chemistry</td></tr><tr><td>Synonyms:</td><td>Mg Level</td></tr><tr><td>Container:</td><td>' + test.container + '</td></tr><tr><td>Reference Ranges:</td><td>' + test.reference + '</td></tr><tr><td>Availability:</td><td>' + test.availability + '</td></tr><tr><td>Special Handling:</td><td>' + test.specialHandling + '</td></tr><tr><td>Additional Comments:</td><td>' + test.additionalComments + '/td></tr></tbody></table>';
$(content).appendTo("#main");
$("#main").fadeIn( );
});
});
});
/* ]]> */
</script>
The result kinda works... the table is there but the code loops 3 times and displays "undefined" for all veribles.
Any help would be great!
Just use the result data without a loop. If data.test is not an array, you can access the object properties directly.
something like :
<script type="text/javascript">
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
var url = 'http://f.cl.ly/items/1L2k221B183J1e1G411j/200.json';
/* <![CDATA[ */
$(document).ready(function(){
$.getJSON(url, function(data){
content = '<h1><p class="p1"><span class="s1">' + data.test.name + '</span></p></h1><table class="table table-bordered"><tbody><tr><td>Section:</td><td>Chemistry</td></tr><tr><td>Synonyms:</td><td>Mg Level</td></tr><tr><td>Container:</td><td>' + data.test.container + '</td></tr><tr><td>Reference Ranges:</td><td>' + data.test.reference + '</td></tr><tr><td>Availability:</td><td>' + data.test.availability + '</td></tr><tr><td>Special Handling:</td><td>' + data.test.specialHandling + '</td></tr><tr><td>Additional Comments:</td><td>' + data.test.additionalComments + '/td></tr></tbody></table>';
$(content).appendTo("#main");
$("#main").fadeIn( );
});
});
/* ]]> */
</script>
Try this:
<script type="text/javascript">
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
var url = 'http://f.cl.ly/items/1L2k221B183J1e1G411j/200.json';
/* <![CDATA[ */
$.getJSON(url, function(data)
{
for(var i in data.test)
{
var obj = data.test[i];
var content = '<h1><p class="p1"><span class="s1">' + obj.name + '</span></p></h1><table class="table table-bordered"><tbody><tr><td>Section:</td><td>Chemistry</td></tr><tr><td>Synonyms:</td><td>Mg Level</td></tr><tr><td>Container:</td><td>' + test.container + '</td></tr><tr><td>Reference Ranges:</td><td>' + obj.reference + '</td></tr><tr><td>Availability:</td><td>' + obj.availability + '</td></tr><tr><td>Special Handling:</td><td>' + obj.specialHandling + '</td></tr><tr><td>Additional Comments:</td><td>' + obj.additionalComments + '/td></tr></tbody></table>';
$(content).appendTo("#main");
$("#main").fadeIn( );
}
});
/* ]]> */
</script>
$.each(Object or Array, iterator) is probably what you should use. The real issue is that data.test has to be an Object or an Array, not an Object property that's not an Object or an Array.
Related
I am using node.js first time in my project and i am running my project on WAMP.
I have created app.js and code for my app.js is :
var http = require("http");
var url = require("url");
var qs = require("querystring");
// Create an HTTP server for *socket.io* to listen on
var app = http.createServer();
var io = require("socket.io").listen(app);app.listen(8080);
var authorisedIPs = [
'127.0.0.1',
'192.168.0.204'
];
var clients = {};
function handler(req, res){
var remoteAddress = req.socket.remoteAddress;
if(authorisedIPs.indexOf(remoteAddress) >= 0) {
try{
if(req.method == 'GET'){
var body = '';
req.on('error',function(){
res.writeHead(500, {"Content-Type": "text/plain"});
res.end("Error");
});
req.on('data',function(data){
body += data;
if(body.length > 1e6){
response.writeHead(413, {'Content-Type': 'text/plain'});
req.connection.destroy();
}
});
req.on('end',function(){
var returned = JSON.parse(body);
var client_name = returned.admin_id+'_'+returned.user_id+'_'+returned.login_id;
var channel = returned.channel;
var event = returned.status;
for(var keys in clients){
if(keys == client_name){
var socket_to_send = clients[keys];
socket_to_send.emit(channel,body);
}
}
if(typeof socket_to_send != 'undefined'){
}
});
}
res.writeHead(200, {"Content-Type": "text/plain"});
res.end("ok");
}
catch(error){
res.writeHead(500, {"Content-Type": "text/plain"});
res.end("Error");
}
}
else{
res.writeHead(401, {"Content-Type": "text/plain"});
res.end("Unauthorised");
}
}
function sendData(socket){
var thisRef = this;
var currentTimeObj = new Date();
var formattedTime = currentTimeObj.getDate() + "-" +currentTimeObj.getMonth() + "-" + currentTimeObj.getFullYear() + " " + currentTimeObj.getHours() + ":" + currentTimeObj.getMinutes() + ":" + currentTimeObj.getSeconds();
socket.emit('timeUpdate', { currentTime: formattedTime});
setTimeout(function(){
sendData.call(thisRef,socket)
},1000);
}
function testfunc(socket){
socket.emit('testEvent', { message: 'testing...'});
}
function testfunc1(socket){
socket.emit('testEvent', { message: 'testing1...'});
}
io.sockets.on('connection', function (socket) {
socket.emit('get_name', {});
socket.on('forceDisconnect',function(data12){
for(var keysd in clients){
if (keysd == data12.my_name) {
delete clients[keysd];
socket.disconnect();
}
}
});
socket.on('take_name', function (data11) {
clients[data11.my_name] = socket;
});
});
function getsplitText(string,splitter,index){
return_arr = string.split(splitter);
return return_arr[index];
}
http.createServer(handler).listen(8080, '192.168.0.204');
and my client side html is :
<!DOCTYPE html>
<html>
<head>
<title>Server Time poller</title>
<meta charset="UTF-8">
</head>
<body>
<div id="statusMessageDiv">
</div>
<div id="serverTimeDiv"></div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"> </script>
<script src="192.168.0.204:3000/socket.io/socket.io.js"></script>
<script>
$(document).ready(function(){
alert('hello');
var socket = io.connect('http://192.168.0.204:8080');
socket.on('testEvent',function(data){
$("#statusMessageDiv").html(data.welcomeMessage);
socket.emit('testRevert',{message:'acknowledged'});
});
socket.on('timeUpdate', function (data) {
$("#serverTimeDiv").html(data.currentTime);
});
});
</script>
</html>
When I run app.js on console,I get the response
info - socket.io started.
But when I open index.html in my browser,I get the alert 'hello' and then error
ReferenceError: io is not defined
var socket = io.connect('http://192.168.0.204:8080');
Please help.
After reviewing it properly I think the issue is with your ports:
You use port 3000 here:
<script src="192.168.0.204:3000/socket.io/socket.io.js"></script>
and your app runs on port 8080
I'm trying to load an image (created with PHP) with jQuery and passing a few variables with it (for example: picture.php?user=1&type=2&color=64). That's the easy part.
The hard part is that I've a dropdown which enables me to select background (the type parameter) and I'll have an input for example to select a color.
Here're the problems I'm facing:
If a dropdown/input hasn't been touched, I want to leave it out of the URL.
If a dropdown/input has been touched, I want to include it in the url. (This won't work by just adding a variable "&type=2" to the pre-existing string as if I touch the dropdown/input several times they'll stack (&type=2&type=2&type=3)).
When adding a variable ("&type=2" - see the code below) to the pre-existing URL, the &-sign disappears (it becomes like this: "signature.php?user=1type=2").
Here's the code for the jQuery:
<script>
var url = "signatureload.php?user=<?php echo $_SESSION['sess_id']; ?>";
$(document).ready(function() {
window.setTimeout(LoadSignature, 1500);
});
$("#signature_type").change(function() {
url += "&type="+$(this).val();
LoadSignature();
});
function LoadSignature()
{
$("#loadingsignature").css("display", "block");
$('#loadsignature').delay(4750).load(url, function() {
$("#loadingsignature").css("display", "none");
});
}
</script>
Here's the code where I load the image:
<div id="loadsignature">
<div id="loadingsignature" style="display: block;"><img src="img/loading-black.gif" alt="Loading.."></div>
</div>
I don't know how more further I could explain my problem. If you have any doubts or need more code, please let me know.
Thank you for your help!
EDIT:
Here's the current code:
<script>
var url = "signatureload.php?user=<?php echo $_SESSION['sess_id']; ?>";
$(document).ready(function() {
window.setTimeout(LoadSignature, 1500);
});
$("#signature_type").change(function() {
url = updateQueryStringParameter(url, 'type', $(this).val());
LoadSignature();
});
function LoadSignature()
{
$("#loadingsignature").css("display", "block");
$('#loadsignature').delay(4750).load(url, function() {
$("#loadingsignature").css("display", "none");
});
}
function updateQueryStringParameter(uri, key, value)
{
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i"),
separator = uri.indexOf('?') !== -1 ? "&" : "?",
returnUri = '';
if (uri.match(re))
{
returnUri = uri.replace(re, '$1' + key + "=" + value + '$2');
}
else
{
returnUri = uri + separator + key + "=" + value;
}
return returnUri;
}
</script>
EDIT2:
Here's the code for signatureload.php
<?php
$url = "signature.php?";
$count = 0;
foreach($_GET as $key => $value)
{
if($count > 0) $url .= "&";
$url .= "{$key}={$value}";
}
echo "<img src='{$url}'></img>";
?>
If I understood your question correctly, it comes down to finding a proper way of modifying GET parameters of the current URI using JavaScript/jQuery, right? As all the problems you point out come from changing the type parameter's value.
This is not trivial as it may seem though, there are even JavaScript plugins for this job. You could use a function like this and in your signature_type change event listener,
function updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i"),
separator = uri.indexOf('?') !== -1 ? "&" : "?",
returnUri = '';
if (uri.match(re)) {
returnUri = uri.replace(re, '$1' + key + "=" + value + '$2');
} else {
returnUri = uri + separator + key + "=" + value;
}
return returnUri;
}
$('#signature_type').change(function () {
// Update the type param using said function
url = updateQueryStringParameter(url, 'type', $(this).val());
LoadSignature();
});
Here is a variant where all the data is keept in a separate javascript array
<script>
var baseurl = "signatureload.php?user=<?php echo $_SESSION['sess_id']; ?>";
var urlparams = {};
$(document).ready(function() {
window.setTimeout(LoadSignature, 1500);
});
$("#signature_type").change(function() {
urlparams['type'] = $(this).val();
LoadSignature();
});
function LoadSignature()
{
var gurl = baseurl; // there is always a ? so don't care about that.
for (key in urlparams) {
gurl += '&' + encodeURIComponent(key) + '=' + encodeURIComponent(urlparams[key]);
}
$("#loadingsignature").css("display", "block");
$('#loadsignature').delay(4750).load(gurl, function() {
$("#loadingsignature").css("display", "none");
});
}
</script>
With this color or any other parameter could be added with urlparams['color'] = $(this).val();
Why don't you try storing your selected value in a variable, and then using AJAX post data and load image. That way you ensure there is only one variable, not repeating ones. Here's example
var type= 'default_value';
$("#signature_type").change(function() {
type = $(this).val();
});
then using ajax call it like this (you could do this in your "change" event function):
$.ajax({
type: 'GET',
url: 'signatureload.php',
data: {
user: <?php echo $_SESSION['sess_id']; ?>,
type: type,
... put other variables here ...
},
success: function(answer){
//load image to div here
}
});
Maybe something like this:
<script>
var baseUrl = "signatureload.php?user=<?php echo $_SESSION['sess_id']; ?>";
$(document).ready(function() {
window.setTimeout(function(){
LoadSignature(baseUrl);
}, 1500);
});
$("#signature_type").change(function() {
var urlWithSelectedType = baseUrl + "&type="+$(this).val();
LoadSignature(urlWithSelectedType);
});
function LoadSignature(urlToLoad)
{
$("#loadingsignature").css("display", "block");
$('#loadsignature').delay(4750).load(urlToLoad, function() {
$("#loadingsignature").css("display", "none");
});
}
</script>
i have a upload form that uses the new multiple attribute and i made an ajax upload form to make things more user friendly. My problem is im trying to update percentages for all of these files that are being uploaded and appended to a div, instead of one percentage being updated all of them get updated from the last file. Here is some code.
$('#File').change(function(event) {
for(I = 0; I < this.files.length; I++)
{
var Name = this.files[I].name;
var Size = this.files[I].size;
var Type = this.files[I].type;
$('#UploadContent').prepend('<div class="UploadLabel" style="width:60%;">'+Name+'</div><div class="UploadLabel UploadPercent" style="width:10%;">0%</div><div class="UploadLabel" style="width:15%;">N/A</div><div class="UploadLabel" style="width:15%;">'+Type+'</div>');
var Data = new FormData();
Data.append('File[]', this.files[I]);
var Request = new XMLHttpRequest();
Request.upload.addEventListener('progress', function(event){
if(event.lengthComputable)
{
var Percent = event.loaded / event.total;
var Progress = $('#UploadContent').find('.UploadPercent');
$(Progress).text(Math.round(Percent * 100) + '%');
}
});
Request.upload.addEventListener('load', function(event) {
});
Request.open('POST', '/Home/Upload/Upload.php');
Request.setRequestHeader('Chache-Control', 'no-cache');
Request.send(Data);
$('#UploadModal').fadeIn('fast');
}
});
now as you can see in the progress listener my
var progress = $('#UploadContent').find('.UploadPercent');
how would i select the file that is supposed to be updated correctly. If someone can find a comepletely different method to change the percent that would be great too! - Thanks!
When you're prepending, add a new, specific class (yes, you could use an id, but I'd just stick to class) to the .UploadPercent element:
$('#UploadContent').prepend('<div class="UploadLabel" style="width:60%;">'+Name+'</div><div class="UploadLabel UploadPercent UploadTarget' + I + '" style="width:10%;">0%</div><div class="UploadLabel" style="width:15%;">N/A</div><div class="UploadLabel" style="width:15%;">'+Type+'</div>');
// LOOK HERE----------------------------------------------------------------------------------------------------------------------^ HERE
And when you're targeting, use this:
var progress = $('#UploadContent').find('.UploadTarget' + I);
Because you need the value of I to be accurate based on where you are in the loop, you need to use a closure as well. So your code will end up looking like:
$('#File').change(function(event) {
for(I = 0; I < this.files.length; I++) {
(function (I) {
// Your current code inside the for loop
})(I);
}
});
While the example from above is definitely an option, it probably makes more sent to just store a reference to the newly inserted element and not have to deal with a new class and I, and then use it later.
Here is the final code I'd use:
http://jsfiddle.net/MeL7L/2/
$("#File").on("change", function (event) {
for (var i = 0; i < this.files.length; i++) {
(function (curFile, i) {
var Name = curFile.files[i].name;
var Size = curFile.files[i].size;
var Type = curFile.files[i].type;
var newEl = "";
newEl += '<div class="UploadLabel" style="width:60%;">' + Name + '</div>';
newEl += '<div class="UploadLabel UploadPercent" style="width:10%;">0%</div>';
newEl += '<div class="UploadLabel" style="width:15%;">N/A</div>';
newEl += '<div class="UploadLabel" style="width:15%;">' + Type + '</div>';
newEl = $(newEl);
$("#UploadContent").prepend(newEl);
var Data = new FormData();
Data.append("File[]", curFile.files[i]);
var Request = new XMLHttpRequest();
Request.upload.addEventListener("progress", function (event){
if (event.lengthComputable) {
var Percent = event.loaded / event.total;
var Progress = newEl.find(".UploadPercent");
Progress.text(Math.round(Percent * 100) + "%");
}
});
Request.upload.addEventListener("load", function(event) {});
Request.open("POST", "/Home/Upload/Upload.php");
Request.setRequestHeader("Cache-Control", "no-cache");
Request.send(Data);
$("#UploadModal").fadeIn("fast");
})(this, i);
}
});
I got a script that:
reads urls from a txt file
does some calculations
inserts results into a table
I want to replace txt file with php array. Heres my current code:
<script type="text/javascript">
$.get("imones.txt", function (data) {
var array = data.split(/\r\n|\r|\n/);
var beforeLoad = (new Date()).getTime();
var loadTimes = [];
var beforeTimes = [];
$('#frame_id').on('load', function () {
beforeTimes.push(beforeLoad); /
loadTimes.push((new Date()).getTime());
$('#frame_id').attr('src', array.shift());
try {
$.each(loadTimes, function (index, value) {
var result = (value - beforeTimes[index]) / 1000;
if (result < 0) {
result = result * (-1);
}
$("#loadingtime" + [index]).html(result);
beforeLoad = value;
});
} catch(ex) {}
}).attr('src', array.shift());
</script>
It reads from imones.txt, then inserts each url into a frame, does some calculations, and then inserts results into #loadingtime div. I want to replace imones.txt with a php array. Also i would like the output to be stored in another php array instead of storing it in a div. Can someone help me with this?
Try something like this:
<?php
$str = implode(',',$yourPhpArr);
?>
<script type="text/javascript">
var urls = "<?=$str?>";
var array = urls.split(/,/);
var beforeLoad = (new Date()).getTime();
var loadTimes = [];
var beforeTimes = [];
$('#frame_id').on('load', function () {
beforeTimes.push(beforeLoad); /
loadTimes.push((new Date()).getTime());
$('#frame_id').attr('src', array.shift());
try {
$.each(loadTimes, function (index, value) {
var result = (value - beforeTimes[index]) / 1000;
if (result < 0) {
result = result * (-1);
}
$("#loadingtime" + [index]).html(result);
beforeLoad = value;
});
} catch(ex) {}
}).attr('src', array.shift());
</script>
Let a php file echo your array:
echo Array(1,2,3,4,5);
your html/javascript:
$.get("yourphp.php", function (data) {
var array = data.split(/\r\n|\r|\n/);
var beforeLoad = (new Date()).getTime();
var loadTimes = [];
var beforeTimes = [];
$('#frame_id').on('load', function () {
beforeTimes.push(beforeLoad); /
loadTimes.push((new Date()).getTime());
$('#frame_id').attr('src', array.shift());
try {
$.each(loadTimes, function (index, value) {
var result = (value - beforeTimes[index]) / 1000;
if (result < 0) {
result = result * (-1);
}
$("#loadingtime" + [index]).html(result);
beforeLoad = value;
});
} catch(ex) {}
}).attr('src', array.shift());
</script>
Hi I have the following script to look up an xml file and produce an ordered list
$(document).ready(function() {
$.ajax({
type: "GET",
url: "search_action.php" + string,
dataType: "xml",
success: disxml
});
})
} // function
function disxml(data) {
$(data).find('results').find('client').each(function(row) {
name = $(this).find('name').text();
var add1 = $(this).find('address1').text();
var add2 = $(this).find('address1').text();
var pcode = $(this).find('postcode').text();
var num1 = $(this).find('number1').text();
var num2 = $(this).find('number2').text();
var contact = $(this).find('contact').text();
var email = $(this).find('email').text();
display += "<a onclick='populate();'> <b>" + name + "</b> - " + add1 + "<br></a>";
})
divbox.html(display); // draw contents
}
function populate() {
}
this is the xml file that it is referencing
<results>
<client>
<name>Ascot Racecourse</name>
<address1>Berkshire</address1>
<address2/>
<postcode>SL5 7JX</postcode>
<number1/>
<number2/>
<contact>Alastair Warwick</contact>
<email>As per course</email>
</client>
<client>
<name>Aston Villa Football Club</name>
<address1>Villa Park</address1>
<address2>Birmingham</address2>
<postcode>B6 6HE</postcode>
<number1/>
<number2/>
<contact>Andrew Evans </contact>
<email>Info#avfc.co.uk</email>
</client>
<client>
<name>Asda 1 Year Celebration</name>
<address1>Park In Ipswich</address1>
<address2>Ipswich</address2>
<postcode>IP</postcode>
<number1/>
<number2/>
<contact/>
<email>Jonathan Stephenson</email>
</client>
</results>
it does all work fine , when I have my list I have a link on each line which when clicked calls the function 'populate'
When the script gets to the populate function I am really stuck as how I reference the particular results line that called the function , how can I find this ?
Thanks for any help and I hope it makes sense !!
This should do:
function disxml(data) {
$(data).find('results').find('client').each(function(row) {
var clientItem = this;
var name = $(clientItem).find('name').text();
var add1 = $(clientItem).find('address1').text();
var add2 = $(clientItem).find('address1').text();
var pcode = $(clientItem).find('postcode').text();
var num1 = $(clientItem).find('number1').text();
var num2 = $(clientItem).find('number2').text();
var contact = $(clientItem).find('contact').text();
var email = $(clientItem).find('email').text();
var link = $("<a href='#'><b>" + name + "</b> - " + add1 + "<br/></a>")
link.click(function(evt){
evt.preventDefault();
populate(clientItem);
});
divbox.append(link);
});
}
function populate(item) {
alert("Populating " + $(item).find("name").text());
}