Jump to content

Recommended Posts

Posted

Attached is a function and form I created that will take any form with the attribute of data-async and deliver it's request to the server to process asynchronously.

 

If at first the function fails it will retry the request denoted by the try limit.

 

However I still get an XHR error on occasion (not every time) even though I know the data is there and nothing else is in que. Are there any ideas for improvement? I am rather new to ajax and am still in the process of learning. Hopefully somebody can point me in the right direction.

 

Here is the Jquery function:

 

$('body').on('submit', 'form[data-async]', function(event) {

var $form = $(this);

var $target = $($form.attr('data-target'));

 

event.preventDefault();

 

$.ajax({

type: $form.attr('method'),

url: $form.attr('action'),

data: $form.serialize(),

dataType: 'json',

tryCount : 0,

retryLimit : 5,

success: function($val) {

 

$($target).html('<div id="response" class="alert alert-'+$val.response.type+' no-margin text-center">'+$val.response.message+'</div>');

if($val.response.action)

{

window.location.href = $val.response.action;

}

if($val.response.function)

{

eval($val.response.function+"()");

}

},

error : function(xhr, textStatus, errorThrown ) {

if (textStatus == 'timeout') {

this.tryCount++;

if (this.tryCount <= this.retryLimit) {

//try again

$.ajax(this);

return;

}

return;

}

if (xhr.status == 500) {

//handle error

alert('error 500 '+xhr.status);

} else {

//handle error

alert('error '+xhr.status);

}

}

});

});

 

Here is an example form:

 

<form data-async data-target="#menu-update-response" action="<?php echo $_SESSION['uri']; ?>api/json/?component=person&type=create_alias" method="POST" >

<hr>

<div>

<label for="first">First Name:</label>

<div class="input">

<input tabindex="1" size="" id="first" name="first" type="text" value="" placeholder="">

</div>

</div>

<div>

<label for="middle">Middle Name:</label>

<div class="input">

<input tabindex="1" size="" id="middle" name="middle" type="text" value="" placeholder="">

</div>

</div>

<div>

<label for="last">Last Name:</label>

<div class="input">

<input tabindex="1" size="" id="last" name="last" type="text" value="" placeholder="">

</div>

</div>

<button class="btn btn-success">Create</button>

</form>

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...