Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
43
rated 0 times [  47] [ 4]  / answers: 1 / hits: 66103  / 12 Years ago, sat, july 21, 2012, 12:00:00

I have a simple form submission with ajax, but it keeps giving me an error. All the error says is error. No code, no description. No nothing, when I alert it when it fails.



Javascript with jQuery:



$(document).ready(function(){

$(.post-input).submit(function(){
var postcontent = $(.post-form).val();

if (postcontent == ){
return false;
}

$(.post-form).attr(disabled, disabled);

$.ajax({
url: '/post',
type: 'POST',
data: {post-form: postcontent},
dataType: json,
success: function(response, textStatus, jqXHR) {
alert(Yay!);
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
});
});


HTML:



<form class=post-input action= method=post accept-charset=utf-8>
<textarea class=post-form name=post-form rows=1 cols=10 onFocus=this.value='';return false;>What are you thinking about...</textarea>
<p><input class=post-submit type=submit name = post.submitted value=Post></p>
</form>


and if there are no problems there, then the server-side (pyramid):



def post(request):
session = Session()
user = authenticated_userid(request)
postContent = request.POST['post-form']
if not postContent == '':
session.add(Activity(user.user_id, 0, postContent, None, None))
return {}
return HTTPNotFound()


UPDATE:
After some more debugging with firebug, I discovered that the post request body contains only post.submitted=Post, instead of the intended result of {post-form: postcontent}.


More From » jquery

 Answers
199

According to jQuery documentation, you must declare the data type:



$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});


Also, looking at your server-side code, you don't actually want to post JSON formatted data. This {post-form:postcontent} is JSON formatted data. What you actually want to do is send TEXT or HTML. Seeming as it's form data, I would guess at TEXT.



Try this:



$.ajax({
url: '/post',
type: 'POST',
data: 'post-form='+postcontent,
dataType: 'text',
success: function(response, textStatus, jqXHR) {
alert(Yay!);
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});

[#84106] Friday, July 20, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mireyag

Total Points: 73
Total Questions: 107
Total Answers: 85

Location: Ukraine
Member since Sun, Dec 13, 2020
3 Years ago
mireyag questions
Sun, Aug 15, 21, 00:00, 3 Years ago
Wed, Dec 16, 20, 00:00, 3 Years ago
Tue, Sep 1, 20, 00:00, 4 Years ago
Sun, Jul 5, 20, 00:00, 4 Years ago
;