Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying the data from database without reloading

HTML

<textarea>Ask a question</textarea><button class="addquestion">POST</button>

After clicking the button the question is added to the database using the following Ajax, jquery and laravel. But, the question is displayed only after reloading. How can the question be added immediately after clicking the button only after storing it in database.

Ajax And Jquery:

$(document).on('click','.addquestion',function(e)
{
    e.preventDefault();
    var question = $(this).prev().val();
    $.ajax({
        type:"POST",
        url: "{{url('/music/addquestion')}}",
        data: {
        "_token": "{{ csrf_token() }}",
        "question": question
        },
        success: function (data) {
            var res = $.parseJSON(data);
            if(res == true)
            {
                alert('question added!');
            }
        }
    });
});

Laravel controller

public function addquestion(Request $request)
    {
        if($request->Ajax())
        {
            $question = new Question();
            $question->question=$request->question;
            if($question->save())
            {
                   echo json_encode(TRUE);die;
            }
        }
    }
like image 963
Steve Avatar asked Feb 20 '26 20:02

Steve


1 Answers

Do so after your alert.

 if(res == true)
    {
       alert('question added!');
       //Add question here
    }
like image 168
David Jiboye Avatar answered Feb 23 '26 08:02

David Jiboye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!