Running a php script asynchronously - javascript

I have a web page with a button, when a user taps the button there is a long php script that runs (say to look at past tokens bought by the user) and sends the user an email at the end of script.
I have abstracted my code for sharing purpose (replacing the script with just a sleep function).
webpage.php
<div class="card">
<input type="submit" class="button" name="update" value="Update" />
</div>
<script type = "text/javascript" src="jquery_functions.js"></script>
jquery_functions.js
$(document).ready(function(){
$('input[name="update"]').click(function() {
$.post(
"script.php",
{update:"fav_tokens"},
function($data) {
alert ($data.message);
},
"json"
);
});
});
script.php
<?php
sleep(60);
?>
The problem is that as soon as the user presses on the button, he is "locked in" on the page and cannot navigate away from it... which kind of defeats the purpose of doing the jQuery AJAX thing.
I have tried putting the script in another file (script2.php) and then call it using exec("php -f script2.php"); in script.php but that also stop the user from navigating away from the page.
What can I do to make this work?

The likely issue is that script.php is opening a session and whichever page you are trying to visit is also trying to open a session but has to wait until script.php is all set with it.
Somewhere in script.php you will need to add:
ignore_user_abort(1); // Let the script run even if user leaves the page
set_time_limit(0); // Let script run forever
session_write_close(); // Close the session. This will allow for other pages to open it
// You will still be able to read your session data but can no longer write to it unless it is re-opened
sleep(60);

Related

How to make a custom Back button for jQuery load() content

In one of my php page (Report.php), I am loading its content through jQuery load(). I want to create a "back button" on my php page so that my user can click it to go back pages. Note- I am not looking for browser back button.
Here is my php pages -
report_template.php
//This page query my database and creates a content table<br>
//Table content
Another Report Link
report.php
<button>Go Back</button> //This button will take user to back (equivalent to window.history.back() )
<div id="rept"> </div>
<script>
jQuery('#rept').load('report_template?id=1');
function fetchReport(id){
jQuery('#rept').load('report_template?id='+id);
}
</script>
I am average level skill in jquery/javascript.
At the top of every page start session session_start(); and set the current page as a $_SESSION variable. IE
<?php
session_start();
$_SESSION['last_page'] = $_SERVER['PHP_SELF']; // Or whatever you designate it as
Then you can call it in report.php
<?php
session_start();
<button onClick="window.open(<?= $_SESSION['last_page'] ?>);">Go Back</button> //This button will take user to back (last report page he's seen)
<div id="rept"> </div>
<script>
jQuery('#rept').load('report_template?id=1');
function fetchReport(id){
jQuery('#rept').load('report_template?id='+id);
}
</script>
A slightly simpler, yet less reliable way to do it, is to grab the last page the person was on according to PHP $_SERVER['HTTP_REFERER'] This can also include "off server" pages. Also it may better suit your question if the referrer may, in fact, come from "somewhere else" IE:
<button onClick="window.open(<?= $_SERVER['HTTP_REFERER'] ?>);">Go Back</button>

Trouble with continous refreshing page

When I try to run this script:
<form class="form-inline" action="<?php $_SERVER['PHP_SELF']; ?>" method="POST">
<button type="submit" name="buttonSubmit" class="btn btn-default">Submit</button>
</form>
<?php
if (isset($_POST['buttonSubmit'])) {
unset($_POST['buttonSubmit']);
echo "<script>alert(".isset($_POST['buttonSubmit']).")</script>";
echo "<script>location.reload(true);</script>";
}
?>
As a result, the page is refreshing in an infinite loop.
What is the reason?
How do I refresh my website only once?
When you use location.reload(true);, you do the same, programmatically, as clicking on the browsers "Refresh/Reload" button.
This will generate yet another "submit", over and over, hence always make the statement isset($_POST['buttonSubmit']) be true.
Here are a couple solutions:
location.href = 'page-to-load';
location.assign('page-to-load');
location.replace('page-to-load');
The Location.replace() method replaces the current resource, and after that the current page will not be saved in
session History, meaning the user won't be able to use the back button either,
to navigate to it and cause a repeated "submit", which normally will occur.
Note, if the 'page-to-load' is the same being already loaded, you can use location.href, e.g.
location.replace(location.href);
Yet another way would be, instead of rely on a client side script, to do a response redirect upon a form submittion, server side.
How to make a redirect in PHP?
This helped me:
Change location.reload(true); to window.location.href = '';

global variable not displayed in div

I declare a variable at the beginning of my .js file:
var option="blabla";
On page 1.html I click on a link to page 2.html where I have
<script>document.write(option);</script>
No text is displayed on 2.html. When I refresh the browser while I am on 2.html I get undefined as an output.
What do I have to do to have the text displayed straight after I click the link?
Alternatively, how can I get the following code work to output strUrl on 2.html:
on 1.html I have a link:
<a href="2.html" onclick="function1("item")">
on 2.html I have a div:
<div id="display">document.write(strUrl);</div>
then I have in my .js file:
function1(searchitem)
{
strUrl = 'http://blabla.com/'
+ '?key=' + searchitem;
}
You try to create a Javascript variable on a page and then use it on another page. This is a more-or-less broad problem, since you want to maintain values across pages. First of all, you need to decide where is this value going to be defined and where is it going to be used. If this is more like a server-side variable, then you need to define it on server-side and then generate it into your Javascript code. If you are using PHP, then you can do it like this:
<script type="text/javascript>
var foo = '<?php echo $bar; ?>';
</script>
Naturally, you need to initialize $bar to be able to do that. If the variable should be a client-side variable, then you need to use localStorage, like this on 1.html:
localStorage.setItem("option", "blablabla");
and then load it on 2.html:
localStorage.getItem("option");
Or, if you need to use it both on server-side and client-side, then you can use a cookie for this purpose. Using cookies i slightly more complex, but my answer to another question should get you going.
Let's focus on the cause this did not work for you. A Javascript variable will cease to exist when the page is unloaded, so you will not be able to use its value after that. So, you need to persist it somehow, storing it either on the server or the computer where the browser is being run.
As a side-note, I should mention that you can use Javascript variables accross pages if you load some pages inside iframes of a page, but that is a different scenario.
This is what FORMS and AJAX were invented for. If your server has a PHP processor (virtually ALL of them do), then you can rename your .html files to .php and use a bit of PHP to accomplish your goal.
A web page ending with .PHP works exactly the same as one ending in .html, except that you can now add snippets of PHP code where desired. It is not necessary to have any PHP code, but if you have some it can do stuff.
Method One: FORMs
If you want to switch to page2.html and see a value sent from page1.html, you can use a FORM construct and post the data from page1 to page2:
page1.php
<form action="2.html" method="post">
<input name="option" type="text" />
<input type="submit" name="sub" value="Go" />
</form>
page2.php
<?php
$p1 = $_POST['option'];
?>
<div>On page1 of this website, you typed: <?php echo $p1; ?>. That's what you did.</div>
Note how a <form> uses the name= attribute for the name of the variable that is sent to the other side.
Example Two: The AJAX method
HTML:
<div id=nonForm">
<input id="option" type="text" />
<input type="button" id="myButt" value="Go" />
</div>
<div id="results"></div>
jQuery:
$('#myButt').click(function(){
var opt = $('#option').val();
$.ajax({
type: 'post',
url: 'page2.php',
data: 'option='+opt,
success: function(john){
if (d.length) alert(john); //display result from Page2 in a pop-up box
$('#results').html(john); //Or, display it right on the page
}
});
});
PAGE2.PHP -- The AJAX processor file
<?php
$opt = $_POST['option'];
//Now, you can do something with the data in $opt, and then send back a result
$rtn = 'Hey, you sent: ' .$opt;
echo $rtn;
The primary (and most important) difference between the two methods is that the FORM will change pages on you. The user will be sent from Page1 to Page2, and the screen will flash as this happens.
What's exciting about AJAX is it sends data to Page2, where Page2 can do something with it (for example, a database lookup), and then Page2 sends different data back to Page1. This new data can then be displayed on the page WITHOUT the page refreshing.
Here are a couple of very basic AJAX examples, to get you going:
AJAX request callback using jQuery

Javascript is loading rest of the script also

i am using to confirm deletion of a content.
i have used js to confirm user to delete the content.. but if user cancels the confirm dialogue, it should redirect.. but instead the page is loading the whole script and then redirecting!
the script goes here...
if (confirm("Are you sure you want to delete??"))
alert("deletion successful");
else
history.go(-1);
alert("unwanted alert");
this unwanted alert is also displayed when i am clicking on cancel in confirm dialogue box..
Edit..
actually the whole code goes like this.. maybe this will give a clear view of what my problem is
<html>
<script>
if (!confirm("Are you sure you want to delete??"))
history.go(-1);
</script>
<?php
require_once "config.php";
$query= 'DELETE FROM `sess` WHERE `sid` ='.$_GET['bid'];
if ($conn->query($query) === TRUE) {?>
<script>
alert("deletion successful");
window.location.replace("../index.php");
</script>
<?php
} else {?>
<script>
alert("unable to delete!");
window.location.replace("../index.php");
</script>
<?php }?>
</html>
Your edit reveals the problem.
Your PHP code runs on the server and before the page is delivered to the browser. So even though you output JavaScript code asking the user whether they want to confirm, that doesn't do anything until the page is sent to the browser. Your server-side code continues to run, executing the SQL statement.
So basically, breaking it into server and client parts, here's how your code runs:
First, this server-side code runs:
require_once "config.php";
$query= 'DELETE FROM `sess` WHERE `sid` ='.$_GET['bid'];
if ($conn->query($query) === TRUE) {
/*...write some output to the response...*/
} else {
/*...write some other output to the response...*/
}
Then, when the response is sent to the client, it looks like this (assuming the query call returned TRUE):
<html>
<script>
if (!confirm("Are you sure you want to delete??"))
history.go(-1);
</script>
<script>
alert("deletion successful");
window.location.replace("../index.php");
</script>
</html>
At this point, the deletion has already happened. The browser receives this response and shows the confirm and the alert and does the update to the location, but again, that has no effect on what happened on the server earlier.
You'll need to have the confirmation happen earlier, on whatever page is calling this page, so it happens before the server-side code is run.
I recommend stepping back from your current task and working through some good PHP and web tutorials, so you can better understand where and when things happen.

PHP mail function gets triggered every time i load the page

I am trying to send mails using PHP's mail() function.
I have a button (Send Mail), clicking on which the mail has to be triggered. Since PHP is a server side scripting language, I used Javascript to trigger the PHP function. A very unusual event occurs. Whenever I load the page, the mail gets triggered. So, I put alerts and echos to check if the code logic is correct.
Funny thing is that the mail does not get triggered when I click the button. Where am I going wrong?
Please see my code:
<input type="button" onclick="jMail()" value="Send Mail"/>
<script>
function jMail()
{
alert("Inside Javascript Function");
alert("<?php PHPFunction(); ?>");
}
</script>
<?php
function PHPFunction(){
echo("Inside PHP Function");
mail("to#example.com", "Help Mee", "Definitely Help me", "From:from#example.com");
echo("Mail Sent");
}
?>
PHP is a server side language, while Javascript is a client side language. I think you are confusing the two, and trying to mix their use in a way that would never work.
When the page is loaded, these steps occur in sequence:
The server interprets the PHP code in your page, and renders a page that does not contain any PHP code.
The client, viewing the page, does not obviously have access to any PHP function, because it sees only the result of the elaboration. It still can use Javascript to achieve dinamic behavior of the page (i.e. changes without refreshing), and things like AJAX to make requests to the server still without re-rendering the page.
<input type="button" onclick="jMail()" value="Send Mail"/>
The event onclick is indeed triggered when you press the button, but after the page has been fully loaded. At this time, all the PHP code has been already interpreted by the server, and there is no chance to execute it again without reloading the page.
EXAMPLE: here you can see the result of the elaboration of your code (under stdout). As you can see, the client is left with a PHP-free web page.
If you're looking for a way to trigger PHP code when an event occurs after the page has been loaded, I suggest you take a look at this question.
Also, this question on programmers.stackexcange.com could help you clarify the difference between client side and server side if it isn't clear.
You cannot trigger PHP from javascript that way. Create another PHP file, and call it using AJAX javascript requests.
<form method="post">
<input type="submit" value="Send Mail" />
</form>
<?php
if(isset($_POST)){
///do sent mail here
mail("to#example.com","Help Mee","Definitely Help me","From:from#example.com");
}
?>
PHP is a server side scripting language which has already been interpreted by the server and then sent to client(i.e browser) for interpretation of any client side script( ex JavaScript).
But if want a responsive webpage to be handled by your server try to use Form and inputs tags and their attributes to send your request back to server
But if you want a Quick way Try using AJAX.
every time you do
<?php PHPFunction();
you send the mail..
maybe you could play with something like
<?php
if(array_key_exists('postMail',$_POST)){
echo ("Inside PHP Function");
//if(empty($_POST['mailContent'])){/*angry blablabla*/}
mail("to#example.com","Help Mee",$_POST['mailContent'],"From:from#example.com");
echo ("Mail Sent");
die();
}?>
<input type="button" onclick="jMail()" value="Send Mail"/>
<script>
function jMail()
{
alert("Inside Javascript Function");
var xhr=new XMLHttpRequest();
xhr.open("POST","?");
var fd=new FormData();
fd.append("postMail","true");
fd.append("mailContent","fooooobar");
xhr.send(fd);
}
</script>

Categories

Resources