Json parse and add format - php

I use this in a function:
$.ajax({
type: 'POST',
url: 'demopost.php',
data: { ... },
dataType: 'json',
success: function(data)
{
console.log(data);
}
});
The demopost.php contains only a query.
The output will be:
But how can I show it inside a div? OR How can I add some formation e.g. with foreach like a php array?
EDIT:
I tried with it (the place of console.log(data):
$('.inner').append(data);
Of course there was a div with class inner. But nothing show
EDIT2:
The query in the demopost.php:
... try
{
$c_id = htmlspecialchars($_POST['cid']);
$leftprice = $_POST['left'];
$rightprice = $_POST['right'];
$items=$main->pdo->prepare("SELECT name, price FROM clf_items WHERE category_id IN (
SELECT node.id
FROM clf_category AS node,
clf_category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt AND price BETWEEN :left AND :right
AND parent.id = :c_id)");
$items->execute(array(':c_id' => $c_id, ':left' => $leftprice, ':right' => $rightprice));
$items_array = array();
while ($row = $items->fetch(PDO::FETCH_ASSOC))
{
$items_array[] = $row;
}
echo json_encode($items_array);exit;
}...

What you are doing here is to return some JSON data from the server which can be read by javascript, but is not useful to be pushed into HTML without some processing.
One solution would be to get the JSON array you receive and transform it into a HTML string before pushing it onto the page. This might look like:
success: function(data)
{
var result = '<table>';
for (i=0; i<data.length; i++) {
result += '<tr><td>'+ data[i].name+'</td><td>'+data[i].price+'</td></tr>';
}
result+= '</table>';
$(".inner").html(result);
}
Now this has not money formatting, no html escaping, very crude layout etc pp. Before you try to make this raw sketch into something useful I recommend looking into the various template engines available for jQuery; a few are listed in this post: jQuery Templates are deprecated? (and unlike the question suggests, jQuery templates are not dead, but got some competition).
However I would prefer another approach: create the HTML server side (instead of JSON), so you return a HTML snippet the same way you would return a full HTML page normally in PHP, and in the ajax request say you want HTML: dataType: 'html', and then you can push the result straight into $(".inner").html(data) (or $(".inner").append(data), no idea how your HTML should look like), as you originally wanted.
I guess this is the same as schwierig wanted to say, but I feel one need to tell it more explicit.

For what reason are you using Ajax if you are not processing the data you are sending? If you just want to format the data, you don't really need PHP to do that.
Of course it would be possible. If you want to process with PHP you need to echo your formatted result and use the .done() function as described in the jQuery API
http://api.jquery.com/jQuery.ajax/

$.post('demopost.php',{..}, function(data) {
$('.inner').html(data);
});
try this one hope it will help and make sure you have div with inner class

Related

How to create multidimensial arrays with PHP and access with jQuery?

So I have got to a stage in my website where I need to pack a lot of information into a single json array like object, so in order to do this I need to pack a list of array information under a certain key name, then another set of data under another key name.
So for example:
$array = array();
foreach(action goes here)
{
$array['data1'] = array('information' => data, 'more_information' => more_data)
}
$array['data2'] = array("more data");
This basically illustrates what I am trying to do, I am able to partially do this, however naming the key for the new data set only replaces each data, instead of adding into it in the foreach loops.
Now if this part isn't too confusing, I need some help with this. Then in addition to this, once this is sorted out, I need to be able to use the data in my jQuery response, so I need to be able to access each set of data something like: json.data1[i++].data, which would ideally return "more_information".
You need an incremental number in that loop and make the results available as a json object...
$array = array();
$i = 0;
foreach(action goes here)
{
$array['data'.$i] = array('information' => data, 'more_information' => more_data)
$i++;
}
$array['data2'] = array("more data");
$data = json_encode($array);
Then in php you might set a js var like so:
<script type="text/javascript">
var data = <?php echo $data; ?>;
</script>
which could then be accessed in js easily:
alert(data.data1.information);
If I understand your question correctly you expect to get this object as a response to something? Like a jQuery .ajax call?
http://api.jquery.com/jQuery.ajax/
This link illustrates how to use it pretty clearly. You would want to make sure to specify dataType = "json" and then place your data handling in the success call:
$.ajax({
url: 'some url string',
type: "GET",
dataType: "json",
success: function(data)
{
$.each(data, function(i, v){
console.log(data[i]);
});
},
error: function()
{
//error handling
}
});
This is relatively untested, but the concept is what I am trying to convey. You basically make your multi-dimensional array in php and json_encode it. Either of these methods will allow you to parse the json.

Adding to an array in sqlite3 and passing with json to jquery ajax

I attempt to fill a drop down from a database. I query and add my result to an array. I then use json_encode to send my data to a php file.
$query="SELECT project FROM main";
$results = $db->query($query);
while ($row_id = $results->fetchArray()) {
$proj_option[] = "<option value=\"".$row_id['project']."\">".$row_id['project']."</option>\n";
$pselected=$row_id['project'];
}
$output = array( "proj" => $proj_option);
echo json_encode($output);
In my php file, I use jquery ajax to fill the drop down.
$("#turninId").change(function() {
var user_id = $("#turninId").val();
$.ajax ( {
url:"send_input.php",
type: "POST",
dataType: "json",
data:{id_selection: user_id},
success:function(response) {
for (var i=0; i<response.proj.length; i++) {
$("#exp").html(response.proj[i]);
$("#project").html(response.proj[i]); } });
});
This is great, BUT the only item in my drop down is the last item in the db. For example, my database has the following under Project:
Project: up, down, low, right
But my drop down only fills with the last entry, "right." Why is this? How can I fix it?
PHP json_encode() in while loop was similar, and I made the changes, but there is something missing here.
may be try this
success:function(response) {
$.each(response.proj,function(key,value){
$("#exp").append(value);
$("#project").append(value);
});
}
each time thru your loop in javascript you are overwriting your html. The .html() method sets the innerHTML property of the tag, so each time you call it you are resetting the html and only the last one will show. try not using a loop, instead join you response together and then call .html()
$("#exp").html(response.proj.join(''));
$("#project").html(response.proj.join(''));

Putting mySQL Database Information into a JavaScript Array

What I'm trying to do is create a slideshow by grabbing database information and putting it into a javascript array. I am currently using the jquery ajax function to call information from a separate php file. Here is my php code:
mysql_connect('x', 'x', 'x') or die('Not Connecting');
mysql_select_db('x') or die ('No Database Selected');
$i = 0;
$sql = mysql_query("SELECT comicname FROM comics ORDER BY upldate ASC");
while($row = mysql_fetch_array($sql, MYSQL_ASSOC)) {
echo "comics[" .$i. "]='comics/" .$row['comicname']. "';";
$i++;
}
What I want is to create the array in php from the mysql query and then be able to reference it with javascript in order to build a simple slideshow script. Please let me know if you have any questions or suggestions.
Ok have your .php echo json_encode('name of your php array');
Then on the javascript side your ajax should look something like this:
$.ajax({
data: "query string to send to your php file if you need it",
url: "youphpfile.php",
datatype: "json",
success: function(data, textStatus, xhr) {
data = JSON.parse(xhr.responseText);
for (i=0; i<data.length; i++) {
alert(data[i]); //this should tell you if your pulling the right information in
}
});
maybe replace data.length by 3 or something if you have alot of data...if your getting the right data use a yourJSArray.push(data[i]); I'm sure there's a more direct way actually...
You may want to fetch all rows into a large array and then encode it as a JSON:
$ret = array();
while($row = mysql_fetch_array($sql, MYSQL_ASSOC))
$ret[] = $row
echo json_encode($ret);
Then, on the client side, call something like this:
function mycallback(data)
{
console.log(data[0].comicname); // outputs the first returned comicname
}
$.ajax
(
{
url: 'myscript.php',
dataType: 'json',
success: mycallback
}
);
Upon successful request completion, mycallback will be called and passed an array of maps, each map representing a record from your resultset.
It's a little hard to tell from your question, but it sounds like:
You are making an AJAX call to your server in JS
Your server (using PHP) responds with the results
When the results come back jQuery invokes the callback you passed to it ...
And you're lost at this point? ie. the point of putting those AJAX results in to an array so that your slideshow can use them?
If so, the solution is very simple: inside your AJAX callback, put the results in to a global variable (eg. window.myResults = resultsFromAjax;) and then reference that variable when you want to start the slideshow.
However, since timing will probably be an issue, what might make more sense is to actually start your slideshow from within your callback instead. As an added bonus, that approach doesn't require a global variable.
If this isn't where you are stuck, please post more info.

How to separate data received from $.get() callback function

I have this:
<div ><span id="compareResult"></span> <span id="result"></span></div>
$.get(
'data.php',
{ valA: $(this,'option:selected').val() , valB:$(this,'option:selected').val()},
function(childData){
$('#result').html(childData).css('display', 'none')});>
PHP:
function getData($names,$id,$flag){
if($flag==0){
$strResult = '<select multiple class="sel" id="selectname" size='.count($names).'>';
}
if($flag==1){
$strResult = '<select multiple class="sel" id="selname" size='.count($names).'>';
}
for($i=0; $i<count($names); $i++)
{
$strResult.= '<option value='.$id[$i].'>'.$names[$i].'</option>';
}
echo $strResult.= '</select>';}
How do I break apart/parse the response inside .html(childData) so I can put it in different span(i.e. id="compareResult")?
Thanks in advance.
This doesn't directly answer your question, but it answers what I think the real question might be.
If the data is coming from your own server, I strongly recommend you look at the jQuery Taconite plugin. It makes child's play of doing multiple-element updates via AJAX. All you have to do is make a slight change to the format of how the data is delivered to the browser.
Seriously, check it out.
After you make the html call to update #result's HTML, you will be able to access anything that was inserted inside #result in subsequent calls.
For example:
$.get(
'data.php',
{ valA: $(this,'option:selected').val() , valB:$(this,'option:selected').val()},
function(childData){
$('#result').html(childData).css('display', 'none');
$('#result #someContainer').appendTo('#compareResult');
}
);
I responded to a similar question recently, but you can actually grab any information you might need from the HTML response by creating a jQuery object of the response. For example:
var response = $("<div>This is my element <span class='a-thing'>Thing</span></div>");
alert(response.find('.a-thing').text());
In your callback, you could do the same thing:
$.get(
'data.php',
{ valA: $(this,'option:selected').val() , valB:$(this,'option:selected').val()},
function(childData){
var result = $(childData);
alert(result.find('.some-selector').text());
}
});

Unable to retrieve data using jQuery.post

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!

Categories