I am trying to get the image links from 9gag (what also works) and when I click on a button the image changes to the next one. The basic problem is that it works only once. I can then switch between the 1st and the 2nd image, though. This should be pretty simple, but I ´ve got no clue where the error is, so thanks in advance to anyone bothering to look at this.
<?php
$index = 0
$html = file_get_contents("http://www.9gag.com");
preg_match_all( '|http://d24w6bsrhbeh9d\.cloudfront\.net/photo/.+?\.jpg|', $html, $gags);
?>
<script>
function nextImg(){
<?php $index++;?>
pic.src='<?php echo $gags[0][$index];?>';
}
function prevImg(){
<?php $index--;?>
pic.src='<?php echo $gags[0][$index];?>';
}
</script>
You can't increment your PHP variables after the page has loaded. You are trying to increment them client-side with JavaScript. You are going to need to call that PHP using AJAX if you want to do this without refreshing the page, and even then you'll want to increment a javascript variable to keep track of where you are.
EDIT: I went a little nuts creating an ajax routine using PHP and JavaScript, specifically the jQuery library, which you will need to link to for this to work. You may also need to modify parts of the script to work with what you're trying to accomplish, but this certainly is a guide for running your ajax app as you're hoping to.
Start by making a PHP file with this script:
<?php
// Set content header to json
header('Content-Type: application/json');
// Get the index from the AJAX
$index = $_GET['index'];
// Grab file contents & parse
$html = file_get_contents("http://www.9gag.com");
preg_match_all( '|http://d24w6bsrhbeh9d\.cloudfront\.net/photo/.+?\.jpg|', $html, $gags);
// Send filename back to AJAX script as JSON
echo json_encode(array($gags[0][$index]));
?>
Then, in your HTML, include this jQuery to complete AJAX calls to your PHP script, and update the DOM with the data from the PHP script.
<script>
$(function() {
'use strict';
// Initiate index variable
var index = 0;
// Load initial image
loadImage(index);
// Add click event to a button with class of next-btn
$('.next-btn').click(function(e) {
e.preventDefault();
// Increment index to get next image
index++;
// Run AJAX function to retrieve image
loadImage(index);
});
// Add click event to a button with class prev-btn
$('.prev-btn').click(function(e) {
e.preventDefault();
// Decrement the index if it isn't 0
if (index > 0) {
index--;
}
// Run AJAX function to retrieve image
loadImage(index);
});
});
function loadImage(index) {
'use strict';
$.ajax({
type: 'GET',
url: 'your-php-script.php', // Filepath to your PHP script
data: 'index='+index, // Index is passed through GET request
dataType: 'json', // Return JSON
success: function (data) { // If the php script succeeds
// Change img with class of pic's src
// to the filename retrieved from php
$('.pic').attr('src', data[0]);
}
});
}
</script>
Configuring this for your needs will require some serious PHP and jQuery/JavaScript knowledge, as some debugging will likely be needed. Good luck!
EDIT 2:
I uploaded the working (tested, it works) source files to my website if you want to download. Please accept answer and let me know you grabbed the files...
http://www.wedgewebdesign.com/files/ajax-image-loader.zip
#Eric basically has it right but didn't really go into detail if you aren't familiar with the model...
PHP is a server side language in that it does all its processing on the web host server and once it is complete sends a static result back to the user. This means, whatever you see after the page is loaded within PHP is there to stay, unless you do one of two things:
1) Send a new request -- You provide different parameters, the page re-executes its logic and returns a new result to the user
2) Execute some form of clientside Javascript. Javascript is different from PHP in that it executes on the client (not the server) so you don't necessarily have to send responses back to the server unless you need more information. Javascript and PHP can be combined to create AJAX calls which allow the client to make asynchronous calls to the webserver for more data without reloading the entire page. The Javascript handles re-drawing the new information or updating the page which can appear seamless to the user.
What you therefore need is one of those two options. Either you provide 'next'/'previous' links to the user and the page is loaded differently each time or you create an AJAX call that fetches the url of the next image and then loads it.
Try assigning a variable to $gags[0][$index]. Something like
$imgsrc = $gags[0][$index];
and then
pic.src='<?php echo $imgsrc; ?>';
Related
If someone click on clickme div the counter increases in the database. Currently when the page refresh the counter increases.
<div class="Hello">Click Me</div>
<?php
$find_counts = mysqli_query($conn, "SELECT * FROM ad_section");
while($row = mysqli_fetch_assoc($find_counts)){
$current_counts = $row['no_of_clicks'];
$new_count = $current_counts + 1;
$update_count = mysqli_query($conn, "UPDATE `ad_section` SET `no_of_clicks`= $new_count");
}
?>
Alright... so I am going to help you understand what AJAX is in a simplified practical manner.. because once you understand AJAX.. You'll be able to solve this and many other problems.
AJAX is not a 'language' or a 'technology' .. It's just an upgrade to how browsers can interact with servers.
Earlier (before AJAX, long before AJAX), when a browser had to request data/page from the server, it had to either refresh the page or request a whole new page.. and display it on a new window.. but it had absolutely no way of doing so in the "background" .. and then updating the currently displayed HTML page without any disturbance.
This is what AJAX solves.
So now.. through Javascript or Jquery.. (same thing) .. you can send a request to a server (to any end point on any web-server) with data... and the server.. then potentially has the ability to read the data you sent, process it in any way..and return back result in the form of data ..
The data going and coming is in the format of JSON (Javascript Object Notation) ..which is nothing but a way to encode data and arrays
So you send a JSON and the server gives you a back a JSON or an error page (404, etc.. )
The magic happens now...
Your page.. after receiving back the result from the server.. still on the same function execution that had sent the request ... will be able to open up the result.. and using Javascript/Jquery/DOM Manipulation.. plug in the results to the current HTML page or take any new action.. like display an alert, redirect, animate, etc..
So this is how it works:
Imagine you got a DIV upon which a click should set data update on the server and then get result from the server and refresh itself..
<div id='clickme'>People clicked ... <span id='howmany'>1</span></div>
<script>
//Not accurate code, I'm just writing from what I remember .. jquery
$('#clickme').click(function() {
//event captured on click on 'click me'
var nothing = ''; //there is no data to be sent, really.. because we will be getting the update from the server on how many people have clicked it..
//AJAX NOW... //sending a post request
$.post(
'https://mywebsite/index.php/incrementMe',
{data:nothing},
function(data)
{
//this is the function that will receive in its data the result back from the web-server function incrementMe
var result = JSON.parse(data); //parsing the JSON into javascript object/array
$('#howmany').html(result['updatedInfo']); //updatedInfo is the variable within the result that was sent back from the server.. which I then.. using DOM manipulation, plug it back into the span ID
}
);
//End of AJAX request... you didn't have to refresh the page..
</script>
On the server.. you'd have something like this: (writing PHP YII style)
public function actionincrementMe()
{
$data = json_decode($_POST['data']); //got the posted variable and decoded using a PHP function .. to get a PHP array/object
//well in fact, you don't even need this.. because.. there is no info coming to you from the front end .. but if you had, then this is how you'd receive it..
$newnumber = SQL to find out latest number + 1;
print json_encode($newnumber); //this is the function that will just answer back the front-end with a json formated data point..which is the variable new number..which you would then have received in the javascript function.
}
One of the ways is by doing it like this (only the steps i have included)
- Create a table with image id and click counter
- Implement a function on the image click or div click (if there are more images then you can use a generalized image click function
- Inside the function use ajax to implement the count increasing functionality
the log file will be in notepad format the values will be like this 11.23445646,56.3456578954
10.23445646,26.3456578954
16.23445646,-46.3456578954
I'm planning to get the data from server to website textbox, of first value which I marked as italic the values will change after few seconds the updated value will come first. I tried some PHP example but not getting it in the below text box the values I need to get.. for example: x=11.23445646, y=56.3456578954, pls guide me
Longtitude <input id="x" type="number" value = "" onkeyup="updateMarker('x')">
Latitude <input id="y" type="number"value = "" onkeyup="updateMarker('y')">
Updated Answer
You can do this now using Web Socketing. Here is a guide and hello-wrold example of a php websocket server:
http://socketo.me/docs/hello-world
And to see how to implement client side javascript of websocket, you can see the bottom of the link put above, which shows you this snippet:
var conn = new WebSocket('ws://localhost:8080');
conn.onopen = function(e) {
console.log("Connection established!");
};
conn.onmessage = function(e) {
console.log(e.data);
};
Old
PHP does not support live connections generally in the way you expect, you have to simulate it via repeated AJAX request. How? For instance on each second, or each two seconds.
You first have to write an ajax in your HTML with jQuery library:
Sending a request each second:
var url = "url_to_you_file";
var textarea_id = "#textarea";
setInterval(function(){
$.ajax({
url : "site.com/get-file-logs.php",
type : "POST",
success : function(data){
$(".textarea").html(data);
}
});
}, 1000);
Then in PHP file you would write this:
$file_path = "path_to_your_file";
$file_content = file_get_contents($file_path);
echo $file_content;
The above example gets the file content and sends it back to your browser. You may want to process it in a certain way; that then changes your approach a little bit. Because you must always stick to JSON format when you try to get data back from server to be manipulated by Javascript.
PHP doesn't really do "live" page updates since normally when a web browser (or other user agent) loads a web page once it's done downloading the page then PHP is already finished and can't touch what's already on the client.
Best way to do this would probably be to use a JavaScript AJAX call to periodically load the updated values from a PHP script and then update the values on the page.
Or if it's a really small page (in byte size) you could just make it automatically reload the whole page (with updated values) if that is not a problem for you.
In any case every time the PHP script is called it would just open the file in read mode and only read the latest values from the beginning of the file and return those. See fread(). Or maybe file_get_contents() or file() would be easier and just read the first line.
AJAX is a bit larger topic and I don't currently have the time to explain the whole process of updating the page using JavaScript. Google is your friend.
I use jquery to set a get query to a php script which then queries the database and writes to the screen, but I can't get it to trigger the download, even with headers.
The steps are as follows:
create a link that the user clicks to download the data
javascript sends the query parameters to php
php queries the database and writes the file
client downloads the file
But I can't get step 4 to happen.
Step 1: (this is a table object that also contains the parameters:
d3.select("#some-div").append('a")
.attr("href", "javascript: void(0)")
.on("click", function() { this.saveAsCSV() };
Step 2: Javascript file to make query:
var saveAsCSV = function(params) {
var tmp_params = $.extend({}, params);
tmp_params['State'] = "NM";
$.get('php/get_data.php', tmp_params);
}
php to return query:
...
header("Content-type: application/text-csv");
header("Content-Disposition: attachment; filename=query_result.csv");
while($row = $result->fetchArray() {
print "$row";
}
...
It works fine in that it correctly queries and will print the data in the javascript function (so it will print it to console.log if I add that into the get return function), but I can't figure out what I should do differently to make it just download it directly.
One thing I've tried is to do the following on the params object:
var param_string = encodeURIComponent(JSON.stringify(params));
location.href = 'http://www.mysite.com"+param_string;
But that both takes the user away from the page and fails to download the data.
EDIT: I should clarify that the php file does output the query well in csv format. The problem seems to be that using the $.get() function does not trigger a download regardless of the php headers. Maybe I need to just provide a simple link with the parameters in the URL address, but I'm not sure how to get a javascript object into a URL format so that the php script can interpret it.
You could open a popup/new window/tab/whatever with your URL php/get_data.php?State=NM (perhaps additional parameters). It should download the output.
But your output might be wrong because you just print the variable $row which is an array. If you try to print an array that way it will just show Array.
You will need to properly output your rows. Unfortunately I don't know the CSV structure well enough to help you with that problem.
You can make an AJAX call for this using something like jQuery and it will pop up the download box while keeping the user on the page. Do something like this:
$.ajax({data: {download: 'query_result.csv'}, type: 'GET', url: 'download.php', cache: false });
I've tried this a few times for a previous employer and it always worked great. Although I did it mostly with .zip and .docx files.
I figured it out!
Basically, my encoding was wrong. I don't want to encode with
encodeURIComponent(JSON.stringify(params));
The result isn't readable by the php script. However, it works to just use $.param().
To summarize, the download is triggered by creating the URL link and then using location.href to link to it. Hence everything else is the same, but instead of the $.get() in step 2, I do:
var url_params = $.param(tmp_params);
location.href = url_params;
Which generates the download. Thanks!
So here is the situation. I'm building a page to host a radio stream hosted on an Icecast server. I got the player working great and cobbled together a PHP script to extract and parse out various data points from the server. Information such as current track, number of listeners, etc.
Here's the problem. It loads fine when the page is first opened, but I can't figure out a way to get these variables to be updated every 5-10 seconds or so and update the page with the new information WITHOUT reloading the page completely (it is a radio station after all, and having to re-buffer the station ever 10 seconds just isn't feasible.
Here's what I have so far, after various attempts have been removed from the code. Any ideas? I've seen it done for one or two variables, but I have almost a Dozen here...
<div id="current_song"></div>
<script language="javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script language="javascript">
{
$.ajax({
type: 'POST',
url: 'script.php',
data: 'getLatestInfo',
dataType: 'json',
cache: false,
success : function(dp){
$.getJSON('script.php', function(dp) {
//'data' will be the json that is returned from the php file
$.("#current_song").html("dp[9]");
});
getlatest();
};
});
}
</script>
and here is the PHP parser
<?php
Function getLatestInfo() {
$SERVER = 'http://chillstep.info:1984';
$STATS_FILE = '/status.xsl?mount=/test.mp3';
$LASTFM_API= '27c480add2ca34385099693a96586bd2';
//create a new curl resource
$ch = curl_init();
//set url
curl_setopt($ch,CURLOPT_URL,$SERVER.$STATS_FILE);
//return as a string
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
//$output = our stauts.xsl file
$output = curl_exec($ch);
//close curl resource to free up system resources
curl_close($ch);
//loop through $ouput and sort into our different arrays
$dp = array();
$search_for = "<td\s[^>]*class=\"streamdata\">(.*)<\/td>";
$search_td = array('<td class="streamdata">','</td>');
if(preg_match_all("/$search_for/siU",$output,$matches)) {
foreach($matches[0] as $match) {
$to_push = str_replace($search_td,'',$match);
$to_push = trim($to_push);
array_push($dp,$to_push);
}
}
$x = explode(" - ",$dp[9]);
echo json_encode($dp);
}
?>
I know it doesn't look pretty yet, but that's what CSS is for right?
Any ideas? Essentially I need the PHP script to rerun, update the variables, and rebuild the text output without touching the audio tag.
Javascript is code that executes client-side (on the website visitors machine) and PHP executes serverside. The way to insert content into a page without reloading the entire page is to use Javascript to inject code into the HTML. Now, for example, say that you have a PHP file on your server, called getLatest.php with a function called getLatestVariables() that finds out the latest values for all your variables and returns an array containing them. What you can do is use javascript to call getLatestVariables() from getLatest.php, and when the function returns the array, it will return it to the javascript. Once the array of variables has been returned to the javascript you can then insert the variabes into HTML divs without having to refresh the entire page.
to call the php function I suggest using jquery to perform an ajax call
also to insert the data returned from the php, jquery is your best bet too.
You need client side JavaScript for this. Get your hands on basic ajax books.
You can request the script for updated data every 5 seconds and update it on the page, this is complicated and needs some knowledge of JavaScript.
The script will have to be new too, or this one edited to trace type of request and return data accordingly.
var url="http://script-address"
var req = new XMLHttpRequest(); // Begin a new request
req.open("GET", url); // An HTTP GET request for the url
req.send(null);
This is how you can check the response
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
//we got a complete valid HTTP response
var response = req.responseText;
//code to handle response
}
php is a serverside language, so re-running the php inside your page will always result in the entire page refreshing, however if you use a javascript ajax call (I suggest using jquery) to a different php file, that php file can be executed serverside without affecting your page. you can then return the newly found variables from this php file to the javascript, and insert them in the callback of the ajax call.
see the answer to this question
If you need any more detail let me know...
$.getJSON('phpFileThatReturnsJSON.php', function(data) {
//'data' will be the json that is returned from the php file
$.("#idOfDivToInsertData").html("an item from the json array ie data['song']");
});
look at JQuery docs for ajax calls, if you've got this far you should be able to nail it out pretty quickly.
Also dont forget to include the jquery library in your html header...
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
Another question by a newbie. I have a php variable that queries the database for a value. It is stored in the variable $publish and its value will change (in the database) when a user clicks on a hyperlink.
if ($publish == '') {
Link to publish.html
} else {
Link to edit.html
}
What is happening in the background is i am querying a database table for some data that i stored in the $publish variable. If the $publish is empty, it will add a link for publish.html in a popup. The popup will process a form and will add the data to the database and which means that the $publish is no more empty. What i would like to achieve is that as soon as the form is processed in the popup and a data has been added to the database, the link should change to edit.html. This can happen when the page will re-query the database but it should happen without page refresh.
How can it be donw using javascript, jquery or ajax?? Please assist.
Javascript by itself cannot be used to deal with database. That is done using php (Or the server side language of your choice). Ajax is used to send a request to your php script using javascript which will in turn communicate with the db. And it doesn't require a page refresh.
So what you are trying to do can be easily achieved using ajax. Since you mentioned jquery, you can check out the $.ajax or $.post methods in jquery which make the process even more simple.
You need to process the form using ajax. The ajax request is sent to a php script which will make the necessary changes in the database and send the new link (link to edit.html) in the response. Upon getting the response, just replace the current anchor element with the new one ..
for eg..
$.post(url, formdataobject , function (resp) {
$("a.youra").text('edit').attr('href', resp);
});
url - where the php script is located
formdataobject - a javascript object that will have the form data as key value pairs
the third parameter is an anonymous function also known as callback function since it will be invoked only when the response is received from the server. This is because ajax requests are asynchronous.
Inside the callback function, jquery is used to change the text inside the anchor element to edit and the href attribute is changed to value that came in the response.
$.post means we are using the post method. so the parameters can be accessed as elements of $_POST array in php.
After updating the db, you can simply echo out the new link and it will be received in the response.
Also, there are other formats in which you can get the response for eg. xml, json.
I'll try to leave the technical jargon aside and give a more generic response since I think you might be confused with client-side and server-side scripting.
Think of javascript as a language that can only instruct your WEB BROWSER how to act. Javascript executes after the server has already finished processing your web page.
PHP on the other hand runs on your web server and has the ability to communicate with your database. If you want to get information from your database using javascript, you'll need to have javascript ask PHP to query the database through an AJAX call to a PHP script.
For example, you could have javascript call a script like:
http://www.myserver.com/ajax_function.php?do=queryTheDatabase
In summary: Javascript can't connect to the database but it can ask PHP to do so. I hope that helps.
Let me try, you want to change the link in a page from a pop-up that handles a form processing. Try to give your link a container:
<div id="publish_link">Publish</div>
As for the form submission use Ajax to submit data to the server to do an update and get a response back to change the link to edit or something:
$.post("submit.php", { some_field: "some_value"}, function(response) {
if(response.isPublished)
$('#publish_link', window.opener.document).html('Edit');
});
Basically your publish link is contained in a div with an ID publish_link so you change its content later after data processing without reloading the page. In the pop-up where you would do the form processing it is done using jQuery Ajax POST method to submit the data. Your script then accepts that data, update the database and if successful returns a response. jQuery POST function receives that response and there's a check there if isPublished is true, get the pop-up's opener window (your main window) and update the link to Edit. Just an idea, may not be the best out there.
It cannot be made with javascript, jquery or ajax. only server side script can query a database. with ajax request you can get the script output. ajax requests can be sent either with pure javascript or jquery.
Well, i think i understand your quaestion, but you have to get a starting point, try to understand this:
try to understand what are client variables and server variables.
javascript does not comunicate with database.
you can use javascript to retrieve data to a specific "Object variable".
Using ajax methods of jquery you can post that data do other page, that will execute the
proper actions
you can ;)
at first you must create php file to query database and return something like true or flase and then with file url check the function and get answer
function find_published(folder_id) {
var aj_url = "{{server_path}}/ajax/url"
var list;
$.getJSON(aj_url+"?callback=?&",
function(data) {
//here is your data... true false ... do every thing you want
}
);
};
this app for node.js does mysql queries https://github.com/felixge/node-mysql
You need to use AJAX for this, like .post() or .get() or JSON.