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.
Related
I have a problem with PHP and JavaScript.
Goal: A .php script should be executed when the event listener of the HTML button in the .js file is called without reloading the page.
Expected result: When the button is clicked, the PHP script gets executed. In my case, a file from a URL will be downloaded to the server.
Actual result: I don't know how to call the PHP script from the JavaScript file.
I tried using AJAX, but nothing really worked out. Also I didn't know where exactly to put the library reference for JQuery.
I also tried to use a form, and inside of it an input (type="submit"), but when this calls the PHP function, it refreshes the page and everything on the page which was displaying client side is gone.
The HTML button:
<button type="button" class="button" id="btnsubmit">Submit</button>
<img class="image" id="someimage">
The JavaScript event listener (I have the button and image already assigned to a var):
btnsubmit.addEventListener("click", () => {
someimage.src = "directory/downloadedimg.png";
});
The PHP script:
<?php
$path = 'https://somewebsite.com/imagetodownload.png';
$dir = 'directory/downloadedimg.png';
$content = file_get_contents($path);
$fp = fopen($dir, "w");
fwrite($fp, $content);
fclose($fp);
?>
So in general, I want to do as follows when the button gets clicked:
Download the image from the URL to my server using PHP
Display the image from the server (not from the URL, I know it's possible, but for my use I need it to be from the server) in an HTML image using JavaScript
I tried the answer of #Abhishek and figured the problem now lies in my php file. It always gives me an internal server error.
Do you spot any error in this code to upload the image from the $path (it's a URL) to my server (serverdirectorypath is $image_url):
<?php
$params = $_POST['data'];
$path = $params['path'];
$image_url = $params['image-url'];
$content = file_get_contents($path);
$fp = fopen($image_url, "w");
fwrite($fp, $content);
fclose($fp);
?>
You can do following things.
Add jquery in head/bottom section of your page like
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Use jquery AJAX and call your php script like below
$("#button-id").on('click',function(){
var data = {"image-url" : "directory/downloadedimg.png","path" : "https://somewebsite.com/imagetodownload.png"};
$.ajax({
type: 'POST',
url: "{hostname}/test.php",
data: data,
dataType: "json",
success: function(resultData) { alert("success"); }
});
});
In your php script ex- test.php, use code like below to get post params.
$params = $_POST['data'];
$path = $params['path'];
$image_url = $params['image-url'];
and do the business operation, you want to do in this.
No need another library, you can do this with vanillaJs.
Your misunderstanding come from : "how to call php with Js and get returned value"
Start here you have an exemple: https://www.w3schools.com/php/php_ajax_php.asp
Once you will be able to call your PHP script you will have done 70% of your target
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.
I'm having some trouble right now with wordpress and the functions.php file. For reference I'm using ninja forms and pop-up maker.
I have a bunch of buttons. When you click one button, it opens a modal where the user will enter in their contact information. That information is then stored and a success message is displayed with a link to the resource the user requested. Since I don't want the user to have to keep filling out information for every resource, I have a cookie stored. To make up for this, I am storing the user's information inside the $_SESSION variable, since I still want to know when the user clicked a resource link.
Because I am using ninja forms I am hooking into the ninja_forms_after_submission function and storing the session in there.
function register_session(){
if(!session_id()){
session_start();
}
}
add_action('init','register_session',1);
add_action('ninja_forms_after_submission','test');
function test($form_data){
// assume ive processed some data here
// and $form_data['name'] / $form_data['email'] is valid
register_session();
$_SESSION['name'] = $form_data['name'];
$_SESSION['email'] = $form_data['email'];
}
Cool. This works and I can echo out $_SESSION and see valid data. Now, since the user is clicking links, and I want to still capture the session, I am doing the following (underneath the code above, still in functions.php):
add_action('wp_footer','save_session',500);
function save_session(){
?>
<script type="text/javascript">
(function($,document,undefined){
$(document).on('click','.pum-trigger',function(){
var post = {};
post['name'] = "<?php echo $_SESSION['name']; ?>";
post['email'] = "<?php echo $_SESSION['email']; ?>";
post['action'] = 'get_resource';
$.post(ajaxurl,post,function(response){
});
});
}(jQuery,document))
</script>
<?php
}
add_action('wp_ajax_get_resource','get_resource');
add_action('wp_ajax_nopriv_get_resource','get_resource');
function get_resource(){
echo json_encode($_POST);
}
This code does work and triggers every time a user clicks on a resource link after the first form has been filled out.
The problem is, $_SESSION['name'] and $_SESSION['email'] do not load into the javascript function until after the user refreshes the page.
So if I enter the information Name: Test, Email: test#test.com into the first form that pops up, and I verify that $_SESSION['name'] and $_SESSION['email'] were saved (by printing it out in the ninja forms hook), then I click another link, the line: echo json_encode($_POST); only shows: {"name" : "", "email" : ""}
After refreshing the page, and clicking a link, echo json_encode($_POST); now shows: {"name" : "test", "email" : "test#test.com"}
The problem with this is that the user probably won't refresh the page on their own. Is there some way to have the value that is saved from the test() function appear in the save_session() function without reloading the page? I've tried global variables, but that doesn't work either.
Any advice on how to set this up would be greatly appreciated.
UPDATE: I resolved my issue by moving my form submitter script from the Header to the bottom of the jamesmsg.php page (the included one). This way the functions always get re-loaded and attached to the "new" form everytime the div is refreshed.
This is a follow-up to a previous question I had about getting only a div to refresh (and not the entire page) when submitting a form. I've stripped out all the unnecessary javascript and code to just focus on this problem but I'm still stumped.
When I click submit the first time, the data is posted and we're good. When I click submit the second time, the entire page refreshes, the URL now shows POSTed data.. the good news is the data IS inserted to the mysql db, I just need to get this form acting properly like it does for the first click (at least it appears to do so).
My main php file is james.php:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
</head>
<body>
<div id='mainpage'>
<div id='control'>CONTROL DIV 1 ... 2 ... 3</div>
<div id='statusupdates'><? include 'jamesmsg.php'; ?></div>
</div>
</body>
</html>
so you can see I have a "Control Div" which should never change and my statusupdates div which should always be updated with the submitted form data (and a subsequent pull from mysql to show the latest updates).
jamesmsg.php (mysql credentials xxx intentionally for this post):
<?
$xxx = new mysqli("xxx","xxx","xxx",xxx);
$MsgText = $_POST["MsgText"];
if ($MsgText != "") {
$query = "INSERT INTO Messages SET
MsgDate = NOW(),
MsgAuthor = 0,
MsgText = '" . mysqli_real_escape_string(xxx,$MsgText) . "'";
if (!xxx->query($query)) {
print "error! xxxx->error<BR>query = $query<BR>";
}
}
print "<form id=\"statusform\" action=\"james.php?L=1\">
<textarea name=MsgText rows=5 cols=40></textarea><BR>
<input type=submit value=Post id=uhsbutton>
</form>";
?>
<?
print "<BR><BR><pre>POST Variables:<BR>";
print_r ($_POST);
print_r ($_GET);
print "</pre>";
?>
<?
$query = "SELECT * FROM Messages ORDER BY MsgDate DESC LIMIT 5";
$msgq = $xxx->query($query);
if ($msgq->num_rows > 0) {
while ($r = $msgq->fetch_array()) {
print ".......<BR>";
print "msg ID: " . $r["ID"] . " - " . $r["MsgDate"] . " " . $r["MsgAuthor"] . "<BR>";
print $r["MsgText"] . "<BR>";
}
}
else {
print "no messages";
}
?>
<script>
/*************************************
* form submitter
**************************************/
$(document).ready(function() {
$("#statusform").submit(function(e) {
e.preventDefault();
var data=$(this).serialize();
var pUrl="jamesmsg.php";
submitFormSave(data, pUrl);
});
function submitFormSave(data, pUrl) {
$.ajax({
url: pUrl,
type: 'POST',
cache: false,
data: data,
success: function(response) {
$("#statusupdates").html(response);
}
}).success(function(){
});
}
});
</script>
You can see this in action by going to: demo
Viewing this in Chrome's console I get no errors at all.
The problem is with the success callback that you've set for your AJAX call:
success: function(response) {
$("#statusupdates").html(response);
}
This ends up overwriting the entire form and the original submit event handler you set up when the page first loaded is lost. Since there is no event handler present to prevent the default behaviour, the second button click causes the entire page to refresh.
So, what I would do is get your server response to return data in the form of JSON or XML (preferably JSON since it easily integrates with JavaScript).
Right now, your server response is returning HTML back. This is something you want to avoid. The server should serve you data and then on the client side you should dynamically generate your HTML via JavaScript to show data in a readable format.
I solved my issue by moving the javascript from the Header to appear at the bottom of the included page: jamesmsg.php.
I'm now able to post and have the appropriate div refresh without the entire page always refreshing.
I currently have a like button that now works with Ajax. With one minor flaw. I click like on a post and it updates 1 like and shows in the page. But if I refresh the page it vanishes out of sight. The like is still in the database it just doesn't show in the page. Now someone told me to use
$(document).ready(function () {}
to do this on page load, but I have no clue how to use it to make my likes show on page refresh.
Or maybe I have to make a new call on page refresh to get all the likes for each post.
This is what I have so far
function likestatus(postid,contextid){
var obj = document.getElementById(contextid);
$.post("../include/like_do.php", { streamitem_id: postid},function(data){
//see the parameter data in this function. Data contains whatever that you echo in your php file.
$("#likesprint"+postid).html(data+"Likes");
});
}
Like_do.php
<?php
session_start();
require"load.php";
if(isset($_POST['streamitem_id'])){
$check = user_core::check_liked($_SESSION['id'],$_POST['streamitem_id'],1);
user_core::do_like($_SESSION['id'],$_POST['streamitem_id'],1);
echo $check; // as your user_core::check_liked() function returns number of likes.
}else{
echo "<script>alert('Error liking post');</script>";
}
?>