Question

I have a form with a text box and a submit button.

<div style="float:left; padding:20px;">
<form id="crate_input" method="get">
    Create new crate: <input type="text" id="create">
    <input id="subbutton" type="submit" value="Submit">
</form>
<select id="crates">
    <option id="choose" value="choose" selected>Choose a crate</option>
    <option id="default_crate" value="default_crate">default_crate</option>
</select>
</div>

User interactions are handled in a separate java script file.

$('#subbutton').click(function(event) {
    $.ajax({
        url: OC.linkTo('crate_it', 'ajax/bagit_handler.php'),
        type: 'get',
        dataType: 'text/html',
        data: {'action':'create', 'crate_name':$('#crate_input #create').val()},
        success: function(data){
            $('#crates option').filter(function(){
            return $(this).attr("id") == data.responseText;
        }).prop('selected', true);
    }
    });
});

But the problem is when I type a name for a crate and press submit button, it sometimes doesn't create the crate. It seemed to refresh the page, but new crate hasn't been created. Does anyone know what's wrong here?

Was it helpful?

Solution

What's wrong is you're not stopping the default form submission.

$('#crate_input').submit(function(){ return false; });

should resolve your issues.

OTHER TIPS

You don't prevent the normal submission of the form, therefore the page is reloaded before the ajax call comes back:

$('#subbutton').click(function(event) {
    $.ajax({
      ...
    });
    return false;
});

Also, return from ajax success handler is meaningless, because
1. - it is executed well after button click finished;
2. - code that calls this handler does not expect any returned value.

Without knowing about the response of 'ajax/bagit_handler.php', it would be difficult to answer this question. However I notice the following

  1. You seem to create a crate on the server but you are using HTTP GET. It is not advisable to use GET for operations that affect the state of the server.

  2. The response data type is given as text/html. And the response HTML is compared with $(this).attr(id) of which I dont understand anything. this at that context refers to the AJAX handler. I am not sure what exactly you are trying to do.

  3. It is better to do the form processing on $('crate_input').submit() instead of $('#subbutton').click().

If possible, please add a jsfiddle to illustrate what you were doing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top