i am new to Javascript and i have created the code below it works fine no problem at all however i want to know what is i want to pull the image dynamically using php and javascript from mysql database how can i refactor my code bellow. thanks in advance for your contribution.
var myimage = document.getelementById("mainImage");
var imageArray =["images/overlook.jpg","images/garden.jpg","images/park.jpg"];
var imageIndex =0;
function changeimage(){
myimage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if(imageIndex >= imageArray.length){
imageIndex = 0;
}
setInterval(changeimage, 5000);
One of several options.
Query the database for the column with the URL of the images.
$query = mysql_query("SELECT url FROM images");
Then something like this to get an array out of it:
$images = array();
while($row = mysql_fetch_array($query)){
$images[] = $row['url'];
}
Then generate this string (that you use in the Javascript provided):
var imageArray = ["images/overlook.jpg","images/garden.jpg","images/park.
using the array you retrieved from the database. You could use json_encode in PHP for this if you don't want to mess around with error prone string building.
$imagesAsJsonArray = json_encode($images);
Echo it. Done.
Not the most elegant of solutions. But it gives you something to play with. Check out a few PHP tutorials online and you'll soon get the hang of it.
Two choices:
Using PHP when your page is created, put an array of images in the page and use page-level javascript to cycle among them.
Using Ajax in the page, call from the page to the server to get the next image and then use client-side javascript to make that returned image visible on the page.
Related
Wizzards :)
I really want to use Quill richtext editor but I have no real knowledge of JSON or how is parses the so called "Deltas".
Basically, I need to collect the page from the editor and process it with php before storing it in the mysql database, and, from the database back to the editor if user wishes to update an existing post. It needs to be able to parse text and multiple images...
I don't have 3 months a piece to learn js/json, can anyone help me out with this one? Thank youuu!
So acording to the Quill documentation (https://quilljs.com/docs/api/) you can use var delta = quill.getContents(); to collect the data. Would it be something like this with an onclick() function? I dont even know with js if it has to be within a form? remember I don't know js :)
<script>
onclick(does this); // or can it be updated as the user creates the document?
var delta = quill.getContents();
// what then?
</script>";
The php would require a different variable if each image to be processed, perhaps in an array?
<?php
$images = array();
$images[0] = 'json/delta/quill image?';
$images[1] = 'etc...';
$images[2] = 'etc...';
$images[2] = 'wtf...';
?>
Why on earth they don't have a simple example of how to do this I don't know, its an all too common problem with these things.
I am doing this animation tool where I fetch a value from my database and then a picture will animate to a certain position. My question is if it is possible to retrieve data constantly or like every 5 seconds?
Somehow like this:
while(autoretreive){
$data = mysql_query("select * from ......");
}
UPDATED from here
Thanks for your answers! Made it a little bit clearer what to do! Maybe I can explain better what I'm doing in my code.
I am doing this animation program as said, where balls with information is moving around to different locations. I have one value that will be updated frequently in the database, lets call it 'city'.
First at previous page I post the balls of information I want based on the 'city' and I do like this (simplified):
$pid = $_POST['id'];
$pcity[0] = $_POST['city'];
$pcity[1] = $_POST['city'];
$pcity[2] = $_POST['city'];
//...
$while(autoretrieve) { // HOW TO?
$data = mysql_query(select * from table where city == $pcity[0] OR $pcity == [1] //...);
while($rows = mysql_fetch_array($data)){
$city = $rows['city'];
$id = $rows['id'];
if($city == example1){
"animate to certain pos"; //attached to image
}
else if($city == example2){
"animate to certain pos"; //attached to image
}
}
}
So for every update in the database the image will animate to a new position. So a time interval of 5 seconds would be great. I'm not an expert in coding so sorry for deprecated code. Not so familiar with AJAX either so what is going to be imported to the code? It is also important that the page is not reloading. Just the fetch from database.
you can do it with ajax and javascript
make one javascript function which contains ajax code to retrive data from database
and at your page load using setTimeout call your ajax function at every 5 second
You can use sleep function to control how often you want to fetch data.
while(autoretreive){
$data = mysql_query("select * from ......");
//output your data here, check more in link about server sent events bellow
sleep(5);
}
Since you haven't specified how you plan to access data I'm writing this answer assuming Server-Sent Events as they are only ones that make sense according to your question.
Now all this was according to your question which wasn't very clear on how do you plan to use data. Again you'll most likely want to fetch data using ajax, but Server Sent Events can also be a good way you could achieve this.
And don't use mysql_* it's deprecated, switch to PDO or mysqli_*
I have this while loop, that basically loops through a lot of records in a database, and inserts the data in another:
$q = $con1->query($users1) or die(print_r($con2->errorInfo(),1));
while($row = $q->fetch(PDO::FETCH_ASSOC)){
$q = $con2->prepare($users2);
$q->execute(array($row['id'], $row['username'])) or die(print_r($con2-errorInfo(),1));
}
(The script has been shortened for easy reading - the correct one has a much longer array)
I would like to do this more graphical, and show a progress bar on how far it has went, instead of just seeing a page loading for a few minutes (there are ~20.000 rows in this one - I have tables with much more data)
I get that you could get the total number from the old database, and I could also easily put the current number into a variable like this:
$q = $con1->query($users1) or die(print_r($con2->errorInfo(),1));
$i = 0;
while($row = $q->fetch(PDO::FETCH_ASSOC)){
$q = $con2->prepare($users2);
$q->execute(array($row['id'], $row['username'])) or die(print_r($con2-errorInfo(),1));
$i++;
}
But now I need to actually fetch $i and display it - or something like it.
How is this "easily" done?
The code for the progress bar can either be in the same document as the while loop, or in another if easier.
You can do a "master" file that does an ajax to this first file to run a single query. You could get all the entry id's in this master file, and then pass it as a parameter to the second file that does a single query. Store these ids in a javascript array.
Create a function that does this, and when the first ajax is done, move to the second element of the id array, and do another ajax with a second parameter. That's how magento imports are done by the way :)
If you need further explanations, let me know, I tried my best to explain, but may have not been perfectly clear.
// you generate this javascript array using php.
// let's say you have all the ids that have to be processed in $Ids php array.
Ids = [<?php echo implode(',', $Ids); ?>];
function doAjax(i) {
$.ajax({ // using jquery for simplicity
'url': "ajax.php?id=" + Ids[i],
}).done(function(){
if ( i >= 0 ) {
// at the point you know you're at ((Ids.length-i)/(Ids.length) * 100) percent of the script
// so you can do something like this:
// $('.progressbar').css('width', ((Ids.length-i)/(Ids.length) * 100) + '%');
doAjax(i-1);
}
});
}
doAjax(Ids.length); // starting from the last entry
So, just to explain what this does. It starts by declaring a global javascript array that has all the ids that will need to be changed.
Then I declare a recursive ajax function, this way we can make sure that only one ajax runs at any single time (so the server doesn't blow up), and we can have a fairly accurate progress. This ajax function does the following:
Sends a request to ajax.php?id=xxx - where xxx is one of the ids in the javascript array.
In the file, we get the id ($_GET['id']), you take it from the old database, and insert it in the new one. This is only for one entry.
when the ajax is done, it goes to the done() function. Since we start the doAjax() function with the last element, we do the next iteration doAjax(i-1). Since we're going backwards in the array, we check if the key is positive. If it's not, the script will stop.
That's about it.
You can't. The php is first interpreted by the server and then send to the user as HTML-Code.
The only possibility would be creating a html-page and call the php-script with AJAX.
So, I'm learning PHP and MySQL, but I have run into a little problem here.
I do lack some information, so this will be very helpful to me =)
I do a query against my database, and get a result. This result is all my image files to be listed.
$fileSQL = $mysqli->query("
SELECT *
FROM content
WHERE projID=$projectID
");
So, if I want to list all my files as thumbnails on my page I do this:
<?php while($row = $fileSQL->fetch_assoc()){ ?>
<img src="assets/<?=$row['contentFull']?>" id="thumbImg"
onclick="document.getElementById('mainImage').src=this.src" width="110px" height="62px"/>
<?php } ?>
Now, this works fine, of course. It loops through all the rows while adding a for each of them.
However, I do have a main image too, where I need to show the first thumb in full (for this example I use contentFull both for thumbs and fullsize).
Now, how do I get the first row's contentFull, without making the while loop start from row nr.2?
And in general; what is the best way to do in these situations? Store the result to an array first, so I can access it easily, or what is the "normal" way of doing it? =)
What I need:
Do a query
Set the main image (using contentFull from the first
image/content in my sql result)
Then draw all the images in the
result to thumbnails (including the first that are already shown as
the main image)
Thanks in advance, and please let me know if you need more information =)
One simple options would be to do this:
<?php
$first = null;
while($row = $fileSQL->fetch_assoc()) {
if(!isset($first)) $first = $row;
?>
<img src="assets/<?=$row['contentFull']?>" id="thumbImg"
onclick="document.getElementById('mainImage').src=this.src" width="110px" height="62px"/>
<?php } ?>
Now you have the first row stored in a variable to use, without having to store all the results in an array. If for some reason you want all rows stored in an array you could simply do this:
<?php
$rows = array();
while($row = $fileSQL->fetch_assoc()) {
$rows[] = $row;
//rest of code
}
?>
Then you could access first row by referencing $rows[0]
Another option would be to not use php to populate the full image. Instead use a javascript call to populate the first image.
I think you could take your first picture outside the while loop:
$row = $fileSQL->fetch_assoc(); // the first picture
if($row){
// show first image if it exists
}
while ( $row = $fileSQL->fetch_assoc()) // etc.
Probably code for larger image is different than for others, so it could be reasonable. If not, consider defining a function, or use a counter (or flag like in Pitchinnate's answer).
I'm trying to build a little script that would let me do this:
http://example.com/appicons.php?id=284417350
and then display this in plain text
http://a3.mzstatic.com/us/r1000/005/Purple/2c/a0/b7/mzl.msucaqmg.png
This is the API query to get that information (artworkUrl512):
http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa/wsLookup?id=284417350
Any help and example code would be much appreciated!
I am not sure why you have jQuery in your tags, unless you want to make the request dynamically without a page refresh. However you can do this simply in PHP using the following example:
$request = array (
"app_id" => #$_GET["id"]
);
// parse the requests.
if (empty($request["app_id"])) {
// redirects back / displays error
}
else {
$app_uri = "http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa/wsLookup?id=" . $request["app_id"];
$data = file_get_contents ($app_uri);
$json = json_decode (trim($data));
print($json->results[0]->artworkUrl100);
}
$request = file_get_contents($itms_url);
$json = json_decode(trim($request));
echo $json[0]->artworkUrl512;
should work in PHP. Unless of course there is more than one hit to the search. A solution using jQuery is probably not very much more difficult.