Change Page Content via jQuery after Uploading File - PHP - php

I don't know if something like this has already been asked and answered, but since no matter what search query I make, nothing seems to be close to what I am looking to do. I am working on a project where the user will upload a file. Once the file has been uploaded it will show the user a success message as well as some file info. I am trying to keep this all within one page, if possible, but can't seem to get it to work. File gets uploaded, but the info does not show.
Here is something like what I am working with:
<?php
if(isset($_POST['uploadFile']) && isset($_FILES['file'])) {
move_uploaded_file($_FILES['file']['tmp_name'], "files/" . $_FILES['file']['name']);
$message = "\"" . $_FILES['file']['name'] . "\" uploaded successfully...";
}
?>
<html>
<head>
<title>Upload File</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(".uploaded-file-info").hide();
$(".uploadForm").submit(function() {
$(".upload-form").hide();
$(".uploaded-file-info").show();
});
});
</script>
</head>
<body>
<div class="upload-form">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" class="uploadForm" >
<input type="file" name="file" /><br />
<input type="submit" name="uploadFile" value="Upload File" />
</form>
</div>
<div class="uploaded-file-info">
<p><?php echo $message; ?></p>
</div>
</body>
</html>
Like I said, the file gets uploaded, but the form doesn't hide and the file info ($message) doesn't show. Any suggestions?

The problem is the JQuery part :
$(".uploadForm").submit(function() {
$(".upload-form").show();
$(".uploaded-file-info").show();
});
coupled with this line :
<form method="post"
The JQuery part is saying : As soon as the form on the page is submitted, Show the information DIV.
The "Form" part just say : Submit the form.
So, when you click the button, the form is submitted and at the same time, the JQuery is executed. But then the form that you just posted needs to "refresh" the page to get the response back from the server. Basically, the JQuery you wrote display your div while you submit it. Meaning that it will work for a fraction of a second but will display an empty div because the response of the server is not there yet.
What you probably want to do is something like :
When the page loads
And there is content in the uploaded-file-info
Show the info and hide the form.
Add a Style tag with the following :
<style>
.uploaded-file-info {
display: none;
}
</style>
It will always hide the uploaded-file-info when the page loads.
Then, change your JavaScript code with :
<script>
$(document).ready(function() {
if ($('.uploaded-file-info > p').html() != "") {
$(".uploaded-file-info").show();
}
});
</script>
It says that when the page loads, if something is present inside the children of the element "uploaded-file-info", then show it. Otherwise, do nothing.
An easier solution would be to display the block, with php (so on the server side), only if a file was uploaded. No need for JQuery (client side) code.
Remove all the JQuery code and code within "<style>" tags and replace surround your "div class="uploaded-file-info" with an IF like this :
<?php if ($message != '') { ?>
<div class="uploaded-file-info">
<p><?php echo $message; ?></p>
</div>
<?php } ?>
Here's what will happen then:
you post (from your browser) the form
the server receives your post
if there is a file uploaded, it will initiate your "message" variable
and if the message variable exists, the server will put the "div uploaded-file-info" into the response. If not, everything surrounded by the "if" won't be put into the response.
your browser will receive the response and display it on screen.

Related

How to create confirm yes/no in php?

I want to create a confirm yes/no box in php
my code like this:
<?php
if(isset($_REQUEST['id']))
{
?>
<script>
var cf=confirm("do you want to delete Y/N");
if(cf)
{ i want to call code edit of php
}
</script>
<?php
}
?>
<html>
<head>
</head>
<body>
<form name="frm" method="post" action="edit.php">
Edit <br>
Edit <br>
Edit <br>
</form>
</body>
</html>
I Want to when press Yes i call code edit in PHP
But it do not work.
Can you help me ?
Thanks you
Just use inline onclick event.
This is a simple techique, you can use it in your PHP page.
Edit
In your code, you have mentioned PHP but, have used JavaScript.
If you want to do a confirm with PHP,
Create an intermediate page for confirmation.
Post form data there.
On confirmation page, add two submit buttons:
Yes: If pressed this, redirect/post to edit page.
No: If pressed this, redirect back to form
So, your confirmation page should be:
<html>
<head>
</head>
<body>
<?php
if (isset($_POST['confirm'])) {
if ($_POST['confirm'] == 'Yes') {
header("Location:edit.php?id=1");
}
else if ($_POST['confirm'] == 'No') {
header("goBack.php");
}
}
?>
<form method="post">
<?php
if(isset($_REQUEST['id']))
{
?>
<input type="submit" name="confirm" value="Yes"><br/>
<input type="submit" name="confirm" value="No"><br/>
<?php
}
?>
</form>
Put an id on your form:
Create an event listener for the form's onsubmit event
<script>
function onFormSubmission(e){
return confirm("do you want to delete Y/N");
}
var frm = document.getElementById('frm');
frm.addEventListener("submit", onFormSubmission);
</script>
When the user submits a form they will be prompted with your message. If they click Yes the function will return true and the form will be submitted. Otherwise the function will return false and the form submission will be cancelled
I think this is what you want to do:
<?php
//YOU MUST BE SURE THAT YOUR URL CONTAINS THE $_REQUEST['id'] PARAMETER, OTHERWISE IT WON'T WORK FROM YOUR CODE... IF YOU WANT IT TO WORK REGARDLESS OF THAT, JUST COMMENT OUT THE IF(ISSET(... BLOCK...
$editURL = "edit.php"; //EDIT URL HERE
if(isset($_REQUEST['id'])) {
//ASSIGN THE ID TO A VARIABLE FOR BUILDING THE URL LATER IN JS...
//THE DEFAULT ID IS 1 BUT YOU CAN DECIDE WITH YOUR OWN LOGIC
$defaultID = ($dID = intval(trim($_REQUEST['id']))) ? $dID : 1;
?>
<script>
function confirmEdit(evt){
evt.preventDefault();
var cf=confirm("do you want to delete Y/N");
var id=<?php echo defaultID; ?>;
if(cf){
//i want to call code edit of php
//HERE'S THE CODE YOU MAY NEED TO RUN;
if(id){
//RETURN TRUE SO THAT THE SCRIPT WITH LINK TO THE APPROPRIATE URL
return true;
// OR REDIRECT WITH JAVASCRIPT TO EDIT PAGE WITH APPROPRIATE ID
//window.location = "" + <?php echo $editURL; ?> + "?id=" + id; //YOU ALREADY HAVE THE EDIT URL... JUST APPEND THE QUERY-STRING WITH ID TO USE IN THE EDIT PAGE
// You might also just (without redirecting) return true here so to that the page continues like you just clicked on the link itself...
}
}
}
</script>
<?php
}
?>
<html>
<head>
</head>
<body>
<!-- THE FORM TAG IS NOT NECESSARY IN THIS CASE SINCE YOUR ANCHOR TAGS HAVE THE EXACT URL YOU WANT ASSOCIATED WITH THEM... AND YOU DON'T EVEN NEED JAVASCRIPT IN THIS CASE... BECAUSE THE HREF OF THE LINKS ARE HARD-CODED... -->
<!-- <form name="frm" method="post" action="edit.php"> -->
<a class='class-4-css' onclick="confirmEdit();" id='dynamic-id-based-btn-1' href="edit.php?id=1">Edit Page 1 </a> <br>
<a class='class-4-css' onclick="confirmEdit();" id='dynamic-id-based-btn-2' href="edit.php?id=2">Edit Page 2</a> <br>
<a class='class-4-css' onclick="confirmEdit();" id='dynamic-id-based-btn-3' href="edit.php?id=3">Edit Page 3</a> <br>
<!-- </form> -->
</body>
</html>
So, now clicking on any of the Links will Ask me to confirm if I want to delete the Resource or not. If I choose yes, then the appropriate page is loaded for the Process...
not sure if the other answers really answered your question, this was my problem too, then I experimented and here's what I came up with:
.
confirmation in php :
$Confirmation = "<script> window.confirm('Your confirmation message here');
</script>";
echo $Confirmation;
if ($Confirmation == true) {
your code goes here
}
that's all, other people might look for this, you're welcome :)
I was looking to simply have a confirmation box in php before triggering POST isset without going through javascript:
echo "<input id='send_btn' type='submit' value='previous'
name='previous' OnClick=\"return confirm('Are you sure you want to go
to previous');\" >";
This appeared for me to be the easiest solution.

Why doesn't a form returned by a jquery AJAX call to PhP into a DIV not work?

I am trying to write an interactive web page and learn newer (10 years or less) web technologies along the way. So PhP, jquery and AJAX all fall into that category. I've pared down the code to just the essentials to ask this question.
I want my jquery to call a PhP program that will load two separate DIVs. One is a data display area and the other is used to display the next form in the process chain. The trouble I'm having is that the form I'm returning isn't functional, even though it displays properly.
This is the main page (demo.php):
<?php
echo <<<_END
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<script>
//
$(document).ready(function(){
$("#btnDemo").click(function() {
$("#PageForm").load("thetest.php", { paramYN: $("#paramYN").val() })
$("#PageContent").load("nextpage.php");
});
});
</script>
</head>
<title>The Title</title>
</head>
<body>
<div id="PageHdr">
<H4>Heading</h4>
</div>
<div id="PageForm">
<form action="" id="Login">
<br/>
To show this form again enter Y otherwise enter N : <input type="text" name="paramYN" id="paramYN" size=1>
<input type="button" name="btnDemo" id="btnDemo" value="test it" /></form>
</div>
<div id="PageContent">
<P>Put response here</p>
</div>
</body>
</html>
_END;
?>
Here's the PhP program "thetest.php" which decides what to return into the PageForm DIV:
<?php //thetest.php
paramYN = $_POST["paramYN"];
if ($paramYN == "Y")
{
echo <<<_EOF
<form action="" id="Login">
<br/>This is the redisplay. Look for the date to change if it works after you click the test it button
<br/>To show this form again enter Y otherwise enter N : <input type="text" name="ParamYN" id="paramYN" size=1>
<input type="button" name="btnDemo" id="btnDemo" value="test it" /></form>
_EOF;
$thetime = time();
echo $thetime;
exit();
}
else
{
echo "<html><head><title>PDO login</title></head><body>";
echo "<h1>Congrats!</h1>";
echo "</body></html>";
exit();
}
?>
I only included the nextpage.php program because the full version of my program needs to update both DIV's. For the purpose of this demo it's as simple as this:
<?php //.php
echo "<h1>This is the new text for this place</h1>";
?>
So what is my problem here? Is it something in the way that I'm loading the DIV? Or is this something that is not doable?
When your page first loads you use jQuery and "bind" a click event to your button "btnDemo".
The user then clicks the button "btnDemo" and triggers the load events. However, by doing this you are overriding your previously loaded button with the established jQuery events with a NEW button "btnDemo". This NEW button does NOT have the same bound click events.
You will need to re-apply the click events to the newly loaded button after it loads by adding the jQuery to the loading page "thetest.php".
echo <<<_EOF
<script>
$(document).ready(function(){
//this will bind the click event to the newly loaded button
$("#btnDemo").click(function() {
$("#PageForm").load("thetest.php", { paramYN: $("#paramYN").val() })
$("#PageContent").load("nextpage.php");
});
});
</script>
<form> (the rest of your form here...)
_EOF;
You have:
<?php //thetest.php
paramYN = $_POST["paramYN"];
if ($paramYN == "Y")
{
Try:
<?php //thetest.php
$paramYN = $_POST["paramYN"];
if ($paramYN == "Y")
{

Undefined index when passing variable from jquery to php

I'm trying to pass a variable from an html file, using jquery and ajax to a php file, where I want to process it. I have two test files:
ajax.html
<html>
<head>
<title>ajax</title>
<script type="text/javascript" src="jquery.js"></script>
<link href="ajax.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
$("#call_back").click(function () {
$.post(
"ajax.php", {
value: $("#input_text").val()
},
function (data) {
$("#response_text").val(data);
}
);
});
});
</script>
</head>
<body>
<div id="wrapper">
<h3>Ajax</h3>
<div class="entry-wrapper">
<h4>Data to send to the server</h4>
<input type="text" size="50" id="input_text" />
<input type="button" value="Ajax Callback" id="call_back" />
</div>
<div id="response_wrapper">
<textarea id="response_text"></textarea>
</div>
</div>
</body>
</html>
and ajax.php
<?php
$value = $_POST['value'];
echo "Returned from the server: $value";
?>
The html works fine. If I enter a value in the text field, it's passed to the php file, processed and sent back to be displayed in the textarea.
I've looked in firebug and the post tag in the console shows the values that I enter.
The problem is that I want to be able to use the variable in the php file, for arithmetic operations or running an sql query with it, but it shows up as undefined index when I open the php file.
I've looked through multiple threads on passing variables from jquery to php but still found no answer. I have no idea what the problem is. Suggestions are much appreciated. Thanks.
If I understand you question correctly, you need to define the variable in your url.
Example:
http://yoursite.com/ajax.php?value=yourdata
This way when you open the file you are defining the value which is all you are doing with your ajax request. If this is not what you are trying to accomplish, try to rephrase your question.
Revised after 1st comment:
<?php
if(isset($_POST['value'])){
//do whatever in here
dowhatever();
}
function dowhatever() {
$value = $_POST['value'];
echo "Returned from the server: $value";
if(value == 'data') {
//run query
}//end if
}
?>
I assume that when you say you can confirm it's working, but when you directly open the .php file, it has undefined index, then I would say that makes perfect sense. If you are browsing directly to the .php file, then no POST data is being sent. But if you are able to type in some text, fire off the submit, and get text back as planned, then it's working.

generate code using form button and then display generated code on page

I have two file code_generator.html. which takes input as a image url and landing url when i click on submit button it calls code_created.php
<html>
<head>
</head>
<body>
<form action ="code_created.php" method ="post">
Image : <input type ="text" name ="image">
Landing Url : <input type ="text" name="landingurl">
<input type= "submit">
</form>
</body>
</html>
I want to show generated code as below on web page
<div id='banner-img' style='display:none;text-align:center' onclick='landing()'><img style='text-align:center' id='bannerImage'/>
<img id='t'/>
<img id='trackeridImg' style='display:none;width:0px;height:0px'/>
</div>
<script type="text/javascript">
function showAd() {
document.getElementById('banner-img').style.display = 'block';
document.getElementById('bannerImage').setAttribute('src',IMAGE URL SUBMITTED FROM HTML FILE);
</script>
problem is that webpage is not showing that code generated code ,webpage is rendering that code , I want to only show that generated code.
1-how to do it using html and php
2-is my approach is right
You can use tag to show HTML entities You need to encode all
Your HTML entities like < => < like way.
Also you can show a text area in which all those HTML code need to echo, it will not execute your code simply it will print it.

PHP Page load/refresh to exact position

What I'm trying to do is to pass a user to a php script via a href link, then have them passed back to exactly the same position that they were at before they clicked the link, like the page hasn't been refreshed. Does anyone know if or how this could be possible possible? Thank you.
Using HTML you can have the following
<p id='open_here'><a href='script.php'> Send to script </a> </p>
And then you can link back to that exact position with
Send Back to page
So essentially, instead of using a regular link as in the previuos code snippet, you could redirect back to the page using
//php redirect
<?php header('Location: mypage.html#open_here'); ?>
//Javascript redirect
<script type='text/javascript'>
window.location = "mypage.html#open_here";
</script>
If you don't mind adding some Javascript to make it work, here is a solution that will make it possible to redirect back to the exact same scrollbar position as when the user clicked the link.
index.php (the file where the link is)
<script>
window.addEventListener('load', function() {
// Do we have a #scroll in the URL hash?
if(window.location.hash && /#scroll/.test(window.location.hash)) {
// Scroll to the #scroll value
window.scrollTo(0, window.location.hash.replace('#scroll=', ''));
}
// Get all <a> elements with data-remember-position attribute
var links = document.querySelectorAll('a[data-remember-position]');
if(links.length) {
// Loop through the found links
for(var i = 0; i < links.length; i++) {
// Listen for clicks
links[i].addEventListener('click', function(e) {
// Prevent normal redirection
e.preventDefault();
// Redirect manually but put the current scroll value at the end
window.location = this.href + '?scroll=' + window.scrollY;
});
}
}
});
</script>
page.php (the PHP script that redirects back)
<?php
// Get the provided scroll position if it exists, otherwise put 0
$scrollPos = (array_key_exists('scroll', $_GET)) ? $_GET['scroll'] : 0;
// Redirect back to index.php and provide the scroll position as a hash value
header('Location: index.php#scroll='.$scrollPos);
Hope it helps! :)
I am just spilling ideas here, but I would use javascript to intercept user's click on the href, and .preventDefault first. Then figure out where the user is on the page. Maybe by splitting the page into sections, indentified by IDs. Your html markup would be something like
<div id="section-1"></div>
<div id="section-2"></div>
<div id="section-3"></div>
so when javascript prevents the link from executing, it would figure out in which section the user currently is. Let's say we know each section's height. Then we need to find out the scrollbar position. I haven't done that, but have a look here
http://api.jquery.com/scrollTop/
Once we know the height of each section and once we can detect where the scroll bar is, we can determine in which section the user is residing. Then, we fetch the url of the href link and add a query string to it like, http://something.com/script.php?section=2 and redirect user to it with whatever data you want . Then once the script has done it's job append the query string to the redirect-uri and redirect the user back with something like http://something.com#section-2 and the user will immediatly pop to section-2
I know this isn't a very specific answer, but hopefully I've given you some leads and ideas how to accomplish this. Let me know how it works!
I'd had to remember the scroll position for a <select>. Example below. Three
submit buttons to illustrate why there's three getElementById. To see
it work you must move the scroll bar first
<?php
$scrollusObscura=$_GET["imgbtn"];
$header = <<<EOD
<!DOCTYPE html>
<html>
<head>
<title>snk_db</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<head>
<script>
function gety(){
var y=document.getElementById('myUlID').scrollTop;
document.getElementById('imgbtn1').value=y;
document.getElementById('imgbtn2').value=y;
document.getElementById('imgbtn3').value=y;
}
function itemRelevatur(scrollum){
document.getElementById('myUlID').scrollTo(0, scrollum);
}
</script>
</head>
<body onload="itemRelevatur({$scrollusObscura})" >
EOD;
$html= <<<EOD
<div >
<select size="6" id="myUlID" name="myUlName" onscroll="myTimer = setInterval(gety, 300)">
<option>'1'</option>
<option>'2'</option>
<option>'3'</option>
<option>'4'</option>
<option>'5'</option>
<option>'6'</option>
<option>'7'</option>
<option>'8'</option>
<option>'9'</option>
<option>'10'</option>
<option>'11'</option>
<option>'12'</option>
<option>'13'</option>
<option>'14'</option>
<option>'15'</option>
<option>'16'</option>
<option>'17'</option>
<option>'18'</option>
<option>'19'</option>
</select>
</div>
EOD;
$html1= <<<EOD
<div><form method='GET' action'myscript.php'>
<input type='hidden' name='imgbtn' id='imgbtn1' value=''></input>
<input type='submit' value='Submit' ></input>
</form>
EOD;
$html2= <<<EOD
<form method='GET' action'myscript.php'>
<input type='hidden' name='imgbtn' id='imgbtn2' value=''></input>
<input type='submit' value='Submit' ></input>
</form>
EOD;
$html3= <<<EOD
<form method='GET' action'myscript.php'>
<input type='hidden' name='imgbtn' id='imgbtn3' value=''></input>
<input type='submit' value='Submit' ></input>
</form></div>
EOD;
echo $header;
echo $html;
echo $html1;
echo $html2;
echo $html3."</body></html>";
I had major problems with cookie javascript libraries, most cookie libraries could not load fast enough before i needed to scroll in the onload event. so I went for the modern html5 browser way of handling this. it stores the last scroll position in the client web browser itself, and then on reload of the page reads the setting from the browser back to the last scroll position.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
if (localStorage.getItem("my_app_name_here-quote-scroll") != null) {
$(window).scrollTop(localStorage.getItem("my_app_name_here-quote-scroll"));
}
$(window).on("scroll", function() {
localStorage.setItem("my_app_name_here-quote-scroll", $(window).scrollTop());
});
});
</script>

Categories