I am trying to save data submitted from a form into my mysql database and and then update the div element with the last posted item prepended to the list in the div.
Right now I am only trying to get a response back, I'm not worried about having the formatting correct at the moment.
My problem is the form won't submit with e.preventDefault();
in place, but without it the form does the normal method of posting to the db then refreshing the page.
Here is my AJAX call:
$(document).ready(function() {
$('form#feedInput').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
data: $('.feed-input').val(),
dataType: "html",
success: function(data){
debugger;
$('#feed-container').prepend(data);
},
error: function() { alert("Error posting feed."); }
});
});
});
I don't think it's necessary for me to post my controller code, seeing as how my issue is the form won't make it past the e.preventDefault();
function.
How can I get this form to submit via AJAX if the e.preventDefault()
function is stopping it before it can reach the $.ajax()
function?
Html part in view
After Html Part Just put ajax request
Within Controller
The
data
attribute of the ajax call is invalid. It should be either in JSON format{ key: $('.feed-input').val() }
or in query format'key='+$('.feed-input').val()
. Also there is an unnecessarydebugger
variable in the success method.A working code could be:
You don't have to use
preventDefault();
you can usereturn false;
in the end of functionsubmit()
but I doubt this is the problem.You should also use url encoding on
$('.feed-input').val()
useencodeURIComponent
for this.You should also check if you have errors in your console.
To determine if default action is prevented you can use
e.isDefaultPrevented()
. By default action in this case I mean submit action of the form with id feedInput.You didn't name your param in data. Check jquery ajax examples.
You are probably getting an error
e.preventDefault();
is not stopping the ajax.