add comment using ajax(from form) - javascript

I want to add comment using ajax. But i faced a problem, that ajax doesn't work. I put alert into success:, but it doesn't go into success function.
$(document).ready(function()
{
$("#comment_form").submit(function(e){
e.preventDefault();
var url_ = "http://127.0.0.1:8000/articles/addcomment/" + "1" + '/';
$.ajax({
url: url_,
type: "post",
success: function(result){
alert(result);
}
});
});
});
Here is my form:
<form action="/articles/addcomment/1/" method="post" id = "comment_form">
<input type = "text" name="commentText" id = "commentText">
<input type="submit" class="button" value="Добавить комментарий" id = "add_comment">
</form>
Console error:
jquery.min.js:5 POST 127.0.0.1:8000/articles/addcomment/1 403 (FORBIDDEN)

Related

How to send multiple variables through ajax?

The code below sends the id of item to more.php to load more content. It works fine. Now to add some more features I need to send one more id to more.php through the same code.
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.show_more',function(){
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type:'POST',
url:'more.php',
data:'id='+ID,
success:function(html){
$('#show_more_main'+ID).remove();
$('.display').append(html);
}
});
});
});
</script>
Suppose second id is var catid = '<?php echo $cat ?>'; how to send this catid through the same ajax code. data : {id : id, catid : catid} is something I should do but can't get how to deal in current situation when my data carries data:'id='+ID,.
your should look like. specify your data as an object:
<script type="text/javascript">
$(document).ready(function () {
$(document).on('click', '.show_more', function () {
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type: 'POST',
url: 'more.php',
data: { id:ID, userid: userid },
success: function (html) {
$('#show_more_main' + ID).remove();
$('.display').append(html);
}
});
});
});
To retrieve multiple input's I suggest combining them in a Form:
first embed your inputs in an form with a submit button, you should also not use the same name twice because it won't work now, create unique names
<form action="GET" id="myForm">
<input id="string" type="text" name="string" />
<input id="string2" type="text" name="string" />
<input type="submit" value="Go" />
</form>
and write code to submit the ajax way
$('#myForm').submit(function(event) {
// Stop form from submitting normally
event.preventDefault();
var $form = $(this);
$.ajax({
type: "GET",
url: "retrieve.php",
data: $form.serialize(), //make it JSON
success: function() {
console.log("it worked");
}
});
});

Preventing jQuery AJAX call from sending form data twice

I'm having some trouble in preventing jquery's ajax call from submitting form data twice.
The form has two fields:
<form id="calendarform_id" method="post" onsubmit="find_schedule()" action="/find_data">
<input id="date1" type="text" required="" name="d_date1">
<input id="date2" type="text" required="" name="d_date2">
</form>
The javascript that makes the ajax call is:
function get_form_data_uid($form){
var form_data_array = $form.serializeArray();
var form_array = {};
$.map(form_data_array, function(n, i){
form_array[n['name']] = n['value'];
});
form_array['uid'] = localStorage.getItem('uid');
return form_array;
}
function find_schedule()
{
var uri, method, formId, $form, form_data;
uri = location.protocol + '//' + location.host + "/find_schedule";
method = "POST";
formId = "#calendarform_id";
$form = $(formId);
form_data = get_form_data_uid($form);
// Set-up ajax call
var request = {
url: uri,
type: method,
contentType: "application/json",
accepts: "application/json",
async: false,
cache: false,
dataType: 'json',
data: form_data
};
$(formId).submit(function(e){
e.preventDefault();
e.stopImmediatePropagation();
// Make the request
$.ajax(request).done(function(data) { // Handle the response
alert(data.message);
}).fail(function(jqXHR) { // Handle failure
console.log("ajax error upon looking up schedule " + jqXHR.status);
}
);
return false;
});
}
Looking at the requests made to the server I see that there is no uid field. I have also tried placing the code retrieving the form data and the user id (uid) as well as the request variable inside the submit handler, but the uid is still not submitted.
Why?
Edit:
I've removed the onsubmit field from the form and moved the submit handler outside the function:
Updated javacript code:
$("#calendarform_id").submit(function(e){
var uri, method, formId, $form, form_data;
uri = location.protocol + '//' + location.host + "/find_schedule";
method = "POST";
formId = "#calendarform_id";
$form = $(formId);
form_data = get_form_data_uid($form);
// Set-up ajax call
var request = {
url: uri,
type: method,
contentType: "application/json",
accepts: "application/json",
async: false,
cache: false,
dataType: 'json',
data: form_data
};
// Prevent implicit submit
e.preventDefault();
e.stopImmediatePropagation();
// Make the request
$.ajax(request).done(function(data) { // Handle the response
alert(data.message);
}).fail(function(jqXHR) { // Handle failure
console.log("ajax error upon looking up schedule " + jqXHR.status);
}
);
return false;
});
Edit #1:
I've added the uid as a hidden field to the form:
<form id="calendarform_id" method="post" action="/find_data">
<input id="date1" type="text" required="" name="d_date1">
<input id="date2" type="text" required="" name="d_date2">
<input id="user_id" type="hidden" name="uid" value="<token_from_local_storage>">
</form>
For some reason apparently I cannot debug code that is within the .submit handler; a simple alert isn't shown either.

why AJAX redirects to the new page in PHP

I have a form:
<form class="searchForm">
<div class="box_style_1">
<h4><?= Yii::t("common", "Age"); ?></h4>
<?
echo '<b class="badge">3</b> ' . Slider::widget([
'name'=>'age',
'value'=>'250,650',
'sliderColor'=>Slider::TYPE_GREY,
'pluginOptions'=>[
'min'=>3,
'max'=>21,
'step'=>1,
'range'=>true
],
]) . ' <b class="badge">21</b>';
?>
<br /><br />
<input type="submit" value="Search" class="searchByAge"/>
<br /><br />
</div>
</form>
And want to show the result in console.log:
$('.searchByAge').on('click', function(e){
e.preventDefault();
var range = $('.form-control').val();
var min = range.split(',')[0];
var max = range.split(',')[1];
//alert(min+' '+max);
$.ajax({
type: 'POST',
url: '/age/'+min+'/'+max,
data: $('.searchForm').serialize(),
success: function (data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
}
});
})
and that's my AJAX code. But when I click on Search button it redirects me to the new page and nothing in the console log. I do not know what is wrong in my code.
I return a JSON from the '/age/min_age/max_age' page, but the result shows in the new page.
How can I fix this problem?
change code to below. change input type submit to button
<input type="button" value="Search" class="searchByAge"/>
also wrap your code in $(document).ready();
Make sure to add jQuery library from correct path.
$(document).ready(function(){
$('.searchByAge').on('click', function(e){
e.preventDefault();
var range = $('.form-control').val();
var min = range.split(',')[0];
var max = range.split(',')[1];
//alert(min+' '+max);
$.ajax({
type: 'POST',
url: '/age/'+min+'/'+max,
data: $('.searchForm').serialize(),
success: function (data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
}
});
});
});
replace your code
$('.searchByAge').on('click', function(e){
e.preventDefault();
with this
$('form.searchForm').on('submit', function(e){
e.preventDefault();
on first code you are preventing your click event instead of submit event thats why form is still submitting

AJAX pass data to PHP

I've been searching this forum, but I had no good result. I have this HTML:
<form method="post" id="postform">
<input type="text" name="message" id="message" placeholder='Say "Hello!"' class="mymessage" maxlength="255"/>
<br />
<input id="submit" type="button" value="Send"/>
</form>
PHP:
<?php
include ('connect.php');
session_start();
if (isset($_POST['message'])){
mysql_query("INSERT INTO messages VALUES ('','".$_POST['message']."','".$_SESSION['user']."')");
}
?>
And jQuery:
$('#submit').click(
function(){
var message = $('#message').val();
$.ajax({
url: post.php,
type:'POST',
data: {"message":message}
});
});
I need to pass #message content to PHP without refreshig the page. This is what I've made, but it's not working.
Check your syntax:
Wrap url with quotes '
Remove single quotes around 'message' variable
$.ajax({
url: 'post.php',
type: 'POST',
data: {message : message}
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
See the first example of $.ajax() at the bottom of its documentation page.
I need to pass #message content to PHP without refreshig the page.
Handle form submit instead:
$("#postform").submit(function(){
var message = $('#message').val();
$.ajax({
url: 'post.php',
type:'POST',
data: {message:message}
}).done(function( data) {
// handle response from the server in case of success.
});
return false; //to prevent submitting and refreshing the page.
});

flask ajax/jquery form submission

So I have this code below.
This is my jquery/ajax script
$(function() {
$(".reply").click(function(){
var id = $(this).attr("id");
var element = ".comment_replies#" + id;
$(element).show();
$(".submit_reply#" + id).click( function(event) {
event.preventDefault();
var reply_box = ".reply_box#" + id
var data = $(reply_box).val
$.ajax({
type : "POST",
url : "{{url_for('main.HomePage')}}",
data: JSON.stringify(data, null, '\t'),
contentType: 'application/json;charset=UTF-8',
success: function(result) {
console.log(result);
console.log(data)}
})
})
})
})
here is the form:
<form class = "reply_form" action="#" method="post">
<input class = "reply_box" type="text" placeholder ="write a reply" name="reply" id = "{{'id_' +com.id|string}}">
<input type="submit" class = "submit_reply" value = "reply" id = "{{'id_' +com.id|string}}">
<input type="hidden" value="{{com.id}}" name = "form_id">
</form>
and if I do:
if request.json["data"] in my HomePage view it somehow doesn't pass
because usually i'd just go if request.form when submitting the form the usual way. here is my homepage view
if request.json["data"] and request.method == "POST":
return request.json["data"]
it's only a test to see if it return what I want it too and it fails.
am I suppose to have extra imports for json? because I don't have any.
I also see this error on firebug:
POST http://127.0.0.1:5000/homepage
400 BAD REQUEST
11ms
I could submit the form the usual way but I wanna try submitting the form and appending the info without a page refresh.

Categories