Run PHP script when button is clicked without refreshing page - javascript

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

Related

Is it possible to edit message body of all sent emails in wordpress

I am testing if it's possible to edit the html code of all the emails sent from wordpress. This is what I came up with until now:
add_filter('wp_mail_content_type', function( $content_type ) {
return 'text/html';
});
add_filter('wp_mail', 'my_wp_mail');
function my_wp_mail($atts) {
$atts['message'] .= ' <br/><div id="result">my text line here</div>';
return $atts;
}
The code above will add the line "my text line here" at the bottom, I am looking for a way to be able to replace the div using JavaScript with content form another page using:
<script>
jQuery(document).ready(function(){
jQuery('#result').load('https://develop2020.000webhostapp.com/divdiv.html .myclass');
});
</script>
then the email to be sent. Is it possible to do this with JavaScript or does PHP have to be used? If it is possible, how can I pull a div from a url and add it to all emails?
Welcome to Stack Overflow!
First of all, using JS inside an email is not possible.
Using Javascript to send or determine content of emails seems really cumbersome, since Wordpress sends emails through PHP. Javascript runs in a browser (when it comes to Wordpress) and not on a server, so somehow a page would have to be opened in a browser to send the emails if you would try to do it with JS. If something is done on the server, like sending emails, you want to use PHP.
As for a solution, it makes more sense to get the page inside .load() with curl (https://www.php.net/manual/en/curl.examples-basic.php) or file_get_contents (https://www.php.net/manual/en/function.file-get-contents.php), and then making what you load with that part of an e-mail using the filter you used to add content to the bottom of the emails.
If you only want to use a part of the page that you've retrieved with curl/file_get_contents, you can select that part using DOMdocument from PHP:
https://www.tutorialspoint.com/php/php_dom_parser_example.htm
https://www.php.net/manual/en/class.domdocument.php
I found this way this worked
add_filter('wp_mail_content_type', function( $content_type ) {
return 'text/html';
});
add_filter('wp_mail', 'my_wp_mail');
function my_wp_mail($atts) {
$url = 'https://develop2020.000webhostapp.com/divdiv.html';
$dom = new DOMDocument();
#$dom->loadHTMLFile($url);
$xpath = new DOMXpath($dom);
$elements = $xpath->query('//div[#class="myclass"]');
$link = $dom->saveHTML($elements->item(0));
$atts['message'] .= $link;
return $atts;
}
it worksed but now the issue with the page I want to capture the div from the div get loaded using ajax ..so not sure there is a solution

how to execute a php function from a separate php file onClick

I have two php files (1.php and 2.php) linked with require
php.1 has a qr <img src="http://chart.googleapis.com/chart?chs=125x125&cht=qr&chl=<?php echo $_jattu; ?>" width="50%"> which gets its value from a string variable in 2.php $_jattu;
What I want is for <?php echo $_jattu; ?> to only echo when <a class="w3-button2 w3-black2"></a> is clicked and not when the page is loaded or refreshed, what can I do to achieve this?
This is imposible to do on the server side. Because the "onClick" event jumps on the client side when de user do the action.
You have few options.
Enable another URL for load the content of $_jattu and when the user click load it with an AJAX request. Is the best way to do it and the result is more smooth and user friendly
As you say you want to do it refreshing. So, slightly refresh the page with a new parameter on your url that tolds you that the "onClick" event has jump. Like:
.../your/path?hasClick=true
And in your php code:
if(isset($_GET["hasClick"]) && $_GET["hasClick"]){
echo $_jetty;
}
http://php.net/manual/en/reserved.variables.get.php
if you want to remember that the user has clicked "forever" you can setup a cookie.
http://php.net/manual/en/function.setcookie.php
You can use ajax. Make a request to whatever php script you want which will return $_jattu when clicking on the link. Then update your img link in javascript using the return of the ajax request.

How to stop refreshing page when passing js value to php using windows.location.href on the same page

In my page, when the user clicks the <div>, it opens a modal and within that click, it passes a value to the modal. Now since that value is in javascript, I want to pass it to php so I can use it for my query. What I used is window.location.href but when I click the modal, it refreshes the page thus not opening the modal.
JS code:
<script>
$(document).ready(function(){
$('#editModal').on('show.bs.modal', function (e) {
var id = $(e.relatedTarget).data('id');
//window.location.href = "tasks.php?id="<?php $id = isset($_GET['id']) ? $_GET['id'] : ""; echo $id; ?>"&final=" + id;
jQuery.ajax({
url:'tasks.php?id=<?php $id = isset($_GET['id']) ? $_GET['id'] : ""; echo $id; ?>',
type: "POST",
data: {'name': id},
dataType: 'text',
success: function(data)
{
alert(id);
}
});
});
});
</script>
PHP code | tasks.php?id=2 (2 is just a sample value, it can be different depending on what the user clicked on the previous page)
<?php
include('config.php');
$value = $_POST['name']; //returns unidentified index
//$value = $_POST['final'];
echo "I got your value! $value";
?>
It keeps refreshing the page everytime I try to open the modal. With that, I cannot actually look or see if the value was passed. Is there more efficient way of passing this on the same page? Or how can I stop the page from refreshing? Your help will be much appreciated. Thank you!!
As soon as you assign window.location.href, the browser will automatically go to the new URL.
To achieve what you're looking for, I suggest you make an AJAX request instead.
Since you're using jQuery, they've got a fantastic helper that provides everything you need and abstracts away from browser specifics. See here - http://api.jquery.com/jquery.ajax/.

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.

Ajax: First Post great, Second Post returns Data in URL

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.

Categories