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";
}
Related
I have a PHP page (page.php) that I am using to post data into my database. I am using the form method post to send the data to my database. Inside the <form> I have a second <form> which I use to upload an image.
But when I click on Upload the outer <form> will posted: action="./submit.php".
Does someone know how I can fix this?
Here is my script:
page.php
<form name="reaction" method="post" action="./submit.php">
//multiple textboxes
//upload script
<form name="newad" method="post" enctype="multipart/form-data" action="page.php">
<table style="width:100%">
<tr><td><input type="file" name="image" value="Choose file"></td></tr>
<tr><td><br /><input name="Submit" class="btn2" type="submit" value="Upload"></td></tr>
</table>
</form>
<button type="submit">Post page</button>
</form>
well Ryan is right, you can't have a <form> inside a <form> my suggestion is change the html stucture or make it into one <form> with one action and maybe you can split the function inside submit.php
You can't have nested form like this in HTML.Follow this instruction to better undrestanding about form handling in PHP.
You can use two submit buttons in one form, they can each have a different formaction to specify where to submit.
<form name="reaction" method="post" enctype="multipart/form-data">
//multiple textboxes
//upload script
<table style="width:100%">
<tr><td><input type="file" name="image" value="Choose file"></td></tr>
<tr><td><br /><input name="Submit" class="btn2" type="submit" value="Upload" formaction="page.php"></td></tr>
</table>
<button type="submit" formaction="submit.php">Post page</button>
</form>
Both buttons will submit all the form fields, but the two scripts can simply ignore the fields that they don't care about.
Recommendations:
Step 1: separate each form
Step 2: give each form an id
Step 3: use jquery's $.ajax() to publish the forms to their respective targets URLs
Example of Ajax call:
$("#ajaxform").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
//data: return data from server
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
Code from hog I was lazy to write one
After following the example and answers by the following threads
jQuery AJAX submit form
submitting a form via AJAX
I have built a similar test form to get to learn the ajax request on submit. Your guess was right, it doesn't work for me (no alert popping up).
My testajax.php with the form:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="../test.js"></script>
<form name="feedback" id="idForm" action="(myurl)/testajax.php" method="post">
<input id="name" type="text">
<input type="submit" name="feedbacksent" value="Send" />
</p>
</form>
My test.js:
// this is the id of the form
$("#idForm").submit(function(e) {
var url = "(myurl)/testajaxinput.php"; // the script where you handle the form input.
e.preventDefault(); // avoid to execute the actual submit of the form.
alert("bla"); // does not work either
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
My testajaxinput.php that should handle the input:
if (isset($_POST['feedbacksent'])){
echo "<h1>".WORKS."</h1>";
}
Try this :
if (isset($_POST['feedbacksent'])){
echo "<h1>".WORKS."</h1>";
return true;
}
Then try your alert and also check have you got any error in console.
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;">
<?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/
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'; ";