AJAX advice
Posted: Sat Dec 06, 2008 11:05 am
I've never been an AJAX guru. I've added a few AJAX features to a few of my apps but I've never written an "ajax app". What is the usual process to take a regular form, submit it via AJAX, accept the response, and update the page with the results? For instance, I'm creating a page that allows you to post little snippets, which it will accept and then insert into "todays entries" below.
Right now, I override the form's submit event, submit data to an ajax action, accept the result, build the entry html, and insert into the HTML node into the DOM below "todays entries". I see two issues with this:
1) The HTML is generated by javascript instead of by the view script I use in PHP, and therefor violates DRY
2) If it's the first entry, there is no "today's entries" to insert it below, so it fudges up.
So, how can I fix this? How do I use PHP to render the entry instead of javascript?
My Javascript:
Right now, I override the form's submit event, submit data to an ajax action, accept the result, build the entry html, and insert into the HTML node into the DOM below "todays entries". I see two issues with this:
1) The HTML is generated by javascript instead of by the view script I use in PHP, and therefor violates DRY
2) If it's the first entry, there is no "today's entries" to insert it below, so it fudges up.
So, how can I fix this? How do I use PHP to render the entry instead of javascript?
My Javascript:
Code: Select all
$(function(){
// bind to the form's submit event
$('#entryform').submit(function() {
// show loading on button
$('#entryform li.buttons input').val('Submitting...');
// inside event callbacks 'this' is the DOM element so we first
// wrap it in a jQuery object and then invoke ajaxSubmit
content = $(this).find('#entry').val();
$.post('<?= $this->url('entry_ajax') ?>', { entry: content }, afterSubmit, "json");
return false;
});
});
function afterSubmit(data, textStatus) {
if (textStatus == 'success') {
if (data.success == true) {
entry = $("<div class='entry'></div>");
entry.html(data.entry.entry);
when = $("<span class='when'></div>");
when.html("just now");
entry.append(when);
entry.hide();
$("#entrylist h3.Today").after(entry);
$("#entryform textarea").attr('value', '');
entry.fadeIn('normal', function() {
$('#entryform li.buttons input').val('Submit');
});
} else {
alert(data.responseText);
}
} else {
alert('Sorry, we\'re having issues at the moment. Try again when we don\'t suck.');
}
}