Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send data without refreshing page in laravel?

I need send data to the database without refreshing page.

Home Blade :

<form class="chat" id="message" action="#" method="post">
    <input type="hidden" name="_token" id="_token" value="{{ csrf_token() }}">
    <li>
        <div class="panel-footer">
            <div class="input-group">
                <input type="text" name="message" class="" placeholder="Type your message here..." />
                <span class="input-group-btn">
                    <button type="submit" class=" btn-success btn-sm searchButton" id="save" >
                    Send
                    </button>
                </span>
            </div>
        </div>
    </li>
</form>

Controller :

public function message(Request $data)
{
    $ins = $data->all();
    unset($ins['_token']);
    $store = DB::table("chatbox")->insert([$ins]);
    return Redirect('Users/home')->with('message',"success");
}

Ajax :

<script>
$(document).on("click", ".save", function() {
    $.ajax({
        type: "post",
        url: '/Users/message',
        data: $(".message").serialize(),
        success: function(store) {

        },
        error: function() {
        }
    });
});
</script>

At present when I send data it is automatically refreshing the whole page but only the particular form need to be refreshed.

like image 995
Hemanth Avatar asked Sep 01 '25 22:09

Hemanth


1 Answers

You should change the type of the button from submit to button like :

<button type="button" class=" btn-success btn-sm searchButton" id="save" >end</button>

Or prevent the default action (submit) using e.preventDefault(); like :

$(document).on("click",".save",function(){
    e.preventDefault(); //Prevent page from submiting
    ...
    ...
}); 

NOTE : Note also that you don't have button with class save but with id save so the event handler should looks like :

$(document).on("click", "#save", function(){
________________________^
like image 107
Zakaria Acharki Avatar answered Sep 03 '25 13:09

Zakaria Acharki