Run PHP function when img clicked - javascript

I'm wondering if there's a way to perform a function when an image is clicked in PHP? I know it can be done in Javascript. For example, when foo.png is clicked, the following function will run.
function example() {
header('Location: example.php');
}

PHP is run on the server, and is used before and while creating the page -- and then it is submitted to the browser for rendering.
Once the page is rendered and displayed to the user, all PHP processing has stopped and the page has been served to the client. Server code no longer runs - its time has passed.
Once in the browser, only client-side code can run (javascript). Particularly when interacting with the user, client side code is all you can use.
However, you can also use client-side code (javascript/jQuery) to interact with the user (detect a click or mouse movement) and then use AJAX to send data over to another server-side PHP file. The PHP file will "wake-up" as it receives the data, and it can do some additional server-side stuff -- such as use the received data to perform a DB look-up, then take the new DB data and create some HTML code and send that back to the page. This new HTML code can be injected onto the page in the success (or .done() ) function of the AJAX code block and new data can appear on the page without refreshing or navigating away from the current page.
But for actually detecting the user click, it's javascript/jQuery.
Note that PHP can also inject javascript along with the HTML - but once the code has been served to the browser for display, it is only the javascript that can interact with the user, not the PHP.
With javascript/jQuery, you can do what you want like this (the code is correct but the example will not work properly - SO will not navigate to the Google webpage):
$('#myImg').click(function(){
window.location.href = 'http://google.com';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Click below for Google</p>
<img id="myImg" src="http://placeimg.com/50/50/animals" />

Related

Basic PHP - HTML flow - high level understanding

Can someone confirm that the is the basic flow for PHP - HTML.
PHP runs on the server, and pre-processes the page so it can be sent to the browser.
In the browser you can run things like javascript.
So in order to pass things to PHP (from Javascript):
you need to "fetch" the php page (with post or get args)
This re-runs the php page (on the server) allowing you to process those args, generating a new "page" to send to the browser.
PHP variables aren't "sent" to the browser, but processed and inserted in the a new page that's sent out when the page is fetched.
Am I even close ?

Is it possible to make a HTTP POST to a standard ASP.Net Web Form using XMLHttpRequest/FormData?

Let's suppose we have an ASP.Net Web Form, Page.aspx, in which we do the following:
<script>
$(document).ready(function () {
// grab the standard ASP.Net form
var form = document.forms['ctl01'];
form.addEventListener("submit", function (event) {
event.preventDefault();
sendData(form);
});
});
function sendData(form) {
const xhr = new XMLHttpRequest();
const fd = new FormData(form);
xhr.addEventListener("load", function (event) {
document.open();
document.write(event.target.response);
document.close();
});
xhr.addEventListener("error", function (event) {
alert('Error!');
});
xhr.open("POST", "Page.aspx");
xhr.send(fd);
}
</script>
The reason for this setup is I want to take advantage of the XMLHttpRequest progress event to erm, show some progress indication because the postback may include files that take some time to upload.
The load event handler works great. As a result of the POST I get the contents of Page.aspx again and replace my current document. So it seems that some kind of POST actually does happen BUT, there is one problem. In Page.Load(), the Request.Form and Request.Files collections are empty so I can't process the form/files.
I tried adding the following header but without much luck:
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
Do you think it is possible to make a successful POST (with page receiving data) using XMLHttpRequest/FormData, or is there some fundamental limitation that prevents this from happening for ASP.Net pages?
Thanks!
Well any ajax call simply can run some code behind, but since the web page IS STILL sitting on the client side in the browser, then things like controls and the page state are NOT available.
So you don’t want a post back, but now you asking for a post back? (I am confused). I mean, either you post back the whole page (standard event post back). Or you drop the controls and things in question into a update panel, and then ONLY that part of the page is posted back. I fail to see any advantage of trying to send “more” of the page in a ajax call when the WHOLE idea is to NOT send the page in the first place, right?
I mean, if you need some extra values in the ajax call, then you have to get/grab those bits and parts from the page, and include that information in your ajax call. (perhaps as a json string).
Without a post back, then viewstate and all of the controls are STILL just sitting on the users desktop in the browser. The code behind, and even the page class object + code ARE OUT OF scope at this point in time. Only upon a post-back does the WHOLE page travel up to server - code behind runs - you have use of full controls on the page, and THEN the whole page travels back down to the client side (and this quite much means that JavaScript code will have to re-start!!!
However, if you need a few parts and values in a page and don't want a full post-back? Then simply put those parts into a update panel. you can then in JavaScript for example do this:
varMyAspNetButton = docuement.GetElementById("Button1");
varMyAspNetButton.Click();
The above will save you world poverty and not have to wire up a bunch of js and web methods since the js code simply CLICKS on your button (that is inside the update panel). In this case, of course a whole page post back does NOT occur, but the page load and events do in fact fire - these so called "partial" page post backs means that the code behind is LIMITED to the information (controls) inside of that up-date panel.
However, as noted, if you do a post back, then the browser page NOW travels up to the server - and that quite much means any js code client side is toast and now can't run, since a whole NEW fresh copy of the web page is about to travel down to the client side again - and that re-starts your js code.
As noted, you can do a partial page post back with a update panel. And in js you can fire a "click" or in fact MOST events of asp.net controls on that page with js.
But, then again?
You don't want a full page post back, and you likely don't want all of the controls and the whole page to travel up to the server. But then again you wondering why you can't use or access controls on the page with ajax calls? Well as noted, the server side code behind is OUT of scope and OUT of context when you make ajax calls. The web page does NOT exist server side. We don't know if the user turned off their computer, or will never do anything in that client side browser and web page. The server at that point in time has lost ALL KNOWLEGE of that web page. So any ajax call does not have use of the controls on the page, and does not even have use of viewstate either.
This tends to mean that say when using say a ajax system to up-load files? Well, you can't store the status in the web page server side - since the page DOES NOT really exist at that point in time. So you can call some web methods, and about the ONLY way to keep some values in context is to use session(), since that does not need the web page, or the view state to function and work.
The major down side of session() of course is that if some user has two tabs open or even two different browsers open? Well, session() is SHARED between those pages - so while session() is great, it also shared between ALL copies of web pages for that given user - and thus you need to add code to separate out each session "set" of values, or simply hope that the user will not have two pages in operation for such file up-loads.
But to answer your question?
You can do and achieve partial page pushbacks by using a up-date panela And thus you can have timer code or js code client side to continue to run since a full page life-cycle does NOT occur. In other words, you control what part of the web page will and is sent up to the server side by using a update panel.
If you don't use a up-date panel, then any ajax calls you make WILL have to pass the data from the browser side, since it STILL just sitting on the users desktop, and any code behind can't grab, nor reach out, or see or even KNOW that the web page exists client side.
So you either pass extra values from the web page with your ajax calls OR YOU can use a update panel, drop controls inside and then the partial page post back will ONLY send up and have use of what you want inside of that panel. So you have two really great choices.
And in either case (a full page post back) or a partial one?
Grab a reference to the client side asp.net button, and fire off a .click event. You can I suppose wire up all kinds of _doPostBack in js, but with update panels and the click() trick, then you have a choice of how much of the page gets sent up, and it all quite much automatic wired up for you and saves a TRUCKLOAD of work that you would have to manually write and wire up if you don't use a update panel to control this.
So you get that "partial" page post back, and in that case the code and events inside of that up-date panel can update/see/use/modify controls in that up-date panel, but anything outside of that up-date panel will NOT have traveled up to the server.
And if you don't use a update-panel, then any ajax call is just that - a direct call to the server side - but the web page STAYS client side - thus on-load and any of the controls or objects or in fact the WHOLE class form object that represents that web page IS STILL SITTING client side - thus as noted, no on-load, no code behind can touch or even see or know about the values of controls on that page, and as noted there is also no ViewState either.
The WHOLE idea of ajax calls is that you did not want and never did want the page to travel up to the server, and then be re-rendered, and then re-sent back down to the client side. But you need to be 100% crystal clear here:
Without a page post back (or partial one with update panels), then the web page does NOT exist any more server side. Web pages are state-less and once the round trip has occurred (web page up to server - code behind runs, page sent back to client), then as far as the server is concerned (and you the developer) that web page is GONE and DOES NOT exist anymore at all - it is out of scope and from your point of view (and the server point of view) that web page does NOT exist anymore the instant it been sent back down to the client side. As noted, the only exception that is practical here is session() values - since they are not part of any given web page.
So, you have to decide if you want a partial page post back to get at and modify some values with server side code.
Or you pass the values with your ajax calls and the returned values can then update the browser controls. And of course once you do eventually do that say full page post back, then the code behind can certainly see + use any controls that the client js code changed - but can only do so with that full page post back, or as noted, controls limited to a update panel if we are talking about a partial page post back (update panel).
You either have to include additional data in your ajax calls, or consider using a partial page post back to send up part of the web page if you need to modify that part of the page with code behind. Or as noted, return information with your ajax call, and then update the client side. There not really a in-between choice here.

Re-run PHP rss feed

I couldn't really find anything online for what I was looking for.
Currently, I have some php code that grabs news feeds and every time the loop runs through, it stores it in an array slot {0,1,2} etc. The interesting part is, I don't know how to refresh the php rss grab function without refreshing the page.
Essentially I have index.php, and with code inside, and I'd like to re-run the php script in those arrows <> through javascript.
I know in javascript you can assign script names and call them in html, that's essential what I want to do but for php, is it possible?
Currently your RSS fetching logic is intertwined with your presentation logic. You need to separate them so the RSS logic can be called independently.
Consider a structure like this:
rss.php - script with logic to fetch RSS feed and package it up as PHP array
index.php - require(s) rss.php and wraps the results in HTML
api.php - another script which require(s) rss.php, but responds with JSON data that can be consumed by Javascript
Now you can present the RSS data when the page loads and then periodically call api.php via Javascript to update the results.
You could also forgo calling rss.php from index.php, merely have it present an HTML skeleton with the javascript and when the page loads, have the javascript call api.php right away to build the initial list. That way you don't have the presentation logic in two places.
PHP is a server-side language, meaning your script will be run by the server before it is returned to your client (the browser).
What you can do if you want to continuously get new data from your script is call your server periodically with JavaScript using an AJAX call and display that to your user.
See this and this.

Web: How do we display content on the Client after making a slow Server Side Call?

I am working on a Web Application for which I am currently doing something like this:
Page1.php posts to Page2.php.
Page2.php contains an HTML file with 2 Javascript files. The first Javascript file uses an AJAX call to trigger Page3.php. The second Javascript file listens to Result.json for results.
Page3.php invokes a Python Script, Task.py.
Task.py takes about 15 minutes to run, writes results to Result.json which I need to display on Page2.php.
The problem here is 1st that the since Task.py is such an expensive call, I end up on Page2.php on Chrome and Chrome pops open the window asking me if I would like to kill or wait for the page to load and the Web Page eventually becomes unresponsive (Times Out).
As a result, I become unable to display the results stored in Result.json on the page.
Another problem that I am having is that the Task.py file that I am executing appears to be a blocking call, so when my first Javascript makes the AJAX call, it prevents my 2nd Javascript from listening to Result.json for results (When Javascript makes an AJAX call, it waits there until it gets the response back). So even if there was content already in the Json file, it wouldn't pick up on it until the 1st AJAX call returns.
The Listening Javascript file looks something like this:
while(true){
result = setTimeout(myFunction, 60000);
if(result === true){
console.log("Quitting the loop");
break;
}
}
where myFunction parses the Json file and manipulates the DOM to display the content.
Any Advice?
You can use Server Push/Websocket for it. If your server is ready to serve the data, it can notify the client side to get the data. Just search for socket.io / nodejs.
first Ajax call starts page3 and set event listener to server push message. If it receives the message, simply get content of Result.json.

Javascript function execution on link click?

I have a link, that when a user clicks on it, it loads a different page as normal but also executes a JS function that autofills a specific text-box on that different page. Is it better practice to use Jquery or Javascript to do this? How can I do this using either one of them?
You can't do this from the source page.
It's a security feature. Imagine if you wrote a JS function that went to an online banking page and auto-filled a bank transfer using the user's current cookie. That's why you can't.
If you control the other page then the sequence you can use is:
Save data to the server;
Go to the new page with a JS redirect;
The new page is loaded from the server;
While loading th epage the data that was saved from the server is retrieved and used to populate the text box.
So it can be done from the server but only if you save it there. The only way of doing that is using Ajax.
An alternative approach is:
Instead of a JS redirect, submit the page back to the server;
The server saves whatever data it needs to;
The server sends back an HTTP redirect to the new page;
The new page uses the saved data to construct the new page with the populated text box.
At the end of the script add return false;. This will make the page run the script without redirecting the page.
Edit: (after saw your edition).
Is it better practice to use Jquery or Javascript to do this? How can I do this using either one of them?
jQuery is a javascript library, this it doesn't matter if you use plain javascript or use jquery as long as you happy with the result.
And about what you say that you successfully manipulated a page fro the redirecter page... I don't see how it possible.

Categories

Resources