I'm using a flash webcam to take a picture. It works great and spits back a URL via POST.
I'm coding in PHP and would like to display this POST data once it is recieved, the problem is that I dont re-load the page.
I've looked around and I'm not sure to dynamically load this array of data.
Where should I be looking? jQuery?
Ah, Figured it out. The Flash thing I have has a built in callback function, so I just have to append the data from there!
jQuery is not able to read any sort of request data other than that which appears in the URL (GET). You will need to use PHP (or some other server-side language) to handle the response created by the FLash application.
Due to the fact that you're using Flash for the process you are at somewhat of a disadvantage because unless the Flash application has some sort of JavaScript "PhotoUploaded" event notification, your page won't be notified that Flash has just submitted a picture to your server which needs to be retrieved and inserted. If you can modify the Flash application to make an external JavaScript event then you can proceed as Frankie has described in his answer; otherwise, if modifying the Flash application is not an option, then another solution would be to have your page send a request to the server every so often (5-10 seconds or so maybe), to check if there is a photo for it to display yet.
The simplest way to setup polling with your server in this fashion would be to make sure that each photo upload from Flash has a unique, pre-determined identifier that your page knows at initial load. You would then simply ping your server every few seconds with an AJAX request and pass it that unique identifier in order to find the right image should one exist.
Basic example:
function GetPhoto() {
$.get('/getphoto.php?ID=1541XJ55A6', function(response) {
if(response.ImageUrl !== "") {
$(".profile-image").attr("src", response.ImageUrl);
if(getPhotoTimer !== undefined) {
clearInterval(getPhotoTimer);
}
}
});
}
$(document).ready(function() {
var getPhotoTimer = setInterval("GetPhoto()", 10000); // every 10 seconds
});
Flash calls javascript each time it spits back the URL.
Javascript contacts server (php) and gets content
Javascript injects content onto page
Like this (flex code):
// attach a function to the completeHandler
private function completeHandler(evt:Event):void {
javascriptComplete();
}
// declare the function that will call the javascript function
private function javascriptComplete():void {
var javascriptFunction:String = "galeryUploadComplete("+Application.application.parameters.opt+")";
ExternalInterface.call(javascriptFunction);
}
Related
I am building a dictionary and I have my words and definitions stored in a MySQL database.
I want to make some words clickable (maybe as spans or buttons) so when I click them a new query that has this word as key starts (so how can I send the content of this clicked word into to _post in my details.php file)? Or how can I turn the content of the span into a php variable?
<html>
Click this <button>word</button>
</html>
<?php
echo "You clicked that " $word;
?>
MySQL communicates with your server-side code (PHP).
Your PHP code reads/writes data into MySQL, generates (or loads) HTML templates that are sent to the browser when requested.
Your browser requests a page via URL when someone visits your site, sending a request to your URL and getting some response, presumably HTML in return.
From the moment when the page is received, CSS rules are being applied with design purpose and programmatic code (Javascript) is being executed.
Now, your span is part of your HTML, which was either received from the server, or generated by your client-side code (Javascript).
It is important to note that in production mode the browser and the PHP code are running on different, remote computers and sometimes the MySQL RDBMS is also running on a separate computer, a database server.
So, the thing you want to do is to have a Javascript event that sends some content to your server, which processes it and then stores it into your MySQL database.
Event creation via Javascript
Read this article: https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events
Basically you will need to create an event, which will either be an
onclick="yourJavascript()"
or a call to addEventListener. Try to implement a trivial example for that, like below:
document.getElementById("mybutton").addEventListener('click', function() {
alert("Yay! The click was handled!");
});
<input type="button" value="click me" id="mybutton">
Later on you will need to replace the function body with a request sending.
Send an AJAX post request and receive a callback
Read this article: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
Read this article as well: https://javascript.info/xmlhttprequest
Example:
let xhr = new XMLHttpRequest();
xhr.open("POST", URL, somedata);
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == 3) {
// loading
}
if (xhr.readyState == 4) {
// request finished
}
};
It is worth converting something similar to a parameterizable function so in the future you would be able to reuse most of the benefits of your current work. And call this function I just suggested in your event listener.
Explanation:
XMLHttpRequest is the type you instantiate in order to send an AJAX request
xhr is the resulting object of the instantiation
xhr.open is a function that you need to call, passing the request method (which is "POST" in this case, the URL, which is the target and some data)
somedata is a variable the code above assumes that was already defined, but you will need to properly initialize it yourself
send is sending the request, in our case asynchronously, that is, the request will not end yet when the next line is processed
xhr.onreadystatechange is a callback which is executed when the ready state changes; state 3 is loading, state 4 is request finished, so your meaningful code should be inside the if that checks for the state being 4
Handle POST requests with PHP
Read this article: https://www.codegrepper.com/code-examples/php/php+handle+post+request
Basically you will have your data in $_POST, you can process whatever logic you want and you can generate an HTML/JSON/whatever response the way you like.
PHP - MySQL
You can generate MySQL queries with PHP and you can use PDO, for example, to generate parameterized queries and sanitize your dynamic parameters, especially those defined by the users, to avoid SQL injection.
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 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; ?>';
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.
I have an application that rates a large set of items and outputs a score for each one.
In my php script I'm using ob_start and ob_flush to handle the output of data for each rating. This works great if I directly load the script. But when I try to use .get via jquery, the entire content loads and then is placed into a container, instead of incrementally adding.
I'm wondering the following
Is there a way to initiate data placement before the get has completed?
Do I need to continually poll the script until the process is complete?
Is there a more efficient way to display the data instead of get?
For this kind of problems, I will have this approach:
Keep the old script that using ob_start() and ob_flush() for a user that disable javascript in their browser.
For a user that have javascript enable, load the predefined number content one at a time. To differentiate between js enable user and not, I'm thinking of 2 page. In first page you display a link to old script. Then put a jquery code in this page to intercept click on the link to old script, so click on that link will display (or create) a div, then load the content into that div.
You can use a setTimeout to call AJAX code continuously, then after a certain condition reached (Ex, empty response), you can remove the setTimeout using clearTimeout. Each AJAX request will need to have an offset param, so it will fetch content from last AJAX call. After receive response, increment the offset for the next AJAX call. You can use global variable for this.
You can use a simple global variable to prevent an AJAX request run while the last AJAX still waiting response, to prevent race condition. Example code:
//lock variable
var is_running = FALSE;
//offset start with 0
var offset = 0;
function load_content($) {
//check lock
if (! is_running) {
//lock
is_running = true;
//do AJAX
$.get(URL,
{ PARAM },
function(resp){
//put data to 'div'
//...
//if empty, then call clearTimeout
//...
//increase offset here
offset = offset + NUM_ITEM_FETCHED
//release lock
is_running = false;
});
}
}
The point you must pay attention that using AJAX call, you must determine the response manually, since ob_start and ob_flush will have no effect in this scenario.
I hope this will help you create your own code.
Jquery will receive a success status from the ajax call when the complete page has finished loading .. so whatever you do in the php will not get returned to the calling page until the whole process has finished .. (ajax is a one-send/one-receive system)
You would need to complicate your system to do what you want..
example..
your php updates an external file of progress, and your jquery polls this file in some interval and displays progress..
You would initiate the interval polling on ajax submit, and on ajax success terminate it..
I had a similar problem awhile back where I wanted a php script to send a series of emails and update the jquery page to say something like "Sending 23/50".
What I ended up doing was setting up the php script to handle one item at a time. This might also work in your case. Could you have jquery pass an item identifier of some sort to a php script that handles just that one item? Then in the callback, you could place the data for that item in the page as well as creating a new ajax request for the next item. In other words, each callback would create a new request for the next item until the entire list of items has been looped through.
What do you think?
-DLH