Submit form and refresh DIV without page refresh not working? - javascript

Please note this is not a duplicate question. This question involves submitting a form and refreshing a div on a change event - not a click event. FYI.
I have a form to allow users to upload an image. I have removed the submit button and added a javascript on change event to submit the form automatically when the user inputs an image.
This works fine and the image is uploaded.
However, I am also pulling through the image to display this to the user. At the moment, the user does not see the image change until they refresh the page or sometimes not even until they clear their cache.
The div containing the images should refresh upon the form being submitted, and the page itself should not refresh. At the moment the div is not refreshing and I think the form is submitting and refreshing the page.
Please can someone show me where I am going wrong? Thanks
Code:
<!-- Commence Photo Upload A -->
<?php
if(isset($_FILES['image6'])){
$dir = $image .'/F/';
$file_name = $_FILES['image6']['name'];
$file_name = $dir. 'sub_img.jpg';
$file_size = $_FILES['image6']['size'];
$file_tmp = $_FILES['image6']['tmp_name'];
$file_type = $_FILES['image6']['type'];
$tmp = explode('.',$_FILES['image6']['name']);
$file_ext=strtolower(end($tmp));
$extensions= array("jpeg","jpg","png","gif");
if(in_array($file_ext,$extensions)=== false){
$errors[]="extension not allowed, please choose a GIF, JPEG or PNG file.";
}
if($file_size > 2097152) {
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true) {
move_uploaded_file($file_tmp, $file_name);
}else{
}} ?>
<script>
$('#uploads6').submit(function(){
var data = $(this).serialize();
$.ajax({
url: "upload_6.php",
type: "POST",
data: data,
success: function( data )
{
//here is the code I want to refresh the div(#container)
$('.image6').html(data);
},
error: function(){
alert('ERROR');
}
});
return false;
});
</script>
<form id="uploads6" action = "" method = "POST" enctype = "multipart/form-data">
<label class="profile_gallery_image_in"><input type="file" name="image6" id="image6" onchange="form.submit()"/><p class="label"></p><img class="myImg" src="<?php echo $image.'/F/sub_img.jpg'; ?>" height="100%" width="100%" /></label>
</form>

For image caching you can try the age old "cachebuster" method.
All it is is put something unique into the url query.
www.example.com/image.jpg?cachebuster=somethingunique
The browser will see this as a new request because it doesn't know what the query string does, it could be a search form for all it cares. So it will not pull it from the cache.
Good choices for the something unque is any time based component, as you know its never been used before. Ive used filesize($file) before when doing image edits.
$url = "www.example.com/image.jpg?cachebuster=".microtime(true); //as a float
$url = "www.example.com/image.jpg?cachebuster=".time(); // only 1 second granularity
$url = "www.example.com/image.jpg?cachebuster=".filesize($file); // based on the size of the file
$url = "www.example.com/image.jpg?cachebuster=".hash_file($file); //based on file contents
And so on. You can even do it in JavaScript if you want to.
For the form
$('#uploads6').submit(function(e){
e.preventDefault();
//.. other code
return false;
});
One note is using $.post how you are will probably prevent the file from being uploaded.
Here is another SO question on that:
jQuery Ajax File Upload
If you want a non-javascript way to upload without refreshing page, you can also do it though an iframe but the onLoad even may not work in Chrome for that, so it can be hard to tell when the file is uploaded from the client side.
Here is a SO question I answered on that back in 2014
How can I upload files asynchronously?

To prevant default form submission try:
e.preventDefault();
To stop event bubling try:
e.stopPropagation();
Also try to add a ‚#‘ or ‚javascript:void(0)‘ in your HTML action-attribute.

You need to use
$('#uploads6').submit(function(e) {
e.preventDefault();
// your code
}
to prevent the submit event from directing to the page that is given in the action value. This is right now the same page since the value of the action attribute is an empty string and therefor the page is refreshed.

Related

Target wpcf7submit event for specific Post Id

With the help of wordpress contact form 7 and popupmaker plugin for contact form in popup.
I would like user to first fill out a form, and after successful submission pdf will download. I am using javascript to target "wpcf7submit" event and one hidden field in contact-form having pdf with below wordpress action hook:
function case_study_download(){ ?>
<script>
document.addEventListener('wpcf7submit', function(event){
if('6980'== event.detail.contactFormId){
var inputs = event.detail.inputs;
var urs = inputs[6].value;
window.location.href=urs;
setTimeout(function(){
location.reload();
}, 3000);
}
}, false);
</script>
<?php
}
add_action('wp_footer', 'case_study_download');
Using above code I can able to download pdf after submission of contact form 7 form. And I am using popup-maker plugin to open contact form on-click.
This all work fine, however I have displayed multiple post with pdf links on the same page, for that I am also passing post-id in the above condition using "detail.containerPostId" custom event but I didn't get any pdf after form submission.
Refer below:
function case_study_download(){ ?>
<script>
document.addEventListener('wpcf7submit', function(event){
if('6980'== event.detail.contactFormId && '345'== event.detail.containerPostId){
var inputs = event.detail.inputs;
var urs = inputs[6].value;
window.location.href=urs;
setTimeout(function(){
location.reload();
}, 3000);
}
}, false);
</script>
<?php
}
add_action('wp_footer', 'case_study_download');
Please advice me, Is it a right way to pass post-id in the above condition?
Because, I want to download a specific pdf by post-id with the same contact-form-id (or multiple).

How to prevent a php page from browser back button?

I have a form which contains many drop-down and numeric slide-bar.
I am using post method to pass the selected variables to another page. Where I am getting the variables in the next page by $_POST() method.
And I am updating the variables passed into the database, after updation giving javascript pop-up as "you have saved successfully".
So my problem is when I click on browser back button, the values are getting updated in the database again and again. How can I prevent this by disabling browser back button.
You can have your post method open up a new tab so that there is no back navigation to go to:
<!DOCTYPE HTML>
<html>
<body>
<form action="www.google.com" method="post" target="_blank">
<input type="submit">
</form>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$('#theSubmit').on('click', function () {
setTimeout(function(){
window.close();
}, 500);
})
</script>
The target generates the new window
And if you would like to close the old window add the two scripts that close the previous tab 500ms after the new tab is opened.
Instead of disabling the back button, you could redirect the user if he gets back to the page using sessions.
page1.php
session_start();
if (isset($_SESSION['block'])) {
header('Location: page2.php');
}
page2.php
session_start();
$_SESSION['block'] = true;
Another option:
This is how you could set values of all your input fields back, if the user clicks back:
page1.html
var block = localStorage.getItem("block");
window.addEventListener("beforeunload", function() {
if (block === 1) {
const block = true;
}
});
if (block) {
const inputs = document.getElementsByTagName('input');
for (input of inputs) {
input.value = '';
}
}
page2.html
localStorage.setItem("block", 1);
In this case, if you don't want your values get updated in your database, use:
if (!empty($_POST['my_value']) { // Add to database })
Don't disable the back button, fix the problem that the data is saved multiple times instead. You could use pass the users to a separate page with message "you have successfully...".
Then if the user tries to go back you look at $_SERVER['HTTP_REFERER'] if that is "successful.php" then don't save the data.
Disabling back buttons is a big reason for me to block a page so that I can't visit it again.
I truly hate when they do that or add several pages that you have to click back to get out of a page.
Whenever you post your data then you should check your post data that this is empty or not
<?php
if(isset($_POST) && !empty($_POST) ){
//your code for update
//Then after run update query and success message ,do empty the post
$_POST=array(); // empty the post
}
?>

Trouble passing a variable from javascript page to php page

I want to send a string from one php page to another via a JavaScript page.
The string is sent through upon the push of a button. The name of the
button is changed each time it is displayed and the name of the button is
the one that is sent through. The problem is, it is not getting displayed in
next php page but the alert() function outputs the string as required. What
is wrong with the code?
Here is the php code in the first page
echo "<form method = 'post' action = 'passer.php'>
<input type = 'submit' value = 'play' name = '$ball'></input>
</form>";
Here's the javascript code
$(':input').click(function(){
var cat = $(this).attr("name");
alert(cat);
console.log(cat);
$.post("studSport.php",{input: cat}, function(data){
});
});
And the php code in the next page
{
$receiver = "";
if(isset($_POST['input'])){
$receiver = $_POST['input'];
echo $receiver;
} else{
echo " it is empty";
}
}
The output is always "it is empty" even though the alert() displays the right variable. What is wrong with the code, why wont $receiver be displayed?
Your Ajax request never runs. When you click the input you trigger it… but the input is a submit button so the Ajax request is canceled, the form submits, and a new page is loaded.
Since your form doesn't have an input named input, you'll always failed the test if(isset($_POST['input'])). (The Ajax request, which gets canceled, does input input, but you never make that request).
To stop the form submitting you need to capture the event object and prevent the default behaviour that the event would normally trigger.
$(':input').click(function(evt){
evt.preventDefault();
Note, however, that your success handler function:
function(data){
}
… does nothing, so you won't be able to see the result without inspecting the HTTP response using your browser's developer tools.
It is possible that your goal isn't to use Ajax, but is to load a new page - just with additional data in the form.
To do that, you need to modify the controls in the form instead.
$(':input').click(function(){
var cat = $(this).attr("name");
alert(cat);
$(this).append(
$("<input type='hidden' name='input'/>").val(cat)
});
});
But if you just want to tell which submit button was pressed then don't involve JavaScript at all. Just use a submit button with the name and value you want.
<form method='post' action='passer.php'>
<button name="input" value="<? echo htmlspecialchars($ball); ?>'>
play
</button>
</form>

php page refresh not working after picture upload

How can I refresh the page automatically after the user is done uploading profile picture?
Well the picture gets updated once the user refreshes the page but I want to force refresh the page on its own.
I am uploading the file and updating my database like this:
$query="UPDATE users set image='".$username_db."_n.gif' where user_name='$username_db'";
mysqli_query($con,$query);
And after this I want a refresh code.
I have tried several ways to do so:
echo "<script type='text/javascript'>$('.display_picture_image').attr('src', '".$src."?".time()."');<scipt>";
exit;
where .display_picture_image is the image tag where I want to display the picture.
echo "<meta http-equiv='refresh' content='0'>"
exit;
Then
header("Refresh:0");
exit();
Then
header("Location:".$_SERVER[REQUEST_URI]);
exit();
Then
header("Location:page_name.php");
exit();
Then
echo "<script type='text/javascript'>location.reload();</script>";
But nothing is working. What am I doing wrong?
I have a page: index.php. It contains the form which is self referencing form.
if(isset($_POST['submit'])
include 'upload.php';
Once the picture is submitted, the code from from
upload.php
is executed. The picture is then uploaded and then
echo '<script type="text/javascript">$(window).on("load",function(){window.top.window.showcrop("'.$target_file.'","'.$username_db.'","'.$imageFileType.'");});</script>';
calls the function showcrop. in a js file which is linked in the header.
Then after the cropping area is selected and submitted this is executed:
function crop_photo() {
var x_ = $('#x').val();
var y_ = $('#y').val();
var w_ = $('#w').val();
var h_ = $('#h').val();
var photo_url_ = $('#photo_url').val();
var username_ = $('#username').val();
var fileTypeImage_ = $('#imageFileType').val();
// hide thecrop popup
$('#popup_crop').hide();
// display the loading texte
// crop photo with a php file using ajax call
$.ajax({
url: 'crop_photo.php',
type: 'POST',
data: {x:x_, y:y_, w:w_, h:h_, photo_url:photo_url_, username:username_, fileTypeImage:fileTypeImage_, targ_w:TARGET_W, targ_h:TARGET_H},
success:function(data){
// display the croped photo
}
});
}
// updateCoords : updates hidden input values after every crop selection
function updateCoords(c) {
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
}
Then the crop.php is executed which uploads the cropped picture and updates the database. In the end, the refresh code is written but doesn't work.
SERVER SIDE :
Note : Put below code after uploaded your file and updated your database :
header("Refresh: 300;url='REDIRECTION URI'");
The browser will redirect after 300 seconds. It can be disabled in configuration of the browser though, but it's not commonly disabled.
CLIENT SIDE :
location.reload();
Okay so I figured out the answer on my own. In my crop_photo.php file I have,
$.ajax({
url: 'crop_photo.php',
type: 'POST',
data: {x:x_, y:y_, w:w_, h:h_, photo_url:photo_url_, username:username_, fileTypeImage:fileTypeImage_, targ_w:TARGET_W, targ_h:TARGET_H},
success:function(data){
// display the croped photo
}
});
Well in the above code, i mentioned nothing within
success:function(data){
//display the cropped photo
}
Though that is where php is gonna echo stuffs.
So I edited that as,
success:function(data){
//display the cropped photo
$('#image_div').html(data);
}
By this whatever I echoed in php was put inside the division with id image_div.
Then I echoed
echo '<script>window.location='redirectbackurl.php'</script>';
and it redirected to redirectbackurl.php which redirected back to the previous link.
Code of my redirectbackurl.php
<?php
header("Location:".$_SERVER['HTTP_REFERER']);
exit();
?>
Now i understand, i could simply use location.reload(), but due to form re submission issues, i did this.

Avoid form multiple submissions and re-enable when done

I have a form which allows to view data in a page or download it in csv according to the submit button pressed.
Since it's a long database query I want to avoid the user to submit more than once (you know how heavy is users' index finger on left mouse button...) to avoid database overload and also to make user more relaxed...
I wrote this little jQuery code to substitute submit button(s) with a Processing, please wait and the classic animated spinning gif
$(document).ready(function(){
//preload wait img
var $waitImg = $('<img />').attr('src', '/img/wait.gif')
$('.wait').click(function(){
$(':submit').hide();
$(this).after($('<span>Processing, please wait...</span>').prepend($waitImg));
});
});
All works but has some drawbacks:
when user sees results and then press the browser's back button he will get again the Processing, please wait sentence and no submit buttons (what if he just wants to edit something and make a new query)
after user is prompted to download the CSV file he keeps on being told to wait...
Solutions could be to detect someway user is back or download stared or another way to tell him work is in progress.
The easier, the better.
When user sees results and then press the browser's back button he will get again the Processing, please wait sentence and no submit buttons (what if he just wants to edit something and make a new query)
The browser is caching the page. You could try resetting the values/removing the loading image in $(document).ready() which should fire when the user presses the back button using the onunload trick: Is there a cross-browser onload event when clicking the back button?
after user is prompted to download the CSV file he keeps on being told to wait...
It won't be possible to detect this without the help of the server. The easiest thing to do would be to "ping" the server via ajax and the server will tell the client if the download was initiated/sent to the user. This can be done by repeatability calling the server every i.e. 3 seconds to see if the download was initiated and if so, reset/hide the loading image and text.
You could use jQuery deferred to help make this easy and of a nice syntax.
jQuery
function downloadStarted()
{
var $def = $.Deferred();
var check = function() {
$.get('/ajax/check-download-status', function(response) {
if (response.started)
{
$def.resolve();
}
else
{
//Check again in 3 seconds
setTimeout(check, 3000);
}
}, 'json');
};
check();
return $def.promise();
}
Usage:
var success = function() { /* reset/hide loading image */ }
$.when(downloadStarted()).then(success);
PHP/Server side
On the server side ajax/check-download-status will look like so:
session_start();
$json['started'] = 0;
if ($_SESSION['download_started']) $json['started'] = 1;
return json_encode($json);
And obviously when your csv file is sent to the client, set $_SESSION['download_started'] to 1.
Found this:
Detecting the File Download Dialog In the Browser
and this is my code based on it:
html
<form ...>
<fieldset>
...
<div>
<input class="wait" id="submit" name="submit" type="submit" value="View" />
<input class="wait" id="submit" name="submit" type="submit" value="Download as CSV" />
</div>
</fieldset>
</form>
javascript
$(document).ready(function(){
var cookieCheckTimer;
var cookieName = 'download_token';
var $wait = $('.wait');
var $waitMsg = $('<span>Processing, please wait...</span>').prepend(
$('<img />').attr('src', '/img/wait.gif').css({
'vertical-align': 'middle',
'margin-right': '1em'
}));
//add hidden field to forms with .wait submit
$wait.parent().each(function(){
$(this).append($('<input />').attr({
'type': 'hidden',
'name': cookieName,
'id': cookieName
}));
});
$wait.click(function(){
var token = new Date().getTime();
//set token value
$('#' + cookieName).val(token);
//hide submit buttons
$(':submit').hide();
//append wait msg
$(this).after($waitMsg);
cookieCheckTimer = window.setInterval(function () {
if ($.cookie(cookieName) == token){
//clear timer
window.clearInterval(cookieCheckTimer);
//clear cookie value
$.cookie(cookieName, null);
//detach wait msg
$waitMsg.detach();
//show again submit buttons
$(':submit').show();
}
}, 1000);
});
});
Server side if a download_token key is found in request parameters a cookie with its name and value is set.
Here's my python (pylons) code for a controller's __before__ :
python
cookieName = 'download_token'
#set file download coockie if asked
if cookieName in request.params:
response.set_cookie(cookieName,
#str: see http://groups.google.com/group/pylons-discuss/browse_thread/thread/7d42f3b28bc6f447
str(request.params.get(self._downloadTokenName)),
expires=datetime.now() + timedelta(minutes=15))
I set cookie expire time to 15 minutes to not fill up client cookies, you choose an appropriate duration based on time needed by task.
This also will work with browser back button issue as when going back the cookie will be found and buttons restored.

Categories