我正在尝试将从表单提交的数据保存到我的mysql数据库中,然后更新div元素,并将最后一个已发布的项目添加到div中的列表中。
现在我只想回复一个回复,我并不担心此刻格式正确。
我的问题是表单不会提交e.preventDefault(); 到位,但没有它,表单执行发布到数据库然后刷新页面的常规方法。
这是我的AJAX电话:
$(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."); } }); }); });我不认为有必要发布我的控制器代码,看看我的问题是如何表格不会超过e.preventDefault(); 功能。
如果e.preventDefault()函数在它到达$.ajax()函数之前停止它,如何通过AJAX提交此表单?
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?
最满意答案
ajax调用的data属性无效。 它应该是JSON格式{ key: $('.feed-input').val() }或查询格式'key='+$('.feed-input').val() 。 在success方法中还有一个不必要的debugger变量。
工作代码可以是:
$('form#feedInput').submit(function(e) { var form = $(this); e.preventDefault(); $.ajax({ type: "POST", url: "<?php echo site_url('dashboard/post_feed_item'); ?>", data: form.serialize(), // <--- THIS IS THE CHANGE dataType: "html", success: function(data){ $('#feed-container').prepend(data); }, error: function() { alert("Error posting feed."); } }); });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 unnecessary debugger variable in the success method.
A working code could be:
$('form#feedInput').submit(function(e) { var form = $(this); e.preventDefault(); $.ajax({ type: "POST", url: "<?php echo site_url('dashboard/post_feed_item'); ?>", data: form.serialize(), // <--- THIS IS THE CHANGE dataType: "html", success: function(data){ $('#feed-container').prepend(data); }, error: function() { alert("Error posting feed."); } }); });更多推荐
发布评论