I've a php script which loads basically just one csv via:
echo json_encode(file(csvfile.csv, FILE_IGNORE_NEW_LINES));
The output is something like this:
["foo,bar,baz","foo, foo,bar","bla,bla,blubb"]
In my basic html file I load it in this way:
<script>
$(document).ready(function(){
$.getJSON("myphpscript.php", function(data) {
filltable(data);
})
});
function filltable(jqxhr){
var table_obj = $('table');
$.each(jqxhr, function(index, item){
table_obj.append($('<tr id="'+item.id+'"><td>'+item.data+'</td></tr>'));
}).insertAfter('.table');
}
</script>
which fills my <table id="table"></table> just with undefined.
My goal is it to get a table with 1 column containing:
foo,bar,baz
foo, foo,bar
bla,bla,blubb
After specify a delimiter my js-function should explode each line and more columns.
This is my first attempt with javascript and json. Thank you very much
Edit: Fixed function call (Thanks VisioN) . object.length is now ok, but the table is still undefinied
I think you might want to use
table_obj.append($('<tr id="'+index+'"><td>'+item+'</td></tr>'));
instead of
table_obj.append($('<tr id="'+item.id+'"><td>'+item.data+'</td></tr>'));
Your data structure doesn't match the jQuery object parsing schema
You are trying to parse an object that would look like:
[{"id":"foo","data":"foo,bar,baz"}]
For one column You just want
table_obj.append($('<tr id="'+item+'</td></tr>'));
Related
i have this HTML / PHP code:
$notes.='<div class="note '.$color.'" ';
if($row["xyz"] == '') {
$notes.='style="left:45%; top:10%; z-index:0;"><h3 align="center">New Note</h3>';
} else {
$notes.='style="left:'.$left.'px;top:'.$top.'px;z-index:'.$zindex.'">';
}
$notes.=htmlspecialchars($row['text']).'
<a class="closeMessage">X</a><div class="addedby">'.htmlspecialchars($row['addedby']).'</div>
<span class="data">'.$row['sequence'].'</span>
</div>';
there are multiple containing different data from the database
i would like to use ajax to send data to a PHP page using GET, i currently have this:
$('.closeMessage').live('click',function(){
//alert("close");
alert($('span.data').html());
$.get('/includes/sticky_notes/closeMessage.php',{
sequence : $('span.data').html()
});
alert("close");
});
but its passing the incorrect sequence each time. its passing the sequence number of a different row
As your HTML code for the notes have several elements with the class 'data', when you call for $('span.data').html() you will always get the inner html of the first span with the data class.
You can traverse the dom tree and use something like the siblings function.
$(document).ready( function(){
$('.closeMessage').on('click',function(){
//alert("close");
this_data = $(this).siblings('.data').html();
alert(this_data);
$.get('/includes/sticky_notes/closeMessage.php',{
sequence : this_data
});
alert("close");
});
});
In this example we store the data in a variable this_data = $(this).siblings('.data').html(), so we refer to the element that was clicked - $(this) and then go down in the tree until the next element with the class data.
One last thing - consider to use $('.closeMessage').on instead of live as it has been deprecated - http://api.jquery.com/live/
As the title says, I have slickgrid getting/parsing JSON data from PHP, but while I can get it to update to the proper row count, nothing is displayed in a cell unless I edit it first. When I do, the correct data is displayed, but only for cells I have edited. Here is the relevant code:
$(function () {
$.getJSON("./test3.php", function(jsondata) {
$.each(jsondata, function(i, arr) {
var d = (data[i] = {});
$.each(arr, function(key, value) {
d[key] = value;
});
});
grid.updateRowCount();
grid.render();
});
grid = new Slick.Grid("#myGrid", data, columns, options);
//continues function prepping the grid
You might want to go for simpler implementation, there's no need to loop through all your data just dump your "jsondata" directly inside the SlickGrid Object creation.
As long as you have the "data" array into a JSON Object then you're fine. Something like this:
{ "data":[{"id":"84","name" : "Someone" ... ]}
// then pass it to your Slick Object.
grid = new Slick.Grid("#myGrid", jsondata, columns, options);
That's all... Oh and don't forget to have at least have a unique "id" on all rows
You can see example from this web site:
http://joeriks.com/2011/07/03/a-first-look-at-slickgrid-with-read-and-update-in-webmatrix/
I needed to call grid.invalidateRow() on all of the added rows.
I can think of plenty of ways to use ajax to load information from my database. For example: http://www.w3schools.com/php/php_ajax_database.asp
However, I really want to separate my structure (HTML), behavior (JS/AJAX), style (CSS), and data (MySQL + PHP) to keep my website scalable.
The above example shows how to just paste in the HTML via AJAX into the existing HTML doc, but what if I have the HTML already and just want to modify HTML elements via ajax using one MySQL call?
For example
Say I have this structure (HTML)
<body>
<h1 id="first">First name here</h1>
<h2 id="last">Last name here</h2>
<h3 id="email">Email here</h3>
</body>
I currently use PHP to make a MySQL query,
"SELECT * FROM `user` WHERE `id` = ".$id;
And of course I could assign each field to individual PHP vars, $first $last, $email. But then when it comes to using jQuery or plain ol AJAX, how do I use this single MySQL statement and single GET request from AJAX to change <h1>, <h2>, and <h3> in the above example?
I know I can use jQuery selectors
$(document).ready(
$('#first').innerHTML = ?
...
)
But is there an elegant way to load values retrieved from PHP into jQ/js? (Let's assume I'm GETting the php doc via jQ/js).
A nice way might be to use JSON with selectors, so return this from your PHP script:
{
'#first': 'First name updated value',
'#last': 'Last name updated value',
'#email': 'etc.'
}
Then, when retrieving the results (don't forget to use 'json' as your dataType):
for(var x in data) {
if(data.hasOwnProperty(x)) {
$(x).html(data[x]);
}
}
Oh, and jQuery can do that for you too:
$.each(data, function(selector, newContent) {
$(selector).html(newContent);
});
Your PHP can return simple json, like the following:
[{ firstName: "Joe", lastName: "Smith", email: "joe#smith.com" }]
And in your ajax success callback, you can use jsRender to render your html, or in other words, "fill your html with data."
What this looks like...
HTML:
<body>
<div id="personContainer"></div>
</body>
<script id="personTmpl" type="text/x-jquery-tmpl">
<h1>{{=firstName}}</h1>
<h2>{{=lastName}}</2>
<h3>{{=email}}</h3>
</script>
in Ajax success callback:
$.ajax({
...
success: function(data) {
$("#personContainer").html(
$("#personTmpl").render(data);
); // where data is in the json format above
}
});
Similar example here: http://jsbin.com/ihuhep/3/edit
I am currently working on a php/javascript project which retrieves information from a database and json encodes the data. It is supposed to show the values from the database inside a combo box on the web page.
In the PHP script that encodes the mysql data I have the following code:
$query = "SELECT pla_platformName as `platform` FROM platforms";
$result = mysql_query($query);
if ($result)
{
while ($myrow = mysql_fetch_array($result))
{
$output[] = $myrow;
}
print json_encode($output);
die();
}
In the javascript code I have the following:
<script>
$(document).ready(function()
{
getPlatforms();
function getPlatforms()
{
$.post("phpHandler/get-platforms.php", function(json)
{
alert(json);
alert(json.platform);
}
);
}
});
</script>
I have alert(json); which shows the entire json data which looks like the following:
[{"0":"hello","platform":"hello"},{"0":"android","platform":"world"}]
The next alert(json.platform) I am expecting it to show either hello or world or both but on this line it keeps on saying undefined. Why isn't this working and how do I get a specific platform, i.e. either hello, or world.
Thanks for any help you can provide.
You need to first convert your JSON string into an object
var data = $.parseJSON(json);
In this case, the object returned is an array. Try
alert(data[0].platform);
You can skip the first step if you set the dataType option to json in your ajax call.
$.post("phpHandler/get-platforms.php", function(data) {
alert(data[0].platform);
},
'json'
);
See jQuery.post() documentation
Your platform member is defined on each item, you'll have to specify which array item you want the platform for. This should do the trick:
alert(json[0].platform);
I'm assuming that your json parameter actually holds a javascript object, and not simply a string. If it is a string, you should define contentType 'application/json' on your php page. (I'm not sure how you do that in php since I do .NET for server side myself.)
To test it quickly however, you can do a $.parseJSON(json) to get the object.
I'm trying to use jQuery.post() function to retrieve some data. But
i get no output.
I have a HTML that displays a table. Clicking this table should trigger a jQuery.post event.
My scriptfile looks like this:
jQuery(document).ready(function() {
jQuery('#storeListTable tr').click(function() {
var storeID = this.cells[0].innerHTML; //This gets me the rowID for the DB call.
jQuery.post("../functions.php", { storeID: "storeID" },
function(data){
alert(data.name); // To test if I get any output
}, "json");
});
});
My PHP file looks like this:
<?php
inlcude_once('dal.php');
//Get store data, and ouput it as JSON.
function getStoreInformation($storeID)
{
$storeID = "9";//$_GET["storeID"];
$sl = new storeLocator();
$result = $sl->getStoreData($storeID);
while ($row = mysql_fetch_assoc($result)) {
{
$arr[] = $row;
}
$storeData = json_encode($arr);
echo $storeData; //Output JSON data
}
?>
I have tested the PHP file, and it outputs the data in JSON format. My only problem now is to return this data to my javascript.
since the javascript is located in the /js/ folder, is it correct to call the php file by using '../'?
I don't think I'm passing the storeID parameter correctly. What is the right way?
How can I call the getStoreInformation($storeID) function and pass on the parameter? The jQuery example on jQuery.com has the following line: $.post("test.php", { func: "getNameAndTime" }
Is the getNameAndTime the name of the function in test.php ?
I have gotten one step further.
I have moved the code from inside the function(), to outside. So now the php code is run when the file is executed.
My js script now looks like this:
jQuery('#storeListTable tr').click(function() {
var storeID = this.cells[0].innerHTML;
jQuery.post("get_storeData.php", { sID: storeID },
function(data){
alert(data);
}, "text");
});
This results in an alert window which ouputs the store data as string in JSON format.
(because I have changed "json" to "text").
The JSON string looks like this:
[{"id":"9","name":"Brandstad Byporten","street1":"Jernbanetorget","street2":null,"zipcode":"0154","city":"Oslo","phone":"23362011","fax":"22178889","www":"http:\/\/www.brandstad.no","email":"bs.byporten#brandstad.no","opening_hours":"Man-Fre 10-21, L","active":"pending"}]
Now, what I really want, is to ouput the data from JSON.
So I would change "text" to "json" and "alert(data)" to "alert(data.name)".
So now my js script will look like this:
jQuery('#storeListTable tr').click(function() {
var storeID = this.cells[0].innerHTML;
jQuery.post("get_storeData.php", { sID: storeID },
function(data){
alert(data.name);
}, "json");
});
Unfortunately, the only output I get, is "Undefined".
And if I change "alert(data.name);" to "alert(data);", the output is "[object Object]".
So how do I output the name of teh store?
In the PHP file, I've tried setting $storeID = $_GET["sID"]; But I don't et the value. How can I get the value that is passed as paramter in jQuery.post ?
(currently I have hardcoded the storeID, for testing)
Lose the quotes around "storeID":
Wrong:
jQuery.post("../functions.php", { storeID: "storeID" }
Right:
jQuery.post("../functions.php", { storeID: storeID }
bartclaeys is correct. As it is right now, you are literally passing the string "storeID" as the store ID.
However, a couple more notes:
It might seem weird that you will be setting storeID: storeID - why is only the second one being evaluated? When I first started I had to triple check everytime that I wasn't sending "1:1" or something. However, keys aren't evaluated when you are using object notation like that, so only the second one will be the actual variable value.
No, it is not correct that you are calling the PHP file as ../ thinking of the JS file's location. You have to call it in respect of whatever page has this javascript loaded. So if the page is actually in the same directory as the PHP file you are calling, you might want to fix that to point to the right place.
Kind of tied to the previous points, you really want to get your hands on Firebug. This will allow you to see AJAX requests when they are sent, if they successfully make it, what data is being sent to them, and what data is being sent back. It is, put simply, the consensus tool of choice to debug your Javascript/AJAX application, and you should have it, use it, and cherish it if you don't want to waste another 6 days debugging a silly mistake. :)
EDIT As far as your reply, if you break down what you are returning:
[
{
"id":"9",
"name":"Brandstad Byporten",
"street1":"Jernbanetorget",
"street2":null,
"zipcode":"0154",
"city":"Oslo",
"phone":"23362011",
"fax":"22178889",
"www":"http:\\/www.brandstad.no",
"email":"bs.byporten#brandstad.no",
"opening_hours":"Man-Fre 10-21, L",
"active":"pending"
}
]
This is actually an array (the square brackets) containing a single object (the curly braces).
So when you try doing:
alert(data.name);
This is not correct because the object resides as the first element of the array.
alert(data[0].name);
Should work as you expect.
Your JSON is returned as a javascript array... with [] wrapping the curly bits [{}]
so this would work.
wrong: alert(data.name);
right: alert(data[0].name);
Hope that helps.
D
Ok, thanks to Darryl, I found the answer.
So here is the functional code for anyone who is wondering about this:
javascript file
jQuery(document).ready(function() {
jQuery('#storeListTable tr').click(function() {
jQuery.post("get_storeData.php", { storeID: this.cells[0].innerHTML }, // this.cells[0].innerHTML is the content ofthe first cell in selected table row
function(data){
alert(data[0].name);
}, "json");
});
});
get_storeData.php
<?php
include_once('dal.php');
$storeID = $_POST['storeID']; //Get storeID from jQuery.post parameter
$sl = new storeLocator();
$result = $sl->getStoreData($storeID); //returns dataset from MySQL (SELECT * from MyTale)
while ($row = mysql_fetch_array($result))
{
$data[] = array(
"id"=>($row['id']) ,
"name"=>($row['name']));
}
$storeData = json_encode($data);
echo $storeData;
?>
Thanks for all your help guys!