I'm trying to integrate a progress bar available at http://malsup.com/jquery/form/progress.html into a php upload form. It works well except it returns duplicate upload form on the same page after submitting the first form. See the screen shots of form below.
Form Screen Shot
The ajax call is following:
<script type="text/javascript">
(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('#Myform').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
success: function() {
var percentVal = '100%';
bar.width(percentVal)
percent.html(percentVal);
},
complete: function(xhr) {
status.html(xhr.responseText);
}
});
})();
html part can be represented as:
<form id="#Myform" action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" enctype="multipart/form-data">
<input type="file" name="DocFile"/>
<input type="submit" id="upload" value="Upload"/>
</form>
<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
<div id="status"></div>
I store form validation messages in PHP array and output these to a predefined div in my upload script.
xhr.responseTextoutputs the PHP validation messages in #status div but it causes the appearance of duplicate form as per the attached screen shot.
Any idea whats going wrong here?
Your PHP-Function is (based on action="<?php echo $_SERVER["PHP_SELF"]; ?>") on the same page as your other html (also your upload form amongst other). The AJAX-Functionality basically just loads the linked file with the form parameters and uses the whole content after the PHP execution as the result. In you case, the content includes your response but also your form.
Now how to solve this problem? The easiest way would be, to define your PHP in another file and link to that. For that, add action="upload.php" to your <form>-Tag. Then create a new PHP-File:
upload.php
if(isset($_POST)) {
...
echo "47";
}
Related
var log = document.getElementById("log");
$(function(){
$('textarea').keypress(function(e) {
if (e.keyCode == 13 && !e.shiftKey) {
log.innerHTML += "Company<br>";
e.preventDefault();
var frm = this.form; // don't submit the form yet
log.innerHTML += "<br>";
$.ajax({
url: $(frm).attr('action'), // remember to specify which attribute you want
data: $(frm).serialize(),
dataType: "json",
success: function() {
log.innerHTML += "Ajax complete (form should be submitted now)<br>";
// submit the form when the ajax request is complete
// frm.submit();
}
});
}
});
});
<form action="#">
<textarea name="comment"></textarea>
</form>
<div id="log"></div>
I am trying to set up the script to where I can display the results within the input. Is there a way to display the results whatever the user puts in the textarea below?
log.innerHTML += "Company<br>";
.innerHTML seems to be acting like a basic paragraph of text. All I need is to be able to display a list of links that are going to be put in the input to save them. Is there a way I can use .text() for the textarea?
Any help is appreciated, thank you!
HTML:
<form action="#">
<textarea name="comment"></textarea>
</form>
<div id="log"></div>
JS:
$('textarea').on('focusout', function(){
$('#log').text($(this).val());
});
use $("#log").text("").append($("textarea").val());
Im going to be submitting url links within the form and each link has to be on a different line. It looks weird with all of them jamd together. Sorry lol
I have one form and in that form i have input type file to upload zip files i upload zip file using that form and than it goes to zip extract php file but i want to show loader till the file extract.How can i do using php or jquery?
<form enctype="multipart/form-data" method="post" action="zip_upload.php">
<label>Upload Zip File: </label> <input type="file" name="zip_file">
<input type="submit" name="submit" value="Upload" class="upload" id="submitzip"> <br><br>
</form>
Showing a percentage based progress bar is tricky work. You're much better off displaying a loading status or a spinning icon if your knowledge on this subject is limited.
Not the prettiest of methods but has worked wonders for me and many others in the past.
CSS:
#uploadFrame {
height:1px;
width:1px;
visibility:hidden;
}
HTML:
// hide this on your page somewhere. It's only 1x1 pixels, so should be simple.
<iframe src="zip_upload.php" name="uploadFrame" id="uploadFrame"></iframe>
// your upload form
<form enctype="multipart/form-data" method="post" action="zip_upload.php" target="uploadFrame">
// form content
</form>
jQuery:
$(form).submit(function() {
$('#loading-spinner').show();
});
$("#uploadFrame").load(function() {
$('#loading-spinner').hide();
});
When the form is submitted, a loading icon is displayed, and when the upload and extraction process has finished (iFrame loaded), the loading icon disappears. This all happens without reloading the page.
The bonus of using this is, if modified slightly (convert jQuery to Javascript) you don't need any external libraries or plugins to use it. Also, it is very simple and understandable.
ANOTHER OPTION --------------------------------------------
A bit more advanced and inclusion of jQuery library & a plugin is required, but has the percentage feature.
Check out http://malsup.com/jquery/form/#file-upload for documentation and full spec and here for demo: http://malsup.com/jquery/form/progress.html.
Here is the code:
<form action="zip-upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="zip_file">
<input type="submit" value="Upload">
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
success: function() {
var percentVal = '100%';
bar.width(percentVal)
percent.html(percentVal);
},
complete: function(xhr) {
status.html(xhr.responseText);
}
});
})();
</script>
And on your PHP page:
<?php
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['zip_file']['name']);
if(move_uploaded_file($_FILES['zip_file']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['zip_file']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
You can use jQuery UI. Here you can check it http://jqueryui.com/progressbar/#default
I know this has been asked some time, but the solutions before did not help, and I do not understand if I am missing something
I have simple php/hmtl page with an index.php where I include the different content php pages with a simple GET check:
if (isset($_GET['section'], $section[$_GET['section']])) {
include $section[$_GET['section']];
} else {
include $section['home'];
}
Now one of these sections contains a form which I want to do some magical ajax/jquery action with.
In my javascript file which is loaded at the bottom of the index.php I have following jquery ajax stuff
//ajax load domain search script
$(document).ready(function(){
$('#lookup_domain').live("click", function(e) {
e.preventDefault();
searchVal = $('#domain').val();
topLevel = $('.custom_select').val();
domain = searchVal + '.' + topLevel;
$.ajax({
type: 'GET',
url: 'script_domain.php',
data: 'domain=' + domain,
dataType: 'html',
beforeSend: function() {
$('#result').html('<img style="margin-left: 80px;margin-top: 30px;" src="_assets/img/loader.gif" alt="loading..." />');
if (!searchVal[0]) {
$('#result').html('<p>Syötä domain nimi.</p>');
return false;
}
},
success: function(response) {
$('#result').html(response);
},
error: function(response) {
$('#result').html('<p>Haussa virheitä.</p>');
}
});
});
});
I thought it would be enough to use
$(document).ready(function(){
and the live method (i have jquery 1.7.1 so live should be working?)
$('#lookup_domain').live("click", function() {
but unfortunatedly this is not working, the form just sends it to itself and loads the page again.
Here is the form:
<?php
if(!defined('indexcalled')){die('Direct access not premitted');}
?>
<div id="domain_search">
<h5>hae verkkotunnusta</h5>
<form action="#" method="get" class="domain_form">
<input type="text" name="domain" class="domain_input" />
<div class="select_wrap">
<select class="custom_select">
<option value="fi">.FI</option>
<option value="com">.COM</option>
<option value="net">.NET</option>
<option value="me">.ME</option>
<option value="info">.INFO</option>
</select>
</div><!--/select wrap-->
<input type="submit" value="Syötä" class="domain_submit_btn" id="lookup_domain"/>
</form>
<div class="clear"></div>
</div><!--/domain search-->
What am I missing here? Is there any good documentation about how to use jquery with this kind of dynamical page setup?
EDIT
My original question was, how to handle these kind of elements properly with jquery, because they are included later on.
I found that I should be working with on() instead of live because its deprecated in 1.7 too. So I edited the code like this:
$(document.body).on("click", '#lookup_domain', function(e){
e.preventDefault();
$(document.body).on("click", '#domain', function(event){
alert($(this).text());
});
But the alert does not work, it does nothing. What am I missing here?
You're calling e.preventDefault(), which should keep the form from submitting, however you are not passing the event object into your click handler. Update it to this and it should work:
$('#lookup_domain').live("click", function(e) {
e.preventDefault();
...
});
Because you are using a submit button for your live click you need to disable the form submission.
There are two solutions:
1, Return false on the click event:
$('#lookup_domain').live("click", function() {
// all of your code
return false;
})
2, add an onsubmit attribute to your form:
<form action="#" method="get" class="domain_form" onsubmit="return false;">
</form>
Thanks for all guys who helped me in the chat, the correct method is to first have the document ready, then use .on() with click method with body to access the element created afterwards. Then just with normal .val() to get the values, like this:
$(document).ready(function(){
$(document.body).on("click", '#lookup_domain', function(e){
e.preventDefault();
searchVal = $('#domain').val();
I'm pretty sure it has to do with my core.js file with the ajax hashing url. But I'm trying to submit a form, but it's not submitting like I want it to. This is the core.js file:
// call init
$(init);
function init() {
ajax_page_handler();
page_load($(window.location).attr("hash")); // goto first page if #! is available
}
function page_load($href) {
if($href != undefined && $href.substring(0, 2) == '#/') {
// replace body the #content with loaded html
$('#content').load($href.substring(2), function () {
$('#content').hide().fadeIn('slow');
});
}
}
function ajax_page_handler() {
$(window).bind('hashchange', function () {
$href = $(window.location).attr("hash");
page_load($href);
});
// this allow you to reload by clicking the same link
$('a[href^="#/"]').live('click', function() {
$curhref = $(window.location).attr("hash");
$href = $(this).attr('href');
if($curhref == $href) {
page_load($href);
}
});
}
The live viewing is over at www.krissales.com. The form is here: http://www.krissales.com/#/media/5.Testing-1
Hit the link "Post Comment", then you'll type info in, then hit comment, but it just refreshes, but doesn't submit it.
The steps I've taken to solve it was in the comment file, in the form action field, I inserted the tag name="#content" simply because that's the name of my div that I'm submitting to.
The original stuff is on http://blog.krissales.com/article/7.Testing-3-man ( where you can actually post a comment, and it'll work)
But apparently it's not working. Do you guys have a clue as to what it is that I'm doing wrong? thanks for your help in advance!
<script type="text/javascript">
tinyMCE.init({
mode : "textareas",
theme : "simple"
});
</script>
<form action="#/media/article.php" name="#content" method="POST">
Name:
<br />
<input type="text" name="name" class="userpass"/>
<br /><br />
Comment:
<br />
<textarea id="elm1" name="comment" rows="7" cols="30" style="width: 500px;">
</textarea>
<br />
<input type="submit" name="submit" value="Comment" class="button" />
<input type="reset" name="submit" value="Reset" class="button" />
</form>
I noticed that you are not setting the ajax type on the file 'comment.php'.
you need...
$.ajax({
type: 'POST',
url: 'comment_ajax.php',
data: { form_name: name, form_comment: comment },
success: function(data) {
$('#new_comment').prepend(data);
// close modal box
// do other shit
// kthnxbai
}
});
If type is not specified, it defaults to a GET request which will not post data. :)
Your current core.js handles changes in the URL hash, and it reroutes any links with a hash to load that relative path into #content. What's missing is code to redirect form submits to do the same thing (add this to ajax_page_handler):
$('form').live('submit', function(e) {
var $action = $(this).attr('action');
if($action.substring(0, 2) == '#/') {
// replace the #content with result of the form post
$.ajax({
url: $action.substring(2),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function(data) {
$('#content').html(data);
$('#content').hide().fadeIn('slow');
}
});
// stop the real form submit from happening
e.preventDefault();
}
});
You should change the action attribute of your form like this :
<form action="script-handling-comment-data.php#/media/article.php" name="#content" method="POST">
For the moment, you're sending the comment data to http://www.krissales.com/ and i think the main page doesn't handle the comment posting.
You seem to be handling links properly, but form submission isn't a link, you probably want to handle submission using $(form).submit(function(){ ... })
In your case, if you gave your form the id form1
$('#form1').submit(function(){
var keyValues = $(this).serializeArray();
var map = {};
for(i in keyValues)
{
var value = keyValues.value;
var name = keyValues.name;
map[name] = value;
}
$.post($(this).attr('action'),map,function(){
alert("Submitted values: " + $(this).serialize());
});
return false;
})
See serializeArray, $.post and .submit for more information
I am having some trouble with my file upload script. The HTML is as follows:
<form method="post" name="imgsubmit" id="contact_form" action="PHP/imgupload.php" enctype="multipart/form-data">
<label id="namelabel" for="username">Your name:</label><input id="username" type="text" name="username" rel="req">
<label id="labelemail" for="imgemail">E-mail:</label><input id="imgemail" type="email" name="imgemail" rel="req">
<label id="filelabel" for="file">Your photo:</label><input id="file" type="file" name="file">
<input id="imgsubmit" type="submit" name="submit" value="SUBMIT"></form>
I have a jquery validation script as which checks the username and email fields to see if they are valid, and returns a white border around them if they are not entered:
$(function () {
$('#contact_form').submit(function (e) {
e.preventDefault();
var form = $('#contact_form');
var post_url = form.attr('action');
var post_data = form.serialize();
var submit_form = false;
var req_fields = $('input[rel=req]');
var field, pcount = 0;
req_fields.each(function () {
field = $(this).val();
if (field == '' || field == 'Required') {
$(this).css('border', '1px solid white').val('');
pcount += 1;
} else {}
});
if (pcount == 0) {
submit_form = true;
}
if (submit_form) {
$.ajax({
type: 'POST',
url: post_url,
data: post_data,
success: function (msg) {
$(form).fadeOut;
form.html(msg).fadeIn();
}
});
}
});
});
The problem is that the username gets submitted to the php script, the email gets submitted to the php script, but the image doesn't get uploaded. I'm aware that AJAX now supports image uploading and that the form.serialize() is likely the root cause of the problem, but have not been able to edit this code correctly to support the image submission.
How can I adjust this code to include the image to be submitted to the php?
`if (window.FormData)`
check this and file must be `
file = $('#elemet').files.
and ajax option should be data: FormData,
where formdata = new FormData();
I like to use the jQuery Form Plugin for this kind of stuff, you just need to bind your form submittal when the DOM is ready for it to work. The example bellow is providing a success callback, but there are other events you could use, like error, beforeSubmit, and so forth:
$('#contact_form').ajaxForm(function() {
alert("Thank you for your data!");
});
It supports both regular input values and also file uploads (in older browsers it will fake an ajax file upload using iframes), and if your browser can handle it you can even display a progress bar.