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'; ";
Related
I've been following along with some ajax uploading tutorial and it was working properly.
Here it's how i done,
i created a form in html like this.
<form id="submit_form" action="php-script/test_lates_statusbx-script.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Select Image</label>
<input type="file" name="ui-is-status_is_photo_fl" id="image_file" />
<textarea name="status_is_text_ara"></textarea>
<span class="help-block">Allowed File Type - jpg, jpeg, png, gif</span>
</div>
<input type="submit" name="is_status_forum_btn" class="btn btn-info" value="Upload" />
</form>
<div id="image_preview">
</div>
and here its my ajax code,
$(document).ready(function(){
$('#submit_form').on('submit', function(e){
e.preventDefault();
$.ajax({
url:"php-script/test_lates_statusbx-script.php",
method:"POST",
data:new FormData(this),
contentType:false,
//cache:false,
processData:false,
success:function(data)
{
$('#image_preview').html(data);
$('#image_file').val('');
}
})
});
});
and my php looks like this,
if(isset($_POST['is_status_forum_btn'])){
echo $fileactuname = basename($_FILES['ui-is-status_is_photo_fl']['name']);
echo $textareastatus = htmlspecialchars($_POST['status_is_text_ara']);
}
Problem: When i click the submit buttons it doesnt execute my code. But if i echo something outside of the isset function will does.Where am i wrong ?
A submit button is only a successful control if it is used to submit the form.
You are:
Using the submit button to submit the form
Preventing the default behaviour of the submit event so the form is not submitted
Collecting the data from the form with JavaScript
Making an HTTP request with that data
Since (due to step 2) the submit button is no longer being used to submit the form, it isn't included in the object you create with FormData().
Test for the presence of a different piece of data that you are sending.
e.g.
if(isset($_FILES['ui-is-status_is_photo_fl']))
In your php script, try like this
if (
isset($_FILES['ui-is-status_is_photo_fl']['name']) &&
$_FILES['ui-is-status_is_photo_fl']['error'] == 0
) {
print_r($_FILES);
print_r($_POST);
// Do the required task here
} else {
echo "error";
}
<?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/
I have a simple application here (QandATable2.php) where when the user clicks on the plus button, it will open a modal window and it displays the details which is stored in another page (previousquestions.php).
Now the problem I have is that if you straight away click on the "Search" button when the textbox is blank, you will see that it loads the page on its own page, displaying the message to enter in a phrase for the search and it also displays all of the features previously from the modal window into that page as well. This is incorrect.
What I want it to do is that if the user has clicked on the search button, then when it post's the form and outputs the message, it does it within the modal window, not on its own whole page. So does anyone know how this can be acheived?
The modal window I am using is known as SimpleModal and it's website is here
Below is the QandATable2.php code where it displays the plus button and where it opens the modal window, linking the content of the modal window to the previousquestions.php page:
<script type="text/javascript">
function plusbutton()
{
$.modal( $('<div />').load('previousquestions.php #previouslink') );
return false;
}
</script>
<h1>CREATING QUESTIONS AND ANSWERS</h1>
<table id="plus" align="center">
<tr>
<th>
<a onclick="return plusbutton();">
<img src="Images/plussign.jpg" width="30" height="30" alt="Look Up Previous Question" class="plusimage"/>
</a>
<span id="plussignmsg">(Click Plus Sign to look <br/> up Previous Questions)</span>
</th>
</tr>
</table>
Below is the previousquestions.php code, where it displays the details in the modal window and where the search feature is stored:
<?php
foreach (array('questioncontent') as $varname) {
$questioncontent = (isset($_POST[$varname])) ? $_POST[$varname] : '';
}
?>
<div id="previouslink">
<button type="button" id="close" onclick="return closewindow();">Close</button>
<h1>PREVIOUS QUESTIONS</h1>
<p>Search for a previous question by entering in a phrase in the search box below and submitting the phrase</p>
<form action="previousquestions.php" method="post">
<p>Search: <input type="text" name="questioncontent" value="<?php echo $questioncontent; ?>" /></p>
<p><input id="searchquestion" name="searchQuestion" type="submit" value="Search" /></p>
</form>
</div>
<?php
//...connected to DB
if (isset($_POST['searchQuestion'])) {
$questionquery = "SELECT QuestionContent FROM Question
WHERE(QuestionContent = '".mysql_real_escape_string($questioncontent)."')";
if (empty($questioncontent)){
echo "Please enter in a phrase in the text box in able to search for a question";
}
?>
You'll probably want to use AJAX, since you're already using jQuery you'll just need something like this:
// override the "default" form submitting behavior with a callback function
$("form").submit(
// this is the callback function for your form submit function.
function(e)
{
// this prevents the page from reloading -- very important!
e.preventDefault();
// get the search data from the input textbox
var s = $("input[name='questioncontent']").val();
// see annotation
$("#simplemodal-data").html("loading...")
.load("previousquestions.php #previouslink",
{
questioncontent : s,
searchQuestion : "Search"
}
);
}); // end submit wrapper
This will send the value to the server and load it in the div with id simplemodal-data
Annotation:
The last line in the code does several things. First, it replaces the simplemodal DIV with a "loading" message. At the same time, it makes a POST request to your previousquestions.php page. This part { questioncontent : s, searchQuestion : "Search"} is where the data from the form gets passed to the PHP page, (remember the variable var s assignment above. Lastly, the results from the previousquestions.php page should be loaded in the simplemodal-data modal window.
One thing that's missing is to add #previousquestions in the load method so that only a portion of your HTML document gets inserted in the modal. It's never a good idea to load an entire HTML page inside another HTML document, and "load" is designed to allow you to just pick the part of the document you want to insert, which is just that DIV.
I added "#previouslink" after the php filename. This is where the magic happens. The browser knows to extract that DIV from your PHP file and insert just that part on the page, no <head> <body> or any of the unneeded markup.
You can achieve what you're looking for by using AJAX to submit the form instead of using the default behavior where the page reloads with the new content. You can't use modal.load because you need to POST data in the request in order to get the appropriate response.
However, when using AJAX to post your data, you can take the response as HTML and add that HTML to a DIV on your page, and then invoke the SimpleModal command on that DIV container.
First, modify the submit button on your form so that it's type="button" instead of type="submit". This will prevent the form from submitting and redirecting the page. Alternatively, you could add event.preventDefault(); and return false to the form submit click handler (see the second step), but it's probably easier to try this method while you're making the changes:
Step 1:
<!-- change type to button -->
<input id="searchquestion" name="searchQuestion" type="button" value="Search" />
Step 2:
Create a handler for the form button, which uses serializeArray to serialize the form into a string and then POST it to the server. In the success callback handler, you'll then take the HTML response and replace the content in the modal window with the new HTML. This also catches errors, if any, and alerts them and writes them to the console:
$('form[type="button"]').click(function() {
var dataString = $('form').serializeArray();
$.ajax({
url: "/previousquestions.php?t="+new Date().getTime(),
type: "POST",
data: dataString,
context: document.body,
success: function(data){
alert(data); // results from server, either the HTML page, or JSON/XML
$('simplemodal-data').html(data); // if HTML, just insert into div#results
},
error: function(jqXHR, textStatus, errorThrown) {
if(window.location.hostname == "localhost") {
alert("Error submitting the form :: " + textStatus + " : " + errorThrown);
}
console.error("Error submitting the form :: " + textStatus + " : " + errorThrown);
}
});
});
Step 3:
Lastly, be sure that your previousquestions.php code returns only a partial HTML document, not a full HTML document. Since you're injecting HTML into an existing page, you don't need the <html>, <head>, or <body> sections. These will just cause your page to not validate, and may cause undesired behavior in legacy browsers. Here is an example of what your response might look like:
<div id="previouslink">
<button type="button" id="close" onclick="return closewindow();">Close</button>
<h1>PREVIOUS QUESTIONS</h1>
<p>Search for a previous question by entering in a phrase in the search box below and submitting the phrase</p>
<form action="previousquestions.php" method="post">
<p>Search: <input type="text" name="questioncontent" value="test" /></p>
<p><input id="searchquestion" name="searchQuestion" type="submit" value="Search" /></p>
</form>
</div>
<p>
Your Search: 'test' </p>
<p>Number of Questions Shown from the Search: <strong>0</strong></p><p>Sorry, No Questions were found from this Search</p>
I have found out from an answer on another page to a similar question to this that like Bergi has stated, it is easier using an iframe than using ajax to keep content displayed within a modal window. So the best answer for this question is below where it shows how an iframe is used for the question above:
function plusbutton() {
// Display an external page using an iframe
var src = "previousquestions.php";
$.modal('<iframe src="' + src + '" style="border:0;width:100%;height:100%;">');
return false;
}
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Enter button on Keyboard refreshes rather than submitting
I have the following form structure
structure of my form:
<form name="form">
<label>Name:</label>
<input type="text" name="name" id="id" size="50"/></br>
<label></label>
<input type="button" value="Get Info" onClick="get();">
</form>
<div id="age"></div>
My javascript for the get function is as follows:
function get() {
$.post('XXX.php', { name: form.name.value },
function(output){
$('#age').html(output).show();
});
}
Now when i use button(input type="button") to post information it works well,But when i fill the information and press enter on the keyboard page gets refreshed.
How can i make Enter button to post the info?
Many times the default behavior in a form when enter is pressed in a non-textarea field is to submit, even when a submit button was not pressed or even present.
Try this:
<form name="form" onsubmit="get();return false;">
In fact, using this technique, you would be able to change your input button to a submit to simplify the form with the same outcome:
<input type="submit" value="Get Info"/>
try return false; in your function. This will stop the button from having its usual behaviour:
function get() {
$.post('XXX.php', { name: form.name.value },
function(output){
$('#age').html(output).show();
});
return false;
}
I do it a little differently (which probably means its the wrong way). I dont make a form at all. I just create inputs, selects, etc.. and then when i do my POST i just get the values wen the function is called..
$.ajax({
type: "POST",
url: "someFile.php",
data: { 'name': $("#ElementID").val()},
success: function(data) {
//some function....
{
});
Hope that may be helpful....
I see you posted this as jQuery so I figured I'd give you a solution using that.
$('form[name=form]').submit(function(e) {
var $form = $(this);
$.post( $form.attr('action'), $form.serializeArray(), function( result ) {
$('#age').html( result ).show();
});
e.preventDefault();
});
This will keep you from having to create a crazy json object for the data parameter and from repeating yourself with the form's action attribute. This will also keep the browser's behavior where pressing enter when on an input will submit the form.
Here goes some code I have from an example earlier. The only thing in the form's action file is <?php print_r($_POST); ?>.
This is almost identical problem which I faced a few days ago. I fixed it then, but now it's not working any more. Well, some of it works.
I'm using AjaxFileUpload Plugin to upload files in my WP plugin. This plugin calls uploader.php to process the upload form.
I am able to get the filename (and other data) using $_FILES['uploadFile'], but I'm not able to retrieve $_POST['current_path'] data.
I have a theory though. When I load the interface to upload data, the hidden input field 'current_path' is empty (as is hould be). As I navigate through my folders, the hidden input field is updated using jQuery.
When I hit the upload button, the Ajax File Upload plugin takes the data in the upload form and passes the data to uploader.php through $_POST and $_FILES.
But why am I able to get data from $_FILES and not from $_POST?
Here is my code:
Javascript
//File upload functions
// Remove feedback message on upload click
jQuery('.uploadImage').live('click',function() {
ajaxFileUpload();
});
(...)
//Lets upload the file by using Ajax uploader plugin
function ajaxFileUpload() {
alert(jQuery('input[type=hidden][name=current_path]').val()) //Shows me the correct current path
jQuery.ajaxFileUpload ( {
url:'../wp-content/plugins/wp-filebrowser/uploader.php',
secureuri:false,
fileElementId:'uploadFile',
dataType: 'json',
success: function (data) {
if(data.error != '') {
alert(data.error);
} else {
alert(data.respons);
}
},
error: function (e) {
jQuery('#uploadOutput').addClass('error').html('Error: ' + e).show();
},
complete: function() {
// Update file list
}
}
)
return false;
}
HTML
<form id="uploadForm" enctype="multipart/form-data" action="" method="POST">
<input type="hidden" id="current_path" name="current_path" value="<?php echo $fb->relative_url; ?>" />
<input id="uploadFile" name="uploadFile" type="file" />
<input type="button" class="button uploadImage" value="<?php _e('Upload File') ?>" /> <br />
</form>
PHP
$this->current_path = $_POST['current_path'];
$this->data['error'] = $_FILES['uploadFile']['name']; //Just for testing
$this->data['respons'] = "Filename: ".$_POST['current_path'];
echo json_encode($this->data);
But why am I able to get data from $_FILES and not from $_POST?
Because you are not submitting the form, only the file input element.
It seems to be the plugin's behaviour by design:
In this hacked version, it submits the specified file type of input element only rather than an entire form
The jQuery form plugin can do both, maybe that helps.