JQuery ajax request not working

I have a simple presentation form with ajax, but it keeps giving me an error. All error indicates error. No code, no description. There is nothing when I warn about this, when he 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, then the server (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 additional debugging with firebug, I found that the message request body contains only post.submitted = Post, and not the intended result {"post-form": postcontent}.

+6
source share
3 answers

According to jQuery documentation, you should declare a data type:

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

In addition, looking at your server code, you actually do not want to publish data in JSON format. This {"post-form":postcontent} is JSON formatted data. What you really want to do is send TEXT or HTML. Seeing how it forms data, I would suggest in TEXT.

Try the following:

 $.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); } }); 
+14
source

Since you are sending JSON -data, you must declare dataType "JSON":

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

I think the problem is that the data you transmit is incorrectly written.

 Try to change data: {"post-form": postcontent}, To: data: 'post-form='+ $('.post-form').val(), 
+1
source

Source: https://habr.com/ru/post/921044/


All Articles