Y
Y
Yevhenii K2015-11-22 23:52:31
PHP
Yevhenii K, 2015-11-22 23:52:31

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",
  {
   //даннЫе
  }
);
});

I can't figure out how to write the sent data to a JS script and pass it to php.
The same, the same and how to transfer the data received from the database to JS for display on the site.
Help solve the problem.
The form
<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>

2. A similar question, you need to do what would be at the time of filling out the reg. forms, the login and email were immediately checked for duplicates and, depending on the result, the color of the frame changed.

PS I understand how to solve the php part, but there is a problem with the JS script and data transfer between php and js. Help, thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Dyrkov, 2015-11-23
@VIKINGVyksa

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
    
  });
});

In php it's even easier, just parse the array, work with the base and echo return the data back)

S
Super User, 2015-11-23
@sergeystepanov1988

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>'); 
  });
);
});

This is in its simplest form. It really depends on the markup, requirements, and implementation on the server.
UPD: If you are good with jQuery, then it will be difficult to implement all this yourself.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question