how to prevent page refresh to top page after submit [closed] - php

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" />&nbsp&nbsp
</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">&nbsp&nbsp
<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.
}
});
});

Related

how to stop reload the page after submit?

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

PHP Display search result text file in external html file

I'm trying to create a html form in the file index.html from where I can query a text file for a line of characters through PHP via the file searchFile.php, get the specific line and display it in said form in index.html.
My problem is that I nothing is displayed in my Search Results field, neither the error message or a search result.
Update! I've investigated my problem further and I realized that the way I'm using the Search button doesn't allow for any echoes to stay displayed on the page before the page is updated again and the echocontent is removed. Still, I don't know how I should solve this issue without using two buttons, one for searching and one for getting the result of the search.
This is what I've come up with so far:
index.html
</head>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
$(function() {
// getting the search term
var searchString = $("#search_box").val();
// forming the searchString
var data = 'search='+ searchString;
//if searchString is not empty
if(searchString) {
// call ajax
$.ajax({
type: "POST",
url: "searchFile.php",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});
}
return false;
});
</script>
<form name="theForm" method="post">
Name: <input type='text' onclick="ajaxFunction();" name='search' class='search_box' id='search_box'/> <br />
<input type='submit' value='Search' class="search_button" ><br />
</form>
<div id="searchresults">Result: <span id="results" class="update"></span></div>
</body>
</html>
searchFile.php
<?php
$search = explode(' ', $_REQUEST["search"]);
$lines = file('file-export.txt');
foreach($lines as $line)
{
if(strpos($line, $search[0]) !== false && strpos($line, $search[1] !== false)) {
echo '<div id="searchresults">' . $search . '</div>';
}else{
echo '<div id="searchresults">' . "No match" . '</div>';
}
}
?>
Edit: updated the button field with action="searchFile.php"
Edit 2: Functioning Search button
Edit 3: Minor changes
You are trying to find a search string in the block that doesn't exist
var searchString = $("#search_box").val();
You have no block with id search_box, only with class search_box, that is $(".search_box") or
<input type='text' onclick="ajaxFunction();" name='search' class='search_box' id='search_box'/>

trouble with if($_SERVER['REQUEST_METHOD'] == "POST")

please help me.
I have form like this in index.php
<form id="statusForm" enctype="multipart/form-data" method="post">
<textarea name="statusText" role="textbox" id="wallpost"></textarea>
<input id="photo_input" type="file" name="photo_input" />
<input type="hidden" name="to_id" value="1" >
<button type="button" name="submit" onClick="write_wall_post();">
</form>
<div id="content"></div>
then i have .js file to handle this form
function write_wall_post()
{
var formData = new FormData($("#statusForm")[0]);
$.ajax({
type: "POST",
url: "act_post_status.php",
data: formData,
success: function(data){
$("#wallpost").val("");
$("#photo_input").val('');
var newStatus=data;
$(newStatus).hide().prependTo("#content").fadeIn(2000);
},
processData: false, // tell jQuery not to process the data
contentType: false,
cache:false
});
}
and i have act_post_status.php to process this file submit
<?php
//some configuration
if($_SERVER['REQUEST_METHOD'] == "POST")
{
//some variable declaration and image validation
//Original Image
if(move_uploaded_file($uploadedfile, $path.$time.'.'.$ext))
{
$is_image=1;
}
else
echo "failed";
}
}
//inserting data to database
$status = trim(strip_tags(htmlspecialchars($_POST["statusText"])));
mysql_query("insert into news (status,is_image) values ('$status','$is_image')");
echo "<div class='post'>$status</div>";
?>
the scenario i want is:
when user input data (status), then click submit button, the content automatically show the update (handled by jquery)
but the fact is:
(1) when I completed the form (both status and picture), it works normally.
(2) but when I completed just data form (filling status input only), it was submitted to database successfully, but the content don't update automatically. I should refresh them to get the update.
(3) when i just filling the image input, it works normally like case (1).
Please help why if($_SERVER['REQUEST_METHOD'] == "POST") failed to echo the input by ajax request when data input (status) is blank/empty.
thousands of thanks. :)
I'm not sure why it matters whether you leave the file input unfilled, but you need to disable the normal form submission when you use AJAX. The onclick function should return false to do this.
<button type="button" name="submit" onClick="write_wall_post();return false;">

Hiding a form upon click of the submission button

<?php
'<form method="post" action="postnotice.php");>
<p> <label for="idCode">ID Code (required): </label>
<input type="text" name="idCode" id="idCode"></p>
<p> <input type="submit" value="Post Notice"></p>
</form>'
?>
Alright, so that's part of my php form - very simple. For my second form (postnotice.php):
<?php
//Some other code containing the password..etc for the connection to the database.
$conn = #mysqli_connect($sql_host,$sql_user,$sql_pass,$sql_db);
if (!$conn) {
echo "<font color='red'>Database connection failure</font><br>";
}else{
//Code to verify my form data/add it to the database.
}
?>
I was wondering if you guys know of a simple way - I'm still quite new to php - that I could use to perhaps hide the form and replace it with a simple text "Attempting to connect to database" until the form hears back from the database and proceeds to the next page where I have other code to show the result of the query and verification of "idCode" validity. Or even database connection failure. I feel it wrong to leave a user sitting there unsure if his/her button click was successful while it tries to connect to the database, or waits for time out.
Thanks for any ideas in advance,
Luke.
Edit: To clarify what I'm after here was a php solution - without the use of ajax or javascript (I've seen methods using these already online, so I'm trying to look for additional routes)
what you need to do is give form a div and then simply submit the form through ajax and then hide the div and show the message after you get the data from server.
<div id = "form_div">
'<form method="post" id = "form" action="postnotice.php";>
<p> <label for="idCode">ID Code (required): </label>
<input type="text" name="idCode" id="idCode"></p>
<p> <input type="submit" value="Post Notice"></p>
</form>'
?>
</div>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'postnotice.php',
data: $('form').serialize(),
success: function (data) {
if(data == 'success'){
echo "success message";
//hide the div
$('#form_div').hide(); //or $('#form').hide();
}
}
});
e.preventDefault();
});
});
</script>
postnotice.php
$idCode = $_POST['idCode'];
// then do whatever you want to do, for example if you want to insert it into db
if(saveSuccessfulIntoDb){
echo 'success';
}
try using AJAX. this will allow you to wait for a response from the server and you can choose what you want to do based on the reponse you got.
http://www.w3schools.com/ajax/default.ASP
AJAX with jQuery:
https://api.jquery.com/jQuery.ajax/

Jquery form plugin recalling php echo in an iframe [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
putting html inside an iframe (using javascript)
I'm using the following code and what I want to do essentially (I'm new to jquery) is submit this form, but then have what is normally outputted on the uploadpic.php page - appear on this page where the form is, in an iframe. I just can't work out how to do it. I added the Jquery Form Plugin - http://www.malsup.com/jquery/form/
So I've gone through the code and commented what it does now. But I've no idea how to add that iframe exchange. Basically the uploadpic.php does this:
$add_one = $membership->add_photo($_POST['photo'], $_POST['caption']);
And if it is all submitted successfully, or if it is a failure, it echos either "sorry your file wasn't uploaded" or "file was uploaded successfully.
How would I stop from having to go to a new page, or resorting to an irritating popup? I thought a temporary iframe would be a good idea - but simply no idea how to implement such a thing.
<div id="uploadform">
<form id = "uploadpicform" enctype="multipart/form-data" action="uploadpic.php" method="POST">
<p>Photo: </p><input type="file" name="photo"><br />
<p>Caption:</p> My <input type="text" name="caption"><br />
<input type="submit" class="large blue button" value="Add">
</form>
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#uploadpicform').ajaxForm(function() {
$("#hideuploadbutton").hide();
$("#uploadbutton").show();
$("#uploadform").hide();
});
});
</script>
</div>
What that does at the moment, is submits the form, with no notice, hides the upload button and shows an open upload button to start the process again. I figure there must be some sort of 'add iframe' or 'print php variable from the other page' option or something.
I'd appreciate any help, thanks a bunch!
EDITED Added code for populating iframe
HTML
<form id="uploadpicform">
<p>Photo:</p>
<input type="file" name="photo"><br />
<p>Caption:</p>
<input type="text" name="caption"><br />
</form>
<div id="uploadpicbutton" class="bluebutton">Upload</div>
JQuery
// **ADDED** Populate the iframe
function iframeresults() {
var content = phpresults;
var tFrame = document.getElementById("iframeid");
var doc = tFrame.contentDocument;
if (doc == undefined || doc == null)
doc = tFrame.contentWindow.document;
doc.open();
doc.write(content);
doc.close();
}
//Submit Upload Ajax Call Function
function submit_upload() {
$('#status').html('Uploading, Please Wait').fadeIn(500);
$.ajax({
type: "POST",
url: "/uploadpic.php",
cache: false,
data: $('#uploadpicform').serialize(), //This adds the variable name and input values automatically
dataType: "script", // Returns Javascript outputted from PHP page and Launches the Script
success: function(){
iframeresults();
});
}
// Bind the upload function to the button
$('#uploadpicbutton').on('click', submit_upload);
PHP
//Use this echo in your PHP after your PHP Successful validation
echo "var phpresults = 'Upload Succesful'; ";
//Use this echo in your PHP after your PHP Failure validation
echo "var phpresults = 'Upload Failed'; ";

Categories