0

Ajax works well for pre-existing forms. But if I add a new form using it and submit it, then I get to the method page.

Added a new form, filled in the field and clicked Submit: http://joxi.ru/DmBOW4KUzep962

I get to the method page, instead of displaying the result in the console: http://joxi.ru/EA4P710TOekbOA

After reloading the page, everything works well.

What could be the matter, tell me please.

Front:

$('.add-answer-form').on('submit', function (e) {
        e.preventDefault();
          $.ajax({
            type: "POST",
            url: `/admin/courses/48/lessons/96/answerAdd`,
            data: $(this).serialize(),
            success: function (data) {
              console.log('!!!!!', data);
            }
          });
      });

Back:

   public function answerAdd(Request $request, Course $course, Lesson $lesson, Test $test, Answer $answer){
        $this->answer->fill($request->all())->save();
        return response ()->json ($this);
   }
8
  • Well, to me it looks like you are not doing anything with your response in the success callback. You need to be injecting/building the html based on the response. Is that what you mean? Commented Jun 30, 2020 at 7:37
  • @KurtFriars, The answer should at least get to the console, as here: joxi.ru/ZrJl84xcME80Z2 Commented Jun 30, 2020 at 7:47
  • I am not sure I am understanding your problem. Are you saying that the answer is not added in the json returned from your controller, but on page reload the answer is there? Commented Jun 30, 2020 at 8:42
  • @KurtFriars, Not really. The answer comes in json format, but the URL changes to the called method, as I showed in the screenshot, instead of just returning the result of the controller to the console. Commented Jun 30, 2020 at 9:16
  • Ok so your problem is that you are being redirected when the ajax response for the added answer button succeeds? If yes, then can you capture the server response in your network inspector and share it? Commented Jun 30, 2020 at 9:23

1 Answer 1

1

I solved this issue as follows: Instead of this:

$ ('.add-answer-form').on('submit', function (e) {

Added this:

$ ('#quest-add-form').on('submit', '.add-answer-form', function (e) {

This is suitable in cases where you need to work with the form that was added by Ajax.

Sign up to request clarification or add additional context in comments.

1 Comment

Good job Artem!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.