无需重新加载即可显示数据库中的数据

时间:2016-09-13 06:53:20

标签: javascript php jquery ajax laravel

HTML

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

单击按钮后,使用以下Ajax,jquery和laravel将问题添加到数据库中。但是,问题仅在重新加载后显示。只有在将按钮存储在数据库中后才能立即添加问题。

Ajax和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控制器

public function addquestion(Request $request)
    {
        if($request->Ajax())
        {
            $question = new Question();
            $question->question=$request->question;
            if($question->save())
            {
                   echo json_encode(TRUE);die;
            }
        }
    }

3 个答案:

答案 0 :(得分:1)

警告后这样做。

 if(res == true)
    {
       alert('question added!');
       //Add question here
    }

答案 1 :(得分:0)

    $(document).on('click','.addquestion',function(e)
    {
        e.preventDefault();
        var question = $(this).prev().val();
       // you can show the question by `question var` from here by using 
       // $('selecter').html(question); or if appending to any input type field
       //$('selecter').val(question); or 
       //you can append it when you got success response
        $.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!');
                   // $('selecter').html(question); or 
                  //$('selecter').val(question); 


                }
            }
        });
    });

答案 2 :(得分:0)

添加div

                        <div class="col-xs-12">
                            <a class="btn btn-cennik" role="button" data-toggle="collapse" href="#<?php the_sub_field('cennik_href'); ?>" aria-expanded="false" aria-controls="collapseExample">
                                <?php the_sub_field('cennik_nazwa_sekcji'); ?>
                            </a>
                        </div>

json编码变量:

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

显示:

echo json_encode(array('status'=>TRUE,'question'=>$request->question));die;