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.
Related
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
This is what I'm trying to achieve, but my Googling hasn't helped:
I have a button that adds a new row to a table dynamically. I also add a select component to a cell with the same action all in javascript. I'd like for that select component to populate with values from a sql select statement. Of course I don't want to define the connection to the DB in the JavaScript. So I was wondering if there was a way I could call a PHP function to retrieve the values then store it in variable within JavaScript.
PS I understand that PHP is server side as opposed to JS. But surely this is possible.
here's a simple implementation of such a thing using jQuery's ajax and php.
html
<select data-source-url="/category/list"></select>
javascript using jQuery
$("select[data-source-url]").each(function(){
var url = $(this).attr("data-source-url");
var el = $(this);
$.get(url, function(data){
for (i=0;i<data.length;i++){
el.append("<option>" + data[i] + "</option>");
}
},"json");
});
category/list endpoint (a php script)
$list = array();
$list[0] = "category 1";
$list[1] = "category 2";
$list[2] = "category 3";
$list[3] = "category 4";
$list[4] = "category 5";
echo json_encode($list);
a little explanation: what happens is a request being made via the JavaScript client to a php script, which returns an array of values in JSON (which is basically a javascript data-structure), those values are added to the select box dynamically.
Please note that on initial load of the page, the select box will be empty.
yes ofcourse you can. for storing s php variable in a js ariable you can do like this.
before storing it into js variable store the required value in your php variable
var value = '<?php echo $value;?>';
Javascript cannot connect directly to a database.
You want AJAX. A basic flow for this functionality looks like this.
Create a PHP script that connects to the database and gets the options for your select element (let's call it options.php). This script should fetch the options from the database and output them as a JSON array.
In your javascript, you would create an ajax request to options.php. With the JSON data returned from that script, you would loop over each element and create and append a corresponding option element to the dom inside of your select element.
Also consider using jQuery. It greatly simplifies ajax and provides a cross-browser solution.
Option 1
Pass a php array with all possible values to the client side using something like this on the client side:
var opt_values = [<?php echo $php_values; ?>]; //javascript array
or
var opt_values = <?php echo json_encode($php_values); ?>; //json object
Option 2
Another way is making an ajax request. Write a php function that return a JSON object and then you can manipulate the result using jQuery ajax method:
PHP function:
$json = array();
$result = mysqli_query ($connection, $query);
while($row = mysqli_fetch_array ($result))
{
$bus = array(
'id' => $row['id'],
'text' => $row['name']
);
array_push($json, $bus);
}
return = json_encode($json)
Jquery
$('#button-id').click(function(){
//adds a new row to a table dynamically
$.ajax({
type: "get",
dataType: "json",
url: "/get_values.php",
success: function (response) {
var $el = $("#myselect"); //get the select
$el.empty(); // remove old options
//Append the new values
$.each(response, function(key, value) {
$el.append($("<option></option>")
.attr("value", value.id).text(value.text));
});
}
});
});
Just thought i'd put it out there since w3schools is my friend and i kinda follow what they're saying in this post.
W3Schools PHP & AJAX communication
I'm building a search function to retrieve XML data for a google map.
In addition to that, I want to display how many results were actually found.
I thought about doing an echo inside the actual document, however that might mess with my marker data. How would I take a PHP variable and retrieve it in Jquery after a success call?
If my PHP looked like this:
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$num_rows = mysql_num_rows($result);
And Jquery like this:
$.ajax({
type: "POST",
url: "MapSearchxml.php",
data: {
dataFromDate: FromDate,
//lalala
dataHasPatio: HasPatio
},
beforeSend: function (html) { // this happens before actual call
$("#results").html('Please Wait');
$("#searchresults").show();
$(".phpFromDate").html(FromDate);
},
success: function (data, status, jqXHR) {
//Success?
},
dataType: 'xml'
});
Might find it easier to create array in php and send JSON. At client is easy to loop over response object/array
$output=array('status'=>'', 'results'=>array());
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$num_rows = mysql_num_rows($result);
if( $num_rows){
$output['status']='ok';
/* push row data to $output['results'][]; in while loop*/
}else{
$output['status']= 'No results';
}
echo json_encode( $output);
Then in jQuery:
success:function( data){
if (data.status != 'No results' ){
/* count array length*/
var count= data.results.length;
/* loop over data.results array*/
}
}
/* change dataType to "json"*/
I forgot about count and added it in jQuery...can also add a count property to the $output php array and use $num_rows to populate
Just trying out a JSON example for you, this has echo but you can do complex things with it?
Not sure if that is what your after? I get that you don't want to do echo on each variable, and you wont if using JSON.
<?php
$simple = 'simple string';
$complex = array('more', 'complex', 'object', array('foo', 'bar'));
?>
<script type="text/javascript">
var simple = '<?php echo $simple; ?>';
var complex = <?php echo json_encode($complex); ?>;
</script>
You see, what AJAX gets on success is an html code. If you AJAX a complete html page you will get it back, starting with <html> and ending with </html>. You can just make a special markap on your return html data, like [sepcial_info : 'INFO'] or somthing and then just to filter it.
Okay, I needed a bit to decipher your question, probably I'm still wrong, let's try:
What you try to do is not technically possible with what you have in mind. In short: If you do one Ajax request, you return one response. The moment the success function is called, your PHP script is already gone. So you can only pass one return value.
However what you can do is, that you make that return value a nested one, e.g. containing two parts:
The XML document you already returned
The count
That is probably your solution. If you ask how, I would add the count as a namespaced value to the XML and then process it with javascript.
As you have not shown any code here, I can not give a quick example (and I leave that as a pointer for your future questions) for your case. Add a namespace element, like an attribute is pretty simple with DOMDocument in PHP.
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.
I've got a page that seems to be in full working order, but I'm having major performance issues (think 30 second delay occasionally from these calls) from what I assume is throwing too many individual POST requests to the server.
Am I right in thinking that there's some way of doing it all in one call and that doing so would improve performance, and what's the easiest way of doing it? Perhaps my use of eval() is part of the problem - or maybe my webhost is just shit.
function startCheckAchs(){
//hide the loading alert
$(document).ajaxStop(function(){
$(this).unbind("ajaxStop");
popup('loadingAlert');
});
//load lifeTimeBaked
lifeTimeBaked = loadAch("lifetimebaked");
loadAch("ach_started", "#achStarted", "achstarted");
loadAch("ach_round1", "#achRound1", "achround1");
loadAch("ach_round2", "#achRound2", "achround2");
loadAch("ach_round3", "#achRound3", "achround3");
if( rewards == 1) {
loadAch("ach_baked100", "#achBaked100", "achbaked100");
loadAch("ach_baked500", "#achBaked500", "achbaked500");
loadAch("ach_baked1000", "#achBaked1000", "achbaked1000");
loadAch("ach_nobread", "#achNoBread", "achnobread");
loadAch("ach_nodough", "#achNoDough", "achnodough");
loadAch("ach_noflour", "#achNoFlour", "achnoflour");
loadAch("ach_allach", "#achAllAch", "achallach");
}
}
function loadAch(ach, achDiv, achVar){
$.ajax({
type: "POST",
url: "scripts/loadach.php",
data: {"achievement" : ach},
dataType: "text",
success: function(result){
if ( achDiv && achVar && result == 1){
$(achDiv).show();
eval(achVar + " = 1");
return result;
} else {
return result;
}
}
});
}
Loadach.php:
$achievement=trim($_POST['achievement']);
$user = $_SESSION['userid'];
$query = "SELECT $achievement FROM breadusers WHERE userid='$user'";
$link =#mysql_query($query);
if(!$link){
die('Could not query:' . mysql_error());
}
echo mysql_result($link, 0);
?>
You are currently loading achievements individually, while you should be doing something like:
<?php
$query = "SELECT ach_started, ach_round1 FROM breadusers WHERE userid='$user'";
$link = mysql_query($query);
$results = mysql_fetch_assoc($link);
echo json_encode($results);
?>
Then, in your javascript code, parse the JSON response (setting dataType: "json" should work), loop over the returned object (has keys such as ach_started, ach_round1, etc etc), and show/hide divs as needed.
Unfortunately you are going to have to redesign that.
SQL queries are slow.
Lots of requests make things slow.
See if you can group all of the data for a user in your database. That way you can make one select for all of the data you need.
You could use a multi-dimensional array and fill it with the data needed, send the array with ajax to the php code, and then you could loop through the array in the php code and echo back the desired results.
This way you would only be making 1 ajax call each time but still get the same results. might be faster this way but i have not tested this. =)
Most browsers have a limit on the number of concurrent server requests they can handle.
If you're using sessions, you'll also find that the server can only process a single request for each session at a time, because the session file is locked by each request, and subsequent requests must wait for it to be unlocked either when the first request finishes, or when a session_write_close() is issued by the executing request.