Answer the question
In order to leave comments, you need to log in
How to use AJAX jQuery and php to send form data (comments) to the database and return them without reloading the page?
Good evening! Please help a newbie. I want to redo the comments on my site, I need them to be added and displayed without reloading the page. JS don't know what is causing the jQuery script issue. I know that I need a click event, on which the function with ajax post will be executed. It just came out like this
$('form').on('submit', function(){
$.post("test1.php",
{
//даннЫе
}
);
});
<form method="POST" action="php/scripts/add_coment.php">
<textarea rows="2" cols="45" name="comment"></textarea>
<input type="text" hidden="hidden" name="login" value="{$_SESSION['login']}">
<input type="text" hidden="hidden" name="user_id" value="{$_SESSION['user_id']}">
<input type="text" hidden="hidden" name="news_id" value="{$_SESSION['news_id']}">
<button type="submit">Отправить</button>
</form>
Answer the question
In order to leave comments, you need to log in
You need to create a php file that will process this request. For example ajax-form-comment.php. In it, you describe in php all the logic for obtaining data. Just take everything from the post array. Using AJAX, you form a request, the php file receives a request from ajax, processes it there, adds a comment to the database, and using echo displays a response, for example, the text "Everything is cool, we wrote down a comment!" or in JSON format. This data will come to the callback success or done function (depending on which one you will use). And in it you describe the logic, for example, rendering this added comment (you only need to receive confirmation from the server that the comment has entered the database, and use the same data that was sent by AJAX earlier to the server). If you need code, then I can write the js part.
$('form').on('submit',function(){//используйте id лучше
e.pereventDefault();//блокируем действия по умолчанию, чтобы не перезагружать страницу
var data;//записываем сюда данные которые хотим передать
$.ajax({
url:'file.php',
data:data,//наши данные которые передадим
method:'POST',//метод
dataType:'text/plain',
}).done(function(data){//допустим сервер будет возвращять JSON {isError="true",message="Всё записалось"}
//описываем действия по получению ответа сервера
if(data.isError==true){
//коммент записался
page.render(data);//отрисовываем наш комент с переданными рание данными
}
}).fail(function(err){
//обрабатываем ошибку ajax
});
});
Something like this:
$('form').on('submit', function(e){
e.preventDefault(); //подавляем отправку данных формы и перезагрузку старницы
var data = this.serialize();
$.post("test1.php", data, function(json){
$('.commentbox').append('<div><span>' + json.author + '</span><p>' + json.comment + '</p></div>');
});
);
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question