update html content automatically - php

I have a temp.php file which gives output in json format:
[{"Date":"2016-10-25 16:12:30","Temp":"1.00"},{"Date":"2016-10-25 16:24:05","Temp":"1.00"},{"Date":"2017-02-25 23:04:04","Temp":"1.00"},{"Date":"2017-02-25 23:05:34","Temp":"1.00"},{"Date":"2017-02-25 23:25:50","Temp":"0.00"}]
I want to load all date and temp values into a webpage. For that, the code I have written is:
<div id ="output"> text replaced </div>
$.ajax({
url:'temp.php',
data : " ",
dataType:'json'
success:function(data)
{
var date = data[0];
var tempval = data[1];
$('#output').html("<b> DATE:</b>"+date+"<b> TEMPER: </b>"+tempval)
}
But I am getting output as object, what is the mistake?

You have to access like below
data[0].Date // 2016-10-25 16:12:30
data[0].Temp // 1.0
OR
data[0]['Date'] // 2016-10-25 16:12:30
data[0]['Temp'] // 1.0
For Example :
var data= [{"Date":"2016-10-25 16:12:30","Temp":"1.00"},{"Date":"2016-10-25 16:24:05","Temp":"1.00"},{"Date":"2017-02-25 23:04:04","Temp":"1.00"},{"Date":"2017-02-25 23:05:34","Temp":"1.00"},{"Date":"2017-02-25 23:25:50","Temp":"0.00"}]
console.log(data[0].Date);
console.log(data[0].Temp);
console.log(data[0]['Date']);
console.log(data[0]['Temp'])
The way you are accessing
success:function(data)
{
var date = data[0];
var tempval = data[1];
$('#output').html("<b> DATE:</b>"+date+"<b> TEMPER: </b>"+tempval)
}
date will be
date = {"Date":"2016-10-25 16:12:30","Temp":"1.00"};
^
This is object inside {}
tempval will be
tempval = {"Date":"2016-10-25 16:24:05","Temp":"1.00"};
^
This is object inside {}
Thus you get below
But I am getting output as , object object
For comment
But this gives data of only first row. I want all
the dates and temp values. What needs to be done?
var data= [{"Date":"2016-10-25 16:12:30","Temp":"1.00"},{"Date":"2016-10-25 16:24:05","Temp":"1.00"},{"Date":"2017-02-25 23:04:04","Temp":"1.00"},{"Date":"2017-02-25 23:05:34","Temp":"1.00"},{"Date":"2017-02-25 23:25:50","Temp":"0.00"}];
$.each( data, function(index,item){
$('#output').append("<b> DATE:</b>"+item.Date+"<b> TEMPER: </b>"+item.Temp+"<br>")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>

Related

How to format 2 variables for 1 ajax call so I can use the data easily?

I have this click event...
$('#save').on('click', function(){
var employee = $('#employee').serialize(); // form with name, phone, email etc.
var training = []; // empty array for now
$('.entry').each(function(){
var tid = $(this).attr('id'); // number
var start = $(this).find('#start').val(); // date
var expiration = $(this).find('#expiration').val(); // date
var entry = [tid, start, expiration]; // create array with data
training.push(entry); // push each entry into array
});
$.ajax({
method: 'post',
url: 'brain.php',
data: {'training':training, 'employee':employee},
success: function(results) {
console.log(results)
}
});
});
The PHP receiving this call looks like this...
$employee = $_POST['employee']; // has string of input values
$training = $_POST['training']; // has array of entries
Now this works, I receive both variables, but they're kinda hard to work with for my purposes, which is putting them into a database. I really don't know how to get the data out easily. I would like something like this...
$firstName = $_POST['employee']['first-name']; // first-name input
$lastName = $_POST['employee']['last-name']; // last-name input
$entry1 = $_POST['training'][0]; // array data found in 0
$entry2 = $_POST['training'][1]; // array data found in 1
My question is, what do I have to change in the javascript or the PHP to get what I want and to make this stuff easier to work with? I think I'm missing a key concept here.
In my opinion, since you don't have much data, you can just manually create an object for the employee instead of using serialize. You can also use objects for your training entries, instead of arrays, then each spot in the training array has one object to represent the training with an ID corresponding to its location in the training array. That's a little wordy, but here's what I mean:
$('#save').on('click', function(){
var employee = {
"first-name":$('#employee').find('[name=first-name]').val(),
"last-name":$('#employee').find('[name=last-name]').val()
};
var training = []; // empty array for now
$('.entry').each(function(){
var tid = $(this).attr('id'); // number
var start = $(this).find('#start').val(); // date
var expiration = $(this).find('#expiration').val(); // date
var entry = {start:start,expiration:expiration}; // create object with data
training[tid] = entry; // push each entry into array, using ID of entry as index
});
var data = {employee:employee, training:training};
//POST function here - use data variable as data
});
And here's a fiddle: http://jsfiddle.net/x2hfb719/

Print an element array in jquery

I have a jquery function that calls a controller which in turn calls a function that I extracted the data from the users table. I return an array cin all the data in the table. ID, username etc etc.. So mold date in jQuery and indeed the array is full. Ex. [{"Id_user": "21", "username": "cassy1994"}].
From this array I have to extract only the username. How can I do?
This is the Ajax function:
$(".apprezzamenti").click(function()
{
var id = $(this).attr('id');
var txt = "";
$.get("http://localhost/laravel/public/index.php/apprezzamenti/"+id,
function(data)
{
$(".modal-body-apprezzamenti>p").html(data);
});
});
If the json is parsed, your object is stored in an array, so:
data[0].username
If not (if it is a string), you need to parse it first:
data_parsed = JSON.parse(data);
// data_parsed[0].username
assuming data is where your response is stored, data[0].username should work. Example:
$(".modal-body-apprezzamenti>p").html(data[0].username);
To print all usernames:
var count = 0;
$.each($(".modal-body-apprezzamenti>p"), function() {
this.html(data[count].username);
count++;
]);
Hope this helps!
So, this is the problem. It's okay though, I realized that with this code I'm using can not seem to generate as many sections as there are users want to print and it shows me only the last username because it can generate only a paragraph in html. A possible solution which would it be?
This is the code:
$(".apprezzamenti").click(function()
{
var id = $(this).attr('id');
var txt = "";
$.get("http://localhost/laravel/public/index.php/apprezzamenti/"+id,
function(data)
{
data_parsed = JSON.parse(data);
for(var i=0; i<data_parsed.length; i++)
{
$(".modal-body-apprezzamenti>p").html((data_parsed[i].username));
}
});
});

jQuery Looping JSON Data

I have created APIs to retrieve data from my server and then I get the data with json format like this :
{
"items": [
{
"2013-03-28": 1771,
"2013-03-29": 1585,
"2013-03-30": 1582,
"2013-03-31": 1476,
"2013-04-01": 2070,
"2013-04-02": 2058,
"2013-04-03": 1981,
"2013-04-04": 1857,
"2013-04-05": 1806,
"2013-04-06": 1677,
"2013-04-07": 1654,
"2013-04-08": 2192,
"2013-04-09": 2028,
"2013-04-10": 1974,
"2013-04-11": 1954,
"2013-04-12": 1813,
"2013-04-13": 1503,
"2013-04-14": 1454,
"2013-04-15": 1957,
"2013-04-16": 1395
}
]
}
How do I looping with my json data dynamically using jQuery?
My code :
<html>
<head></head>
<body>
<script src="jquery-1.9.1.js"></script>
<script>
$(document).ready(function() {
$.ajax({
type : "GET",
url: "myurl.php",
cache: false,
dataType: "jsonp",
success:function(data){
if(data==''){
alert('Fail');
}else{
alert('Success');
}
}
})
});
</script>
</body>
</html>
How do I modify my jQuery to get data dynamically following the date that the data will change every day as in the example I wrote above data??
Thanks before...
There are a few things to consider with your example data, but in your case, the following will do the trick:
var importantObject = data.items[0];
for(var item in importantObject ){
var theDate = item;//the KEY
var theNumber = importantObject[item];//the VALUE
}
Here is a working example
But what does all this mean?...
First of all, we need to get the object that we want to work with, this is the list of dates/numbers found between a { } (which means an object) - an array is defined as [ ]. With the example given, this is achieved like so:
var importantObject = data.items[0];
because items is an array, and the object we want is the first item in that array.
Then we can use the foreach technique, which effectively iterates all properties of an object. In this example, the properties are the date values:
for(var item in importantObject ){ ... }
Because we are iterating the properties, item will be the property value (i.e. the date bit), so item is the date value:
var theDate = item;//the KEY
Finally we get the number part. We can access the value of any given object property by using the string value of the property index (relative to the object), like so:
var theNumber = importantObject[item];//the VALUE
If you already know which date you want the value for, then you can access it directly like so:
var myValue = data.items[0]["2013-04-16"];//myValue will be 1395 in this example
Using jQuery.each() loop through the items
$.each(data.items[0], function (key, value) {
console.log(key + ": " + value);
var date = key;
var number = value;
});
DEMO HERE
You can use the jQuery each function to do this. For example like this:
$.each(data, function(k, v) {
// Access items here
});
Where k is the key and v is the value of the item currently processed.
//get your detail info.
var detail = data.items[0];
$.each(detail, function(key, val) {
console.log(key + ": " + val);
}

json/jquery to second div returns NaN

I'm fetching a row of data from a mysql-server using php, then encode it to a json array. I then pull the information using the following PHP. The strange part is that if I send "vname" to it's own div, I get "NaN" as a result. If I display it in the first div, everything turns out fine. Any idea why? Btw, is it right of me to use .html to send to the div? I've tried .appendTo and .text with the same result.
<h3>Output: </h3>
<div id="output">Content1</div>
<div id="username">content2</div>
<script id="source" language="javascript" type="text/javascript">
$(function() {
$.ajax({
url: 'api.php',
dataType: 'json',
success: function(data) {
var id = data[0];
var vname = data[1];
var message = data[2];
var timestamp = data[3];
$('#output').html(+id + timestamp + message);
$('#username').html(+vname);
}
});
});
</script>
I;m going to guess its because of the first +. Javascript is trying to add nothing to all of the other stuff, which would output a NaN
$('#output').html(id +timestamp +message );
$('#username').html( vname );
In this case text() might be a better to use because there aren't any html elements in your strings, but it really doesn't matter.
+variable is shorthand for casting a variable to a number: Unary plus/minus (MDN)
var x = "5";
+x; //Gives you 5 as a number
x = "Hello";
+x; //Gives you NaN
You can use regular append.
$('#output').append(id + timestamp + message);
$('#username').append(vname);
$('#output').html(+id + timestamp + message);
$('#username').html(+vname);
These are probably your problem. The plus sign in front of the variables would throw an error. If you are trying to concatenate (add together) the existing the value and your response from the ajax change it to some thing like this:
$('#output').html($('#output').html() + id + timestamp + message);
$('#username').html($('#username').html + vname);

Displaying data as a table using $.ajax() and jQuery

I'm new to jQuery and PHP.
I'm developing a web page to display a set of records taken from a database. Here I have used PHP and jQuery.
I need to display a set of records as a table. Data is retrieved from a MySQL database using php. Set of rows is passed to the html page as a string using json_encode().
The problem is that I can't display those data in a table row by row. I'm using a table created with <div>. So I need to know how to display this string of data row by row and separating the value for each column.
Here is what I have done to display only one row, but the data is not displayed as a table. No compile error either. I need help to extend this to display multiple rows too.
demo.html (page I'm going to display the records):
<div class="table">
<div class="headRow">
<div class="cell">ID</div>
<div class="cell">First Name</div>
<div class="cell">Last Name</div>
<div class="cell">Age</div>
<div class="cell">Class</div>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'beta.php' ,
data:"",
dataType: 'json',
success:function(data){
var elementArray = new Array(); //creating the array
elementArray = data.split(""); //splitting the string which was passed using json_encode()
var id = elementArray[0]; //passing values corresponding to the columns
var fname = elementArray[1];
var lname = elementArray[2];
var age = elementArray[3];
var grade = elementArray[4];
$("<div>", { //creating a new div element and assiging the value and appending it to the column 1
"class":"cell",
"text":id
})
.appendTo("document.body");
$("<div>", { //cloumn 2 value
"class":"cell",
"text":fnam
})
.appendTo("document.body");
$("<div>", { //cloumn 3 value
"class":"cell",
"text":lname
})
.appendTo("document.body");
$("<div>", { //cloumn 4 value
"class":"cell",
"text":age
})
.appendTo("document.body");
$("<div>", { //cloumn 5 value
"class":"cell",
"text":grade
})
.appendTo("document.body");
}
});
});
</script>
</div>
</div>
demo.php (retrieving data from the database):
$result = mysql_query("SELECT * FROM student WHERE StuId=1",$con) or die (mysql_error());
$resultArray = mysql_fetch_row($result);
echo json_encode($value);
If someone can help me it would be a great.
try this one....
var id = elementArray[0];
var fname = elementArray[1];
var lname = elementArray[2];
var age = elementArray[3];
var grade = elementArray[4];
then create table using these values something like this....
$("<table>").appendTo("document.body");
$("table").html("<tr><td>"+id +"</td><td>"+fname +"</td><td>"+lname +"</td><td>"+age +"</td><td>"+grade +"</td></tr>);
Here is a Jfiddle, if you use .html and append to a empty table on your page you can append the var contents returned from your ajax query just the same
http://jsfiddle.net/L4G79/1/
this your code will look something like
var id = elementArray[0]; //passing values corresponding to the columns
var fname = elementArray[1];
var lname = elementArray[2];
var age = elementArray[3];
var grade = elementArray[4];
$("table").html("<tr><td>"+id +"</td><td>"+fname +"</td><td>"+lname +"</td><td>"+age +"</td><td>"+grade +"</td></tr>");

Categories