I have that code that make me download images from other wepsite to my wepsite and after a click on submit the page is reload. I want to stop page from reload.
the code I put it in some plugin in wordpress.enter image description here
the code that I put in the plugin
<form action="zip.php" method="POST">
<h2 class="inputmanga"> manga name:</h2></p>
<input type="text" name="name">
<h2 class="inputmanga"> image url:</h2></p>
<input type="text" name="img">
<h2 class="inputmanga"> image numper :</h2>
<input type="text" name="num"><br><br>
<input class="sumbitmanga" type="submit" value="Get!">
the php code that I put in separate folder
$zip = new ZipArchive();
$my_save_dir = "manga/".$_POST['name'].".zip";
$zip->open($my_save_dir, ZipArchive::CREATE);
$num = $_POST['num'];
for ($i=1; $i <= $num ; $i++) {
$url_to_image = $_POST['img'].$i.'.jpg';
$download_file = file_get_contents($url_to_image);
$zip->addFromString(basename($url_to_image), $download_file);
}
$zip->close();
echo $my_save_dir . " Download completed successfully";
You'll need to submit an ajax request to send the email without reloading the page. Take a look at http://api.jquery.com/jQuery.ajax/
$('.submitmanga').click(function() {
$.ajax({
url: 'zip.php',
type: 'POST',
data: {
// pass required data here
},
success: function(msg) {
alert('successfully sent');
}
});
});
The form will submit in the background to the zip.php page which will need to handle the request.
This is a repeated question, you do that by listening on the submit event.
https://stackoverflow.com/a/19454346/11028815
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I made a script to open all image on folder include form on it. Every time I post submit, page refreshes to the top of the page. How can I prevent it from refreshing after I hit submit?
<?php
$folder = ".."; //folder tempat gambar disimpan
$handle = opendir($folder);
echo '<table cellspacing="5" cellpadding="1" width="100%" >';
echo '<tr>';
$i = 1;
$fileGambar = array('JPG', 'jpg');
while(false !== ($file = readdir($handle))){
$fileAndExt = explode('.', $file);
if(in_array(end($fileAndExt), $fileGambar)){
echo '<td style="border:1px solid #000000;" align="center" >
<div class="hvrbox">
<img src="../'.$file.'" alt="Mountains" class="hvrbox-layer_bottom"
width="100%" />
<div class="hvrbox-layer_top">
<div class="hvrbox-text">'.$file.'</div>
</div>
</div> <br></br>
<form method="post" name="f1">
<b><u>'.$file.'</u>:</b>
<input type="hidden" name="namafoto1" value="'.$file.'">
<input type="submit" name="upload" value="UPLOAD" />  
</form>
<form method="post" name="f2">
<input type="hidden" name="namafoto" value="'.$file.'">
<input type="number" min="1" max="10" value="1" name="jumlah"
maxlength="3" size="3" >
<input type="submit" name="submitcetak" value="CETAK">  
<input type="submit" name="delete" value="HAPUS CETAK" />
</form
<script type="text/javascript" src="js/jquery-1.11.3.min.js">
</script>
<script type="text/javascript" src="js/hover-box.js"></script>
</select>
</td>';
if(($i % 1) == 0){
echo '</tr><tr>';
}
$i++;
}
}
echo '</tr>';
echo '</table>';
?>
and submit script is
<?php
// Turn off all error reporting
error_reporting(0);
$txtx = "../upload.txt";
if (isset($_POST['upload']) && isset($_POST['namafoto1'])) {
$fh = fopen($txtx, 'a++');
$txtx=$_POST['namafoto1'].PHP_EOL;
fwrite($fh,$txtx); // Write information to the file
fclose($fh); // Close the file
}
// $txt = "../cetak.txt";
// if (isset($_POST['submitcetak']) && isset($_POST['namafoto'])) {
// $fh = fopen($txt, 'a++');
// $txt=$_POST['namafoto'].PHP_EOL;
// fwrite($fh,$txt); // Write information to the file
// fclose($fh); // Close the file
if (isset($_POST['delete']) && isset($_POST['namafoto'])) {
rename('../print/'.$_POST['namafoto'], '../'.$_POST['namafoto']);
delLineFromFile ();
//echo "<meta http-equiv='refresh' content='1'>";
}
?>
Every time I press submit button, page refreshes and scrolls to the top of the page. Help me make it not refresh to the top of the page.
It is hard to write answer in code as the question is too broad and general but here are some links to get you started. If I understand correctly, you want to submit the form without page refresh. For that, use ajax. Serialize your form and post it using ajax so it won’t reload. Something like this:
//Serialize your form here
var formData = $("#yourFormID").serialize();
$.ajax({
type: "POST", //You are posting data so this is a post method
url: "post_data.php", //Your URL or link to php file which posts data
data: formData, //The data passed, which is the variable of serialized form
dataType: "json", //Data type json
success: function(data) {
//var parse = jQuery.parseJSON(data);
//if successful parse the data and display here
//use console.log(data) to see if you have data
},
error: function() {
alert('error handling here');
//use console.log(“error occurred”) to see if it failed
}
});
Link to Jquery Ajax
And additionally, if you want the page to refresh but scroll to a specific part of the page, try something like this:
//This is your HTML
<div id="bottom"></div>
//After posting in your php, use the code below
header('Location: contact.php#bottom');
As mentioned HERE
Hope this helps. Happy coding :)
Looking at you question, it seems you have alot of forms,
NOTE: am using jQuery
$("#id_of_the_form").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form which will reload the page
var form = $(this);//get the form
$.ajax({
type: "POST",
url: "The php script posting the form to",
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
// show response from the php script.
}
});
});
So I give my users the possibility to upload a xml file of their iTunes playlist. Once they've uploaded their xml-file, i need to read out that xml file. I tried it first with just an ajax call and a local xml file and it worked fine, but now i need to get acces to the uploaded xml file.
This is my upload form
<form id="formulier" action="playlist.php" method="post" enctype="multipart/form-data">
<fieldset>
<legend>Upload your playlist</legend>
</br>
<label>
<input type="file" name="bestand">
</label>
</br>
</br>
<input type="submit" value="Generate">
</fieldset>
this is my playlist.php file:
<?php
$path = "playlists/" . ($_FILES['bestand']['name']);
if(move_uploaded_file($_FILES['bestand']['tmp_name'], $path)){
}
header("Location:index.html?url=".$path);
?>
this is my ajax call that i previously used:
var my_fn = function(callback) { // <-- this is callback to be called later
var jax = [];
$.ajax({
url: "",
dataType: "xml",
success: function (data) {
var song = $(data).find('key').filter(function () {
return $(this).text().indexOf('Name') != -1;
}).each(function() {
var content = $(this).next('string').text();
jax.push(content);
});
callback(jax);
}
});
};
How do I get to read out the xml file that is uploaded by the user? I really do not have a clue...
My goal is to, upon clicking the form submit button, to upload the attachments from the form to the server and show a progress bar of that happening and then submitting the form (ie. mailing the message).
upload_form.php:
<form action="email_message.php" method="post" enctype="multipart/form-data" name="fileform" id="fileform">
<input type="hidden" name="MAX_FILE_SIZE" value="50000000"/>
<input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="uploads"/>
<label for="userfile1">Upload a file:</label>
<input type="file" name="userfile1" id="userfile1" class="userfile"/>
<input id="submit_btn" type="submit" value="Send Message"/>
</form>
In the same page, I run the following code to prevent the form from being executed and sending a request to upload all of the files from the form.
$(document).ready(function(){
$("#fileform").submit(function(e){
e.preventDefault();
var self = this;
var formData = new FormData(document.getElementById("fileform"));
var upload_req = $.ajax({
url: "./upload_multiple_files.php",
type: "POST",
data: formData,
processData: false,
contentType: false
});
upload_req.done(function(data){
alert("Uploading complete!");
});
});
});
upload_multiple_files.php:
<?php
session_start();
foreach ($_FILES as $k => $v){
// code to deal with file errors
if (is_uploaded_file($v['tmp_name'])){
// code to rename file
echo "<p>The file was successfully uploaded.</p>";
}else{
echo "<p>The file was not uploaded.</p>";
}
}
?>
All of this works: the files are all uploaded to the server.
The problem I have is integrating PHP Upload Session Progress (http://php.net/manual/en/session.upload-progress.php).
I know I need to use session.upload_progress.name and the $_POST array to get the file upload information but I'm not sure where to place it. I want to create an ajax call with an interval to periodically get the upload progress to be displayed on my form page. However, when I create a new page, the session information is empty. Here is an example of a page I tried:
get_progress.php:
<?php
session_start();
// $key is a combination of session.upload_progress.prefix and session.upload_progress.name
$results = array("content_length" => $_SESSION[$key]['content_length'],
"bytes_processed" => $_SESSION[$key]['bytes_processed']
);
echo json_encode($results);
?>
I checked the session ids from upload_form.php and get_progress.php and they are the same.
Any reason why $_SESSION is empty in get_progress.php? I think I missed something easy but I can't figure it out.
#Perry Your answer is right, session.upload_progress.enabled wasn't enabled in php.ini. Thanks.
I'm trying to create a file uploader with jQuery, that uploads a file, renames it with a timestamp and registers it into a DB. Basically it it sends the file with a form to the server where a second script renames it and moves the file to the right directory. This works without any problem. The problem is, that I want to send also the table name where this DB Entry should be made.
So index.php contains the form:
<div id="uploaderMain">
<p>Upload Your Files</p>
<form method="post" enctype="multipart/form-data" action="./upload.php">
<input type="file" name="images" id="images" />
<input type="hidden" name="List" id="List" value="<?php echo $DBTable; ?>" />
<button type="submit" id="btn">Upload Files!</button>
</form>
<div id="response"></div>
<ul id="image-list">
</ul>
</div>
The jQuery Code looks like this:
$.ajax({
url: "./uploader/upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
document.getElementById("response").innerHTML = res;
}
});
The upload.php looks like this:
<?php
//include db configuration file
include_once('../../db.php');
$List = $_POST['List'];
// get the time stamp for the uploaded file
date_default_timezone_set('EST');
$date = new DateTime();
$date = $date->getTimestamp();
// echo $date;
foreach ($_FILES["images"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$name = $_FILES["images"]["name"][$key];
// store the file name and the file ending in 2 variables
$fileEnding = substr($name, -4,4);
$fileName = substr($name, 0, (strlen($name)-4));
$uploadName = $fileName."_".$date.$fileEnding;
move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "./uploads/" . $uploadName);
}
}
after that I want to write to the DB. The problem is, that the $_POST['LIST'] statement doesn't provide my DBTable-name.
Can anyone give me a hint?
Cheers
Dan
I think you need to add this to your jQuery code:
formdata.append('List', '[your value]');
Please note: in PHP everything that is a file will go into $_FILES. Everything else will go into $_POST.
If this does not work, make sure you also have the following code:
var formdata = new FormData();
jQuery.each($('input[type="file"]')[0].files, function(i, file) {
formdata.append(i, file);
});
Can you check the source from browser if the List control has any value.
my 2form.php :
<script type="text/javascript" src="mootools.js"></script>
<script type="text/javascript">
function test()
{
url = '2form.php';
var ajax = new Ajax(url, {
method: 'post',
onComplete: function(response) {
document.getElementById('error_upload_logo').innerHTML = response;
}
});
ajax.request();
}
</script>
<?php
if($_FILES)
{
echo "<div>";
foreach($_FILES['name'] as $v)
{
echo $v."<br/>";
}
echo "</div>";
}
else
{ ?>
<form action='' id='form1' name="form1" method="post" enctype="multipart/form-data">
<input type="file" name="name"/>
<input type="submit" name="submit" onclick='test(); return false;'/>
</form>
<?php
}
?>
<div id="error_upload_logo"></div>
if run code with out javascript , it 2form.php like simple php page, and
we can see information of $_FILES that was printed to scrreen
But if i have run with javascript by test() function ,
i don't get information in $_FILES ?
How to get $_FILES ? when click button run with javascript ?
i want to upload with ajax
You can't do file uploads using AJAX because you won't have access to the local file.
The most common workaround is what the JQuery Form plugin does, creating a temporary iframe and doing a normal form submit into it.
The other alternative is using a Flash-based uploader like SWFUpload or Uploadify.