Jake
Jake

Reputation: 507

Ajax Request With jQuery Mobile Without Page Refresh

I am submitting a simple form via Ajax POST and getting back a JSON response, and using that response to populate the data into a custom-built audio player with a slider.

The audio player slider functions work before the Ajax POST. However, after I submit my form, it appears that jQuery Mobile is refreshing the page, and after that refresh, the slider is broken.

The error message I get is: "Error: cannot call methods on slider prior to initialization; attempted to call method 'refresh'"

My form code looks like:

<form name="test" method="post">
    <input type="hidden" name="action" value="test.php">
    <input type="number" name="id" />
    <button data-icon="star" onclick="onFormSumbit();">Submit</button>
</form>

And my submit function looks like:

function onFormSumbit() {
    $.ajax({
        type: $('form').attr('method'),
        url: $('form input[name=action]').attr('value'),
        data: $('form').serialize(),
        dataType: 'json',
        success: function(response, textStatus, XMLHttpRequest) {
            if (response.error) {
                console.log('ERROR: ' + response.error);                
            } else {
                mediaSource = response.url;                 
                console.log('URL: ' + response.url);
                console.log('ARTIST: ' + response.artist);
                console.log('TITLE: ' + response.title);
            }
        }
    });
}

My slider coded looks like:

<input type="range" id="slider" value="0" min="0" max="100" step="0.01" data-highlight="true" />

And my slider function looks like:

playSlider.on('slidestop', function(event,ui) {
    mediaObject.seekTo((playSlider.val() / 100) * mediaDuration * 1000);
    console.log(playSlider.val());
});

Upvotes: 1

Views: 4095

Answers (1)

Apostolos Emmanouilidis
Apostolos Emmanouilidis

Reputation: 7197

I modified your code as following and the page is not refreshing:

$(document).on('submit', '#myForm', function(e) {
    e.preventDefault();
    postForm();
});

function postForm()
{
    $.ajax({
        type: $('form').attr('method'),
        url: $('form input[name=action]').attr('value'),
        data: $('form').serialize(),
        dataType: 'json',
        async: true,
        success: function(data) {
            mediaSource = response.url;                
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert("Error: " + xhr.status + "\n" +
                   "Message: " + xhr.statusText + "\n" +
                   "Response: " + xhr.responseText + "\n" + thrownError);
        }
    });
}

<form name="test" id="myForm" method="post">
   <input type="hidden" name="action" value="test.php">
   <input type="number" name="id"/>
   <input type="submit" data-icon="star" value="Submit">
</form>

Upvotes: 5

Related Questions