There is a submit button that serializes some forms and submits them correspondingly to different handlers on the server. When the data have been sent, I would like to redirect to another page where the user can see an overview of the results. How can I do it so? Redirecting right away does not work since the page does not have enough time to submit the data (or it looks so).
The following fails:
$(document).ready(function(){
$('#submit_all_button').submit(function(){
var querystring = $('#q1').serialize();
$.get('/change_q1', querystring);
var querystring = $('#q2').serialize();
$.get('/change_q2', querystring);
var querystring = $('#q3').serialize();
$.get('/change_q3', querystring);
window.location.href = "/main";
return false;
});
});
The same problem arises when the submit action is to redirect to /main page.
Use the success function of jQuery get() and keep track whether all your updates are send. So the last success function call finally redirects your page.
I have an other answer in PHP which is interesting: run it as a background job (Other answer is the best way to go but if, for some reason, you can't use it):
set_time_limit(900);
ignore_user_abort(true);
header("Connection: close");
header("Content-Length: " . mb_strlen('ok'));
echo 'ok';
flush();
// Your code follows here
Maybe you can use this logic in your server-side language.
Related
When registration form submits using POST method and when you refresh the same page then it will prompt for resubmit or resend information. How we can prevent this?
Use post-redirect-get. In short:
You can use ajax. You keep the same php code that you put in another file, and you post the data via ajax.
You can use include a one-time random token in the form. The first time that token is submitted (with other data), an action is taken. Future submissions of the same token have no effect (or just show the same confirmation page), and submissions with blank or invalid tokens are rejected.
This also protects against cross-site request forgery.
Try this:
<?php
if (!empty($_POST)){
?>
<script type="text/javascript">
window.location = window.location.href;
</script>
<?php } ?>
I placed it into prevent_resend.php and then included it after the postdata processing was done.
// ... save data from $_POST to DB
include('prevent_resend.php');
// ... do some other stuff
Before i go on, I'm aware that this question has been asked a couple of times but it doesn't deal with specificity.
I have a functions.php script which contains a couple of functions and i would like to call a specific function when the user clicks on an anchor tag.
I have gone through most of the questions in this manner and i understand that this would be done through javascript and ajax load the page specified with the on-click attribute.
My question is when this happens(page is being loaded) how do I call a specific function out of the functions.php script and if I have required it on the current page where the anchor tag exists will it cause complications?
To be more precise i have a register.php page which does the following; take user data then validate, if validated insert into DB and send a mail to the user to verify his account then redirect to a registration_complete.php page which has the option of resending the link if user didn't receive it. Hence clicking the link will run a specific mail function in the functions.php file.
The Code is written below
register.php
<?php
session_start();
$_SESSION['name'] = hmtspecialchars($_POST['name']);
//validation code goes here
if (isset ($_POST)){ //check that fields are not empty etc...
// insert into db code...
// email the user code...
// redirect to registration_complete.php code..
}
?>
<form method='post' action="">
<input type="text" name="name" id="name">
<input type="text" name="email" id="email">
<input type= "submit" value="submit">
</form>
registration_complete.php
<?php
require'functions.php'
session_start();
$Name = $_SESSION['name']
$RegisterationComplete = "Thank you . ' ' . ' $Name' . ' ' . for registering pls click on the link in the email sent to the email address you provided to verify you account. If you didn't recieve the email click on the resend email link below to get on resent to you. Please make sure to check your spam folder if you did not see it in your inbox folder."
?>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
$.get("somepage.php");
return false;
}
</script>
Resend Verification Link
Please not that i have copied the js code from one of the answers related to my question
functions.php
<?php
//connect to db code
// insert into db code
// send verification link code using PHP Mailer function..
?>
So when ajax loads the functions.php page how does javascript call the exact function(PHP Mailer).
I just want to state that i am new to programming i'm only a bit conversant with php. My knowledge of Javascript and Ajax can be said to be negligible. Also want to say a big thank you to all contributors.
Javascript will never call PHP functions, since PHP is running on the server and Javascript is running in the web-browser. The server and the web-browser are assumed to be different machines, the only exception being testing by developers. Therefore, if you have a function in functions.php called foo, Javascript will not be able to call it.
As you have already mentioned in your question, this might involve AJAX, which is surely true, but let's be more exact: when your Javascript code intends to "execute" a PHP function, it needs to trigger a request to the server. Not necessarily with AJAX, as you can trigger form submission, or anchor click as well. The request will reach the server, which will handle it.
Now, since we know that the life cycle is as follows:
Javascript detects that foo has to be executed
Javascript triggers a request to the server
Server is requested
Server handles the request
Server responds
The missing piece in the puzzle is to let the server know that it has to execute foo. To achieve this, the server has to determine somehow whether foo needs to be executed. This can be done with various way, including get params or post params. Next, you need to modify your Javascript code or html structure to let the server know that the function needs to be executed.
You can add a get parameter to the href of the anchor tag, for instance, but in general, you need to let the server know what the intention is and at server-side you need to handle that intention.
Also, you are doing validation on the server. This is ok, but may I advise you to validate the inputs on client-side and prevent posting if the input is invalid, to reduce server load... On server-side, if the post is valid, you need to execute the needed functions.
Also, this part is not exactly correct:
if (isset ($_POST)){
This is not the right approach to check whether this was a post request. You need
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
instead.
It is not important if the Request comes from javascript or a regular server Request (user clicks on link). You need to check the GET or POST parameters and redirect the Request to a specific function.
<?php
if( isset( $_GET['method'] ) ) {
// NOTE: untested and REALY unsecure Code
$method = $_GET['method'];
if( function_exists( $method ) ) {
call_user_func( $method );
}
}
else {
echo '<a id="link" href="?method=foo">klickme</a>';
}
function foo(){
echo 'in method';
}
?>
<div id="answer"><!-- server answer here --></div>
when you now have a link
http://yourSite.com?method=foo
and the function foo gets executed.
Now the JS part you have to check if the user clicks on a link, or sends a form. Then you have to send the request to server using Ajax and handle the result from the Server.
// inject the serverData in DOM
function loadSuccess( e ) {
document.getElementById( 'answer' ).innerHTML = e.target.response;
}
// handle click, open ajax request
function doClick( e ) {
e.preventDefault();
var ajax = new XMLHttpRequest();
ajax.open("GET", e.target.href ,true);
ajax.send();
ajax.addEventListener('load', loadSuccess);
}
var link = document.getElementById( 'link' );
link.addEventListener( 'click', doClick );
I have 2 php files named card_process.php and payment.php. I'm trying to pass data from the cart_process page to payment page. The code goes like this:
cart_process.php:
$paynow = "<button type='submit' id='reset' class='btn btn-danger' align='center' disabled>PAY NOW</button> ";
$cart_box_total = '<div class="cart-products-total" id="cart-products-total" name="subtotalsub">.$total.</div>';
?>
<script>
$(document).ready(function() {
$("#reset").click(function() {
var content = $('#cart-products-total').html();
$.post("payment.php", { html: content})
.done(function(data) {
window.location = "payment.php";
});
});
});
</script>
And on payment.php:
<?php echo $_POST['html']; ?>
As the page redirects to payment.php, the $_POST['html'] doesn't echoes anything, but if I use alert(content) in cart_process.php it alerts me with the needed data.
How can I post the whole data to the page?
Replace window.location = "payment.php"; with:
$('body').append( data );
See how that works out. Eventually you may want to designate a destination target element:
<div id="ajax-target"></div>
Then instead of $('body').append( data ) you would have:
$('#ajax-target').html( data );
UPDATE
If you must be redirected, then you do not need ajax. Here is how you can do that:
$(document).ready(function() {
$("#reset").click(function() {
var content = $('#cart-products-total').html();
$('<form action="payments.php" method="POST"/>')
.html( '<textarea name="html">' + content + '</textarea>' )
[0].submit();
});
});
You have some misconceptions of the order of operations taking place here. You're actually invoking payment.php twice. Once as a POST request with the html parameter here:
$.post("payment.php", { html: content})
and then again as a GET request without any parameter here:
window.location = "http://selina.co.il/payment.php";
The client-side code is essentially ignoring the result of the POST request and just sending the user to the GET request, which naturally doesn't echo anything.
It's not entirely clear what you're trying to do here, but if you're using AJAX then you probably don't really want to be redirecting the user to anything anyway. So instead of doing this:
window.location = "http://selina.co.il/payment.php";
Do something in that AJAX callback to modify the current page. Maybe set the data variable to some content on the page? Something like this?:
$('#someDiv').html(data);
It's really up to you what should happen here, we can't tell for certain from the code posted.
If the flow of the application indeed is that the user should be redirected to another page, then you have two options:
1: Expect a GET parameter instead of a POST parameter in the PHP code and include it on the redirect:
window.location = "http://selina.co.il/payment.php?html=" + encodeURIComponent(content);
That will probably be pretty ugly if content is what it implies to be.
2: Don't use AJAX at all and simply have a form which POSTS to payment.php.
I want to hide get variables in url
I want this
"dem/?p=user"
instead of whatever i passed like
dem/?p=user&act=stored
dem/?p=user&act=changed
dem/?p=user&act=deleted
Mates please help for me.
Advance thanks.
If you want to hide GET variables or values you should not use GET. In GET methods the data will always be send as part of the url. If you want to 'hide' the data (or not show it in the URL) from the user you should use a POST method.
You may use any one of the following:
Use POST method instead of GET
Use Ajax, with either POST or GET method
Use encryption and decryption if you really wish to send secured way i.e dem/?p=ENCRYPTED_STRING. Here ENCRYPTED_STRING will have all the GET data
Obviously since you did not take the time to tell us how you page structure is and how you are storing your values I can only guess.
Server side
If you store the data on a post-redirect page you can store it in a $_SESSION
session_start();
if (isset($_SESSION['message']))
{
$_SESSION['message'] = "succes";
}
Then on your confirmation page
session_start();
echo $_SESSION['message'];
Client side
You can create hidden inputs and add these to your form, set your form to post and handle these $_POST values on your form action page.
var x = document.createElement("INPUT");
x.setAttribute("type", "hidden");
x.setAttribute("name", "message");
form.appendChild(x);
Then on your confirmation page
if (isset($_POST['message']))
{
echo $_POST['message'];
}
modify .htaccess file to make short URLs the way you want them to look like
I've searched for over an hour and tried many examples but none do what I need. From JavaScript I can display the necessary variable in PHP or HTML with <b id="citynm"></b> but I need to make citynm $citynm. I've tried looking in AJAX for the first time but could only get it to work with a button click or page refresh.
I need to run the JavaScript to get citynm and then make it into $citynm for PHP use on any page without running the JS again. The JS is only run once upon entering the site. But the $citynm will be run on several pages in different needs (such as echo "You live in ".$citynm).
The best way is to store the value you want for citynm into a session variable as below:
$_SESSION['citynm'] = $citynm
You have to do this either at page load, or by ajax. Then, you can use $_SESSION['citynm'] in any pages you want since its global.
USECASE 1: via user input
in your html document:
<input type="text" name="citynm" id="citynm" value="Brussels">
inside your javascript file (using jquery here for readability):
(function(){
$('#citynm').on('blur',function(){
// when the input value has changed, post its value to server.
var citynm = $(this).val();
$.post('http://domain.com/path/to/your/php/file.php',{citynm: citynm},function(data){
// if the request is successful, the following script will be executed.
alert("server said: "+data);
});
});
})(jQuery);
And inside the file.php file:
<?php
session_start();
if(isset($_POST['citynm']) && strlen($_POST['citynm'])>0){
$_SESSION['citynm'] = $_POST['citynm'];
}
echo "citynm is ". $_SESSION['citynm'];
?>
USECASE 2: no userinput
var cityname = city.short_name;
if (status == google.maps.GeocoderStatus.OK) { document.getElementById("citynm").innerHTML = cityname; }
(function(){
$.post('http://domain.com/path/to/your/php/file.php',{citynm: cityname},function(data){
// if the request is successful, the following script will be executed.
alert("server said: "+data);
});
})(jQuery);