jquery submit form and then show results in an existing div

I have a simple one text input form that when submitted, needs to fetch a php file (passing the inputs to the file) and then take the result (just a line of text) and place it in a div and fade that div into view.

Here is what I have now:

<form id=create method=POST action=create.php>
<input type=text name=url>
<input type="submit" value="Create" /> 

<div id=created></div>

What I need is the results of create.php?url=INPUT, to be dynamically loaded into the div called created.

I have the jquery form script, but I haven't been able to get it to work right. But I do have the library loaded (the file).


Solution 1:

This code should do it. You don't need the Form plugin for something as simple as this:

$('#create').submit(function() { // catch the form's submit event
    $.ajax({ // create an AJAX call...
        data: $(this).serialize(), // get the form data
        type: $(this).attr('method'), // GET or POST
        url: $(this).attr('action'), // the file to call
        success: function(response) { // on success..
            $('#created').html(response); // update the DIV
        }
    });
    return false; // cancel original event to prevent form submitting
});

Solution 2:

This works also for file upload

$(document).on("submit", "form", function(event)
{
    event.preventDefault();

    var url=$(this).attr("action");
    $.ajax({
        url: url,
        type: 'POST',
        dataType: "JSON",
        data: new FormData(this),
        processData: false,
        contentType: false,
        success: function (data, status)
        {
            $('#created').html(data); //content loads here

        },
        error: function (xhr, desc, err)
        {
            console.log("error");

        }
    });        

});

Solution 3:

You must use AJAX to post the form if you don't want the page to be refreshed.

$('#create').submit(function () {
    $.post('create.php', $('#create').serialize(), function (data, textStatus) {
         $('#created').append(data);
    });
    return false;
});