Git Product home page Git Product logo

form's Introduction

jQuery Form Build Status

Overview

The jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit, gather information from the form element to determine how to manage the submit process. Both of these methods support numerous options which allow you to have full control over how the data is submitted.

No special markup is needed, just a normal form. Submitting a form with AJAX doesn't get any easier than this!

Community

Want to contribute to jQuery Form? Awesome! See CONTRIBUTING for more information.

Code of Conduct

Please note that this project is released with a Contributor Code of Conduct to ensure that this project is a welcoming place for everyone to contribute to. By participating in this project you agree to abide by its terms.

Pull Requests Needed

Enhancements needed to to be fully compatible with jQuery 3

jQuery 3 is removing a lot of features that have been deprecated for a long time. Some of these are still in use by jQuery Form.
Pull requests and assistance in updating jQuery Form to be compatible with jQuery 3 are greatly appreciated.
See issue #544 for more information.

Compatibility

  • Requires jQuery 1.7.2 or later.
  • Compatible with jQuery 2.
  • Partially compatible with jQuery 3.
  • Not compatible with jQuery 3 Slim. (issue #544)

Download

CDN

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.3.0/jquery.form.min.js" integrity="sha384-qlmct0AOBiA2VPZkMY3+2WqkHtIQ9lSdAsAn5RUJD/3vA5MKDgSGcdmIv4ycVxyn" crossorigin="anonymous"></script>

or

<script src="https://cdn.jsdelivr.net/gh/jquery-form/[email protected]/dist/jquery.form.min.js" integrity="sha384-qlmct0AOBiA2VPZkMY3+2WqkHtIQ9lSdAsAn5RUJD/3vA5MKDgSGcdmIv4ycVxyn" crossorigin="anonymous"></script>

API

jqXHR

The jqXHR object is stored in element data-cache with the jqxhr key after each ajaxSubmit call. It can be accessed like this:

var form = $('#myForm').ajaxSubmit({ /* options */ });
var xhr = form.data('jqxhr');

xhr.done(function() {
...
});

ajaxForm( options )

Prepares a form to be submitted via AJAX by adding all of the necessary event listeners. It does not submit the form. Use ajaxForm in your document's ready function to prepare existing forms for AJAX submission, or with the delegation option to handle forms not yet added to the DOM.
Use ajaxForm when you want the plugin to manage all the event binding for you.

// prepare all forms for ajax submission
$('form').ajaxForm({
    target: '#myResultsDiv'
});

ajaxSubmit( options )

Immediately submits the form via AJAX. In the most common use case this is invoked in response to the user clicking a submit button on the form. Use ajaxSubmit if you want to bind your own submit handler to the form.

// bind submit handler to form
$('form').on('submit', function(e) {
    e.preventDefault(); // prevent native submit
    $(this).ajaxSubmit({
        target: '#myResultsDiv'
    })
});

Options

Note: All standard $.ajax options can be used.

beforeSerialize

Callback function invoked before form serialization. Provides an opportunity to manipulate the form before its values are retrieved. Returning false from the callback will prevent the form from being submitted. The callback is invoked with two arguments: the jQuery wrapped form object and the options object.

beforeSerialize: function($form, options) {
    // return false to cancel submit
}

beforeSubmit

Callback function invoked before form submission. Returning false from the callback will prevent the form from being submitted. The callback is invoked with three arguments: the form data in array format, the jQuery wrapped form object, and the options object.

beforeSubmit: function(arr, $form, options) {
    // form data array is an array of objects with name and value properties
    // [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
    // return false to cancel submit
}

beforeFormUnbind

Callback function invoked before form events unbind and bind again. Provides an opportunity to manipulate the form before events will be remounted. The callback is invoked with two arguments: the jQuery wrapped form object and the options object.

beforeFormUnbind: function($form, options) {
    // your callback code
}

filtering

Callback function invoked before processing fields. This provides a way to filter elements.

filtering: function(el, index) {
    if ( !$(el).hasClass('ignore') ) {
        return el;
    }
}

clearForm

Boolean flag indicating whether the form should be cleared if the submit is successful

data

An object containing extra data that should be submitted along with the form.

data: { key1: 'value1', key2: 'value2' }

dataType

Expected data type of the response. One of: null, 'xml', 'script', or 'json'. The dataType option provides a means for specifying how the server response should be handled. This maps directly to jQuery's dataType method. The following values are supported:

  • 'xml': server response is treated as XML and the 'success' callback method, if specified, will be passed the responseXML value
  • 'json': server response will be evaluated and passed to the 'success' callback, if specified
  • 'script': server response is evaluated in the global context

delegation

true to enable support for event delegation requires jQuery v1.7+

// prepare all existing and future forms for ajax submission
$('form').ajaxForm({
    delegation: true
});

error

Deprecated
Callback function to be invoked upon error.

forceSync

Only applicable when explicity using the iframe option or when uploading files on browsers that don't support XHR2. Set to true to remove the short delay before posting form when uploading files. The delay is used to allow the browser to render DOM updates before performing a native form submit. This improves usability when displaying notifications to the user, such as "Please Wait..."

iframe

Boolean flag indicating whether the form should always target the server response to an iframe instead of leveraging XHR when possible.

iframeSrc

String value that should be used for the iframe's src attribute when an iframe is used.

iframeTarget

Identifies the iframe element to be used as the response target for file uploads. By default, the plugin will create a temporary iframe element to capture the response when uploading files. This option allows you to use an existing iframe if you wish. When using this option the plugin will not attempt handling the response from the server.

method

The HTTP method to use for the request (e.g. 'POST', 'GET', 'PUT').

replaceTarget

Optionally used along with the target option. Set to true if the target should be replaced or false if only the target contents should be replaced.

resetForm

Boolean flag indicating whether the form should be reset if the submit is successful

semantic

Boolean flag indicating whether data must be submitted in strict semantic order (slower). Note that the normal form serialization is done in semantic order except for input elements of type="image". You should only set the semantic option to true if your server has strict semantic requirements and your form contains an input element of type="image".

success

Deprecated
Callback function to be invoked after the form has been submitted. If a 'success' callback function is provided it is invoked after the response has been returned from the server. It is passed the following standard jQuery arguments:

  1. data, formatted according to the dataType parameter or the dataFilter callback function, if specified
  2. textStatus, string
  3. jqXHR, object
  4. $form jQuery object containing form element

target

Identifies the element(s) in the page to be updated with the server response. This value may be specified as a jQuery selection string, a jQuery object, or a DOM element.

type

The HTTP method to use for the request (e.g. 'POST', 'GET', 'PUT').
An alias for method option. Overridden by the method value if both are present.

uploadProgress

Callback function to be invoked with upload progress information (if supported by the browser). The callback is passed the following arguments:

  1. event; the browser event
  2. position (integer)
  3. total (integer)
  4. percentComplete (integer)

url

URL to which the form data will be submitted.


Utility Methods

formSerialize

Serializes the form into a query string. This method will return a string in the format: name1=value1&name2=value2

var queryString = $('#myFormId').formSerialize();

fieldSerialize

Serializes field elements into a query string. This is handy when you need to serialize only part of a form. This method will return a string in the format: name1=value1&name2=value2

var queryString = $('#myFormId .specialFields').fieldSerialize();

fieldValue

Returns the value(s) of the element(s) in the matched set in an array. This method always returns an array. If no valid value can be determined the array will be empty, otherwise it will contain one or more values.

resetForm

Resets the form to its original state by invoking the form element's native DOM method.

clearForm

Clears the form elements. This method empties all of the text inputs, password inputs and textarea elements, clears the selection in any select elements, and unchecks all radio and checkbox inputs. It does not clear hidden field values.

clearFields

Clears selected field elements. This is handy when you need to clear only a part of the form.


File Uploads

The Form Plugin supports the use of XMLHttpRequest Level 2 and FormData objects on browsers that support these features. As of today (March 2012) that includes Chrome, Safari, and Firefox. On these browsers (and future Opera and IE10) files uploads will occur seamlessly through the XHR object and progress updates are available as the upload proceeds. For older browsers, a fallback technology is used which involves iframes. More Info


Contributors

This project has transferred from github.com/malsup/form, courtesy of Mike Alsup.
See CONTRIBUTORS for details.

License

This project is dual-licensed under the LGPLv2.1 (or later) or MIT licenses:


Additional documentation and examples for version 3.51- at: http://malsup.com/jquery/form/

form's People

Contributors

andrew-sayers--slando avatar azurebyte avatar breath20 avatar chaoflow avatar cvn avatar cyril-roques avatar dairiki avatar dependabot[bot] avatar doochik avatar ekkis avatar franciscoruiz avatar izziaraffaele avatar jason-cooke avatar jasuca avatar javierjulio avatar jdorfman avatar johnalbin avatar kares avatar kevindb avatar kieran avatar korvinszanto avatar lazyknightx avatar malsup avatar markhalliwell avatar mrdinckleman avatar robloach avatar sineswiper avatar togakangaroo avatar wchristian avatar x3ro avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

form's Issues

Upload brakes on Opera 10 with lates jquery.forms.js.

100 Ms is not enought to opera 10 to understand that post was posted. This fix adds flexible approach to add time on post processing:

                 doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
 
-                if ((doc.body == null || doc.body.innerHTML == '') && !nullCheckFlag) {
+                if ((doc.body == null || doc.body.innerHTML == '') && ($.browser.opera) && (nullCheckFlag < 1000000)) {
                     // in some browsers (cough, Opera 9.2.x) the iframe DOM is not always traversable when
                     // the onload callback fires, so we give them a 2nd chance
-                    nullCheckFlag = 1;
-                    cbInvoked--;
+                    nullCheckFlag++;
+                    cbInvoked = 0;
                     setTimeout(cb, 100);
                     return;
                 }

IFrame to upload files, Safari Error

This seems to work fine in firefox, I get an error in Chrome:

Uncaught TypeError: Cannot call method 'call' of undefined

And an error in Safari it's a bit more detailed:

TypeError: Result of expression '(jQuery(this).data('form-plugin-onload'))' [null] is not a function.

My Form:

<form method="post"  enctype="multipart/form-data" id="add_photo" action="/add_photo/" id="add_photo"><div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='ba7d8cc065e23cd47bdc1b65e5fabac2' /></div>
<table>
    <tr><th><label for="id_title">Caption:</label></th><td><input id="id_title" type="text" name="title" maxlength="255" /></td></tr>
     <tr><th><label for="id_photo">Photo:</label></th><td><input type="file" name="photo" id="id_photo" /><input type="hidden" name="post" value="4" id="id_post" /><input type="hidden" name="owner" value="1" id="id_owner" /><input type="hidden" name="order" value="0" id="id_order" /></td></tr>
   </table>
<input type="submit" name="update" value="Add Picture" />
 </form>

My JS

$("form#add_photo").ajaxForm({
            dataType: 'xml',
            iframe: true,
            beforeSubmit: function(){
                $("form#add_photo").before('<h4 id="loading">Please Wait, Loading</h4>')
            },
            success : function(data,text){
                frick = data
                $("h4#loading").remove()
                $('<li style="background:url('+$(data).find('img:first').attr('src')+') top;display:block;width:300px;height:100px;"><span style="background:rgba(255,255,255,0.7); display:block; height:20%; width:100%"> <input type="radio" name="cover" value=""/><strong>Cover</strong><a href="#move_up">Move Up</a><a href="#move_to_top">Move To Top</a></span></li>').appendTo($('#gallery_sort'));
                $("h3#loading").remove()
            }   
        });

ajaxSubmit doesn't work after hiding ("display:none") the form

On document.ready, bind a form to send ajax submissions with ajaxForm, and then submit it.

After that, using an element of your choice, eg: a button or a link, toggle the visibility of that form so that you can hide it and show it.

Try to submit the form again, the form is not ajax anymore, it behaves like a normal form.

Hi, Opera Bug

Opera 10.63, Form Plugin 2.52, jquery 1.4.4

Uncaught exception: TypeError: 'window['_'+this.id]' is not a function
Error thrown at line 1, column 0 in (event):
window'_'+this.id

.. and don't upload files, response is false

Coordinates for type="image" not being sent

ajaxForm() is supposed to:

  • 1: This method will include coordinates for elements (if the element
  • is used to submit the form).

This isn't working. ajaxForm() calculates the coordinated correctly and puts them in form.clk_x & form.clk_y (which is then deleted on line 413?!). But in either event they are not being injected into the form, so formToArray() doesn't pick them up. Result is they are not passed to the server.

Thanks,
Geoff

p.s. excellent plug-in by the way - most useful :)

jquery.form 2.40 (26-FEB-2010)
jquery 1.4.2

$.fieldValue bug in IE6+ with <select>

When serialising an AJAX form containing a select, I have a bug in the $.fieldValue() method where the selected option is not correctly identified.

The error occurs on line 578 in v 2.43. For some reason, IE6+ can have a select list with a selectedIndex of 0 and not have any options with the op.selected being set to true.

I have made a local patch by changing the line to: if (op.selected || op.index == index), but i'm not sure if this will work in all situations.

I can provide more info if required.

File Upload and XML broken with Opera

Hi Malsup,

Great plugin. I was wondering if you've noticed that Opera does not handle xml return responses like the other browsers? Your examples page is (ironically) a good example:

http://jquery.malsup.com/form/#file-upload

I'm looking through the source now and unfortunately it's out of my depth but if I do find something I will post it here.

Cheers

Chris

xhr.responseText problem

hi,

we recently upgraded to the newest version (from 2.43) and are having some problems at the success function, we output using php json_encode some status messages, etc but with the newest version 2.47 we are not getting anything.

if we go to line 352 and change the following:
xhr.responseText = doc.documentElement ? doc.documentElement.innerHTML : null;

to the way it was before:
xhr.responseText = doc.body ? doc.body.innerHTML : null;

it works without problem so maybe we are doing something wrong.
any help would be greatly appreciated.

warm regards,
sebastian baldovino

Abort of the file uploading

How can one abort the file uploading?
I'm saving the XHR object that comes in beforeSubmit function, but calling .abort() method seems doing nothing (i still get the file and business-logic running on my server)

any thoughts?

Handle error return HTTP status codes?

Hi,

I was wondering if it would be possible to detect a return HTTP return status code upon doing a file upload?

For example, in Rails I may do the following if there was some error during upload:

render :json => @Product, :status => 400

I then don't want the return to go through the "success" handler, but an "error" handler. I see that the xhr.status mock is set to 0, but cannot see how I could pick up the response status code and use that.

Cheers,
Diego

ajaxSubmit with empty form in IE 7/8

Hello,

First thanks for this usefull plugin.

I've got a problem when i try to post empty form in IE 7 and 8, success callback is called but no post is done. (not tested in IE 6)

My example:

<form id="plop" action="myaction" method="POST">
    <button type="submit">Post!!!</button>
</form>

$("#plop button").click(function() {
    $("#plop").ajaxSubmit({
        success : function(data, textStatus, xhr) {
                alert("success");
        }
    });
    return false;
});

Thanks!
Charles

file upload from iframe using firefox 3.6

I have a page which has a form in an iframe. This form is submitted using ajaxSubmit and the JSON response is then processed. This works until I submit a file: as soon as that happens jquery.form correctly adds a new iframe and change the target for the form to point to the new iframe. However when it calls form.submit() the response comes in with an application/json content type which triggers a 'Save As' dialog from firefox and no further processing is done from javascript.

Reporting status_code = 403 in error handler

I just spent a load of time tracking this down, and though it involved multiple screw-ups on my part, jQuery.form could've helped.
I was using the hidden iframe file uploader to upload a file and returning JSON wrapped in textarea's if successful and an empty HTTP response with a status code of 403 if the response failed due to a server-side problem (Django).
Unfortunately, if there is no response content, jQuery.form doesn't catch the response and assumes that the iframe DOM isn't ready yet and queues the callback 99 more times. As a result I never noticed that the server was returning 403's and thought it was a JS or browser fault.
Anyhow, basically the Opera iframe DOM-not-ready hack screws up empty response handling. This is an edge case, but it should be mentioned somewhere or fixed so that the error handler is called.
Thanks!

JSON iframe

When I have some HTML in the JSON object, I get &lt; instead of < and &gt; instead of > and so on.
This modification fixed the problem.:

Line 320:
xhr.responseText = pre.textContent;

There is innerHTML instead of textContent now. But that returns something like php func htmlspecialchars - chars like < and > are encoded to their entities which is bad.

iframe option vs XMLHttpRequest

whe using the 'iframe' option an xhr mock object it's created. this prevent reusing a valid XMLHttpRequest object in ajax callbacks (ie. complete()).

iframe ajaxSubmit doesn't accept PUT method

in FireFox 3.6 (I didn't test other browsers) code like
.ajaxSubmit({ 'type' : 'PUT', 'dataType': 'json', 'iframe': true); or
.ajaxSubmit({ 'method' : 'PUT', 'dataType': 'json', 'iframe': true); (I tried many variants)
with form method attr set to 'PUT' makes POST request instead of needed PUT.

If an error occurs when using ajaxSubmit and uploading a file, error & completed handlers aren't called.

This is happening because the DOM isn't available in the iframe after checking 100 times. When that happens, the code simply returns out of the 'cb' method without reaching the bottom where the callbacks are called. The consequence of this is that if an error occurs while uploading something, the spinner (or whatever in-progress signal is in use) never stops and the user doesn't know what's going on.

Uncaught TypeError: object is not a function

Using JQuery 1.4.1 and trunk on jquery.form I get this error in Google Chrome (latest)

Uncaught TypeError: object is not a function, and it says line 2, it's presumably on the iFrame.

<form id="srv_upload_image" method="post" enctype="multipart/form-data" action="">
    <input type="files" />
    <input type="submit" class="srv_button insert" id="srv_upload_image_action" value="Upload">
</form>
</div>
<script type="text/javascript">
$(document).ready(function(){
    $("form#srv_upload_image").ajaxForm({
            dataType: 'json',
            iframe: true,
            success : function(data,text,xhr,another){
                if(data.errors.length == 0){
                    $("#srv_image_filePane").append(data.item);
                }
                else {
                    else for (error in data.errors) alert(error);
                }
            }   
    });

Minify

Is there a minified version available? I tried to do the minification myself using a website, but it created errors pertaining to the call to window.console.log in the log() function. Would be really nice to see a minified/packed version.

AJAX File Upload with redirect and script evaluation on firefox 3.6

I'm using this file upload script so users can upload a video to Youtube. The workflow requires that the video be uploaded to youtube's servers, which responds with a redirect to a URL supplied in the form action. The redirect contains the ID of the video, the status of the request, and any user-supplied data necessary. My implementation called for the redirect to return server-generated javascript to modify the page inline to show success or failure.

Basic implementation was:

$('#video_upload_form').ajaxForm({
  iframe: true,
  beforeSubmit: function(a,f,o) {
    o.dataType = 'script'; 
    nexturl = $('#nexturl').fieldValue()[0];
    title = $('#title').fieldValue()[0];
    nexturl = $.param.querystring(nexturl, { "title": title});
    o.url = $.param.querystring(o.url, {"nexturl": nexturl});
        $('#nexturl').remove()
    $('#title').remove()

  }
})

Ignore the url manipulation. I need this to serialize a field into the nexturl string.
This works fine on Chrome/Safari, but the response was empty on Firefox 3.6.

I modified cb() to get the innerHTML if it existed instead of the innerText, which was null.

The implementation code changes to:

function unescapeHTML(html) {
   return $("<div />").html(html).text();
}
$.fn.ajaxSubmit.debug = true;
$('#video_upload_form').ajaxForm({
  iframe: true,
  beforeSubmit: function(a,f,o) {
    o.dataType = 'text'; 
    nexturl = $('#nexturl').fieldValue()[0];
    title = $('#title').fieldValue()[0];
    nexturl = $.param.querystring(nexturl, { "title": title});
    o.url = $.param.querystring(o.url, {"nexturl": nexturl});
    $('#nexturl').remove()
    $('#title').remove()

  },
  success: function(data,response, xhr){
    eval(unescapeHTML(data))
   }
});

The data is being returned as escaped html. Once it's escaped it can be evaluated.

I am pushing some changes i made, but the unescaping and evaluation should be done in the plugin. I don't have the time to fully implement and test this now.

$.httpData and $.handleError removed from 1.5

They have been rolled in to the ajax functionality with the ajax rewrite, therefore $.httpData and $.handleError no longer exist, and this plugin no longer works. temporary workaround is to manually include the functions into the plugin and call them.

Form plugin does not handle redirect response

Google App Engine's blobstore upload handler http://code.google.com/appengine/docs/python/blobstore/overview.html#Complete_Sample_App mandates a redirect response, and it looks like the form plugin doesn't handle this properly, returning 'null' as the response text. I'm guessing this is content of the redirect and not of the document returned by following the redirect.
More detail here - http://stackoverflow.com/questions/3080922/ajaxform-and-app-engine-blobstore

X-Requested-With

Hello.
Why u don't send this header:
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");

It's feature from jquery.
May be u know how correct this???

Thanks.

File upload sends multiple submit button name/value pairs

Using multiple submit buttons to upload files leads to situation where both buttons name/value pairs are submitted to the server, making it impossible to identify which button was clicked.

The problem occurs when using ajaxForm.

See the topic1 for more information and potential patch.

Regards, Bob

Success function not getting called.

I have jQuery 1.4.2 and the latest jQuery form plugin from github. However, my success function is not getting called after the ajax call finishes. The code I have is shown below:

    nextGameFormOptions = {
        beforeSubmit: validateNextGame,
        dataType: "json",
        success: successNextGame
    };

    $("#nextGameForm").ajaxForm(nextGameFormOptions);

    function validateNextGame(formData, jqForm, options) {
        var anum = /(^\d+$)/

        var teamScore = $('#teamScoreNextGame').val();
        var opponentScore = $('#oppScoreNextGame').val();

        //alert (teamScore + " :: " + opponentScore);
        if (teamScore < 0 || opponentScore < 0) {
            flagCustomError("next_game_message", "Scores cannot be negative numbers!");
            return false;
        }
        if (!anum.test(teamScore) || !anum.test(opponentScore)) {
            flagCustomError("next_game_message", "Scores must be numbers!");
            return false;
        }
    }

    function successNextGame(data) {
        alert("SUCCESS");
        if (data.response_code == {{ ResponseCodes.PICKSET_GUESS_CREATED }}) {
            flagCustomSuccess("next_game_message", "Your guess was saved!");
        }
    }

The JSON coming back is { response_code: 204, response_message: 'Guess saved.' }

The beforeSubmit function is called without a problem. If I go back to jQuery 1.3.2 it works fine.

File Upload broken in IE

There seems to be a recent regression with the iframe response handling inIE.

In commit a53241d this code was changed to use textContent instead of innerHTML. This property doesn't exist in IE as far as I can tell, and thus the success handler receives the data as null.

Hi Malsup

Have big Problem on File Upload

When i click upload the picture get uploaded thats ok but my PHP code alert unsuporrtet picture file.

This mean I dont get any Files data

This is my Code

if (isset($_GET["cmdUpload"])) {

                $album_id = (int)$_GET["album"];



                #album meins?

                $query  = "SELECT\n".

                          "  gaa_user_usr_id\n".

                          "FROM\n".

                          "  cif_galery_albums\n".

                          "WHERE\n".

                          "  gaa_id = '".$album_id."'";



                $result = db_query ($query);



                if ($row = mysql_fetch_assoc ($result)) {

                    if ($row["gaa_user_usr_id"] == USER_ID) {

                        if ($_FILES["gai_file"]["error"] == 0) {

                            if ($_FILES["gai_file"]["size"] <= GALERY_IMAGE_MAX_SIZE) {

                                switch ($_FILES["gai_file"]["type"]) {

                                case "image/png":

                                case "image/x-png":

                                    $img = @imagecreatefrompng($_FILES["gai_file"]["tmp_name"]);

                                    break;

                                case "image/gif":

                                    $img = @imagecreatefromgif($_FILES["gai_file"]["tmp_name"]);

                                    break;

                                case "image/jpeg":

                                case "image/pjpeg":

                                    $img = @imagecreatefromjpeg($_FILES["gai_file"]["tmp_name"]);

                                    break;

                                }





                                if ($img) {

                                    #verzeichnisse prüfen

                                    if (!(is_dir(MEDIAPATH."galery/".USER_ID."/large"))) {

                                        mkdir(MEDIAPATH."galery/".USER_ID);

                                        chmod(MEDIAPATH."galery/".USER_ID, 0777);



                                        mkdir(MEDIAPATH."galery/".USER_ID."/large");

                                        chmod(MEDIAPATH."galery/".USER_ID."/large", 0777);



                                        mkdir(MEDIAPATH."galery/".USER_ID."/small");

                                        chmod(MEDIAPATH."galery/".USER_ID."/small", 0777);

                                    }





                                    $img_w = imagesx ($img);

                                    $img_h = imagesy ($img);

                                    $img_ratio = $img_w / $img_h;

                                    $filename = USER_ID."_".md5($_FILES["usr_picture"]["name"].time()).".jpg";



                                    if (($img_w < GALERY_PIC_MIN_W) || ($img_h < GALERY_PIC_MIN_H)) {

                                        alert ("Das Profilbild ist zu klein. Es muss mindestens ".GALERY_PIC_MIN_W." Pixel breit und ".GALERY_PIC_MIN_H." Pixel hoch sein!", "error");

                                    } else {

                                        #large-bild

                                        if (($img_w > GALERY_PIC_MAX_W) || ($img_h > GALERY_PIC_MAX_H)) {

                                            #bild zu groß -> verkleinern!



                                            if (GALERY_PIC_MAX_H * $img_ratio > GALERY_PIC_MAX_W) { #neue errechnete breite wäre größer als erlaubt

                                                $new_w = GALERY_PIC_MAX_W;

                                                $new_h = GALERY_PIC_MAX_W / $img_ratio;

                                            } else {

                                                $new_w = GALERY_PIC_MAX_H * $img_ratio;

                                                $new_h = GALERY_PIC_MAX_H;

                                            }



                                            if (GALERY_PIC_MAX_W / $img_ratio < GALERY_PIC_MAX_H) { #neue errechnete breite wäre größer als erlaubt

                                                $new_w = GALERY_PIC_MAX_W;

                                                $new_h = GALERY_PIC_MAX_W / $img_ratio;

                                            } else {

                                                $new_w = GALERY_PIC_MAX_H * $img_ratio;

                                                $new_h = GALERY_PIC_MAX_H;

                                            }



                                            $img_tmp = imagecreatetruecolor ($new_w, $new_h);

                                            imagecopyresampled($img_tmp, $img, 0, 0, 0, 0, $new_w, $new_h, $img_w, $img_h);

                                        } else {

                                            $img_tmp = $img;

                                        }



                                        #wasserzeichen reinrechnen

                                        $img_tmp = img_add_watermark ($img_tmp);

                                        imagejpeg($img_tmp, MEDIAPATH."galery/".USER_ID."/large/".$filename);



                                        #kleines profilbild (small)

                                        if ($img_ratio >= 1) {  #bild ist breiter als hoch oder genauso breit wie hoch

                                            $new_w = SMALL_PIC_MAX_W;

                                            $new_h = SMALL_PIC_MAX_W / $img_ratio;

                                        } else {

                                            $new_w = SMALL_PIC_MAX_H * $img_ratio;

                                            $new_h = SMALL_PIC_MAX_H;

                                        }



                                        $img_tmp = imagecreatetruecolor ($new_w, $new_h);

                                        imagecopyresampled($img_tmp, $img, 0, 0, 0, 0, $new_w, $new_h, $img_w, $img_h);

                                        imagejpeg($img_tmp, MEDIAPATH."galery/".USER_ID."/small/".$filename);



                                        #belegte größe berechnen

                                        $size = filesize (MEDIAPATH."galery/".USER_ID."/small/".$filename) + filesize (MEDIAPATH."galery/".USER_ID."/large/".$filename);



                                        #in db speichern

                                        $query_data = array(

                                                            "gai_user_usr_id"   => USER_ID,

                                                            "gai_album_gaa_id"  => $album_id,

                                                            "gai_file"          => $filename,

                                                            "gai_title"         => converte($_GET["gai_title"]),

                                                            "gai_description"   => converte($_GET["gai_description"]),

                                                            "gai_size"          => $size,

                                                            "gai_uploaded"      => time()

                                                            );

                                        $query = build_insert_query ("cif_galery_images", $query_data);

                                        db_query ($query);



                                        alert ("Das Bild wurde hochgeladen", "success");

                                    }



                                } else {

                                    alert ("Ung&uuml;ltiges Bild, erlaubt sind JPG, PNG und GIF!", "error");

                                }

                            } else {

                                alert ("Die Datei ist gr&ouml;&szlig;er als die erlaubten ".get_readable_filesize(GALERY_IMAGE_MAX_SIZE), "error");

                            }

                        }

                    }

                }

            }

Passing a class selector does not work as expected.

Sorry if I'm missing something obvious here, or if I'm doing something that just shouldn't work period, but I've searched around to no avail, and what I'm trying to do seems like a pretty obvious use case.

Say we have multiple forms on a page that we want to be able to turn into ajaxForms. Something like this:

<form method="post" action="/foo/bar" class="ajaxform">
  ...
</form>
<form method="post" action="/foo/quux" class="ajaxform">
  ...
</form>

I expected the following to work:

$(document).ready(function() { 
  $('.ajaxform').ajaxForm({...});
});

It does not.

$('body').ajaxSuccess not being triggered.

I have a gobal handler for ajax calls and it seems the event isn't being triggered when I use ajaxSubmit()?

$('body').ajaxSuccess(function(){ alert('ajax called was successful'); });

Fix file upload issues with Opera

Despite changes that should fix Opera issues, 2.36 doesn't work correctly for me in Opera.
I tested 9.27, 9.52, 9.64 and 10.00 under Ubuntu, upload is always interrupted early.
When searching for Opera iframe onload issues, I found note
in http://developer.yahoo.com/yui/releasenotes/README.connection and
that 2.5.2 issue description gave me idea how to fix this bug:
attach onload handler after iframe is inserted into DOM!

After applying following patch, form plugin works flawlessly under Opera (9.27, 9.52, 9.64, 10.00), I also tested (without problems) IE6,7,8 and Fx2,Fx3.

diff --git a/public/javascripts/jquery.form.js b/public/javascripts/jquery.form.js
--- a/public/javascripts/jquery.form.js
+++ b/public/javascripts/jquery.form.js
@@ -261,7 +261,9 @@ $.fn.ajaxSubmit = function(options) {

                                // add iframe to doc and submit the form
                                $io.appendTo('body');
+                               setTimeout(function() {
                                io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
+                               }, 1);
                                form.submit();
                        }
                        finally {

IE8 issue with ajaxForm type GET sending as POST

We are using ajaxForm 1.49 with jQuery 1.3.2 and seeing only in IE8 that it is ignoring the GET declared in the form tag and submitting as a POST. Also tried setting type: 'GET' in the options hash without success. It correctly does the GET in Firefox and Chrome.

Suggested enhancement - how identify AJAX submission?

To avoid duplicating code, I use the same script to process form submissions whether it is via ajax or not (e.g. if user has JS disabled). It is necessary in this case to separate ajax posts so that only the relevant sub-page can be sent back to the browser. I normally inject a form field prior to the ajax submission to do this. I could pick up the form object in a pre-submission callback but it may be easier to simply mod the plug-in - perhaps a small enhancement: e.g. insert before L473:
a.push({name: 'jqueryForm', value: 'true'});

This will add an input field which I can then detect in the server script and adjust the processing accordingly.
Thx,
Geoff

IE7 "helpfully" converts PUT/DELETE into "get" --with fix

IE7 converts the method attribute in the dom to "get" if it is not a GET or POST. Unforuntately, this means that $(form).attr('method') returns the screwed up, modified version. PUTs and DELETEs do work just fine in IE7 when submitted via the XMLHttpRequest object.
Fix (against version 2.52) is to ask for the 'method' attribute on the original DOM element, not the jQuery copy of a modified version:

~line 170 add this just before the call to $.ajax(options)

if ($form.attr('method') == 'get') { options.type = $form.get(0).getAttribute('method'); }

File upload on firefox with application/json response

When using ajaxForm over a file upload form that get back an application/json response from the server, FF is giving a file download dialog and 'success' event isn't called. It works ok on chrome and safari.

I can fix the problem changing content-type to text/plain for json responses. But it doesn't look like the right direction. I'm missing something?, is this something that should be fixed on FF and nothing can be done here?

Googling a bit tells me I'm not the only one having this issue: http://stackoverflow.com/questions/2755802/jquery-ajaxform-returning-json-file

Form doesn't submit in Firefox 3.5.7 when in iframe

This issue may exist in other versions of Firefox, but it specifically exists in 3.5.7. If the form being submitted is within an iframe, then the form never submits because the setTimeout callback is never called. I have no idea why, it just doesn't seem to work when setTimeout is called within an iframe.

Removing the setTimeout call which wraps the actual form submission resolves the issue, but this seems to be more of a temporary fix than a permanent one.

Do not download multiple files in the opera 11

Do not download multiple files in the opera 11.
If you download a file then everything is fine, but if you set multiple = "multiple" and try to download more files do not download anything

P.S. Thanks, great plugin!:)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.