使用Ajax插入数据

I am using Laravel 5.3. I want to insert the data using blade template.But my when i press submit button it gets refreshed every time. what to do? and please anyone tell me how to use ajax url,type,data

I just assume you are using jquery if you are talking about ajax. It's really simple. Your laravel routes listen to "post", "get", "patch", "delete" methods.

Everything of these can be created with a ajax request - example:

$.ajax({
  method: "POST",
  url: "/posts",
  data: { title: "Hello World", text: "..." }
})
  .done(function( post ) {
    // assuming you return the post
    alert(post.title + " created");
  });

Now that you use ajax you will not want to return a view to the ajax call. You have different options here (create a new route, helper functions etc.) I will give the most easy example

Controller function:

public function store(Request $request) {
    $post = App\Post::create($request->all());

    if($request->ajax()) {
       return $post;
    } else {
       return redirect('/posts');
    }
}

now you controller will return data on ajax calls and will redirect you on default calls without ajax.

Finally you have a last thing to keep in mind. If you have web middleware applied ( done by default ) you need to handle the csrf token. The most easy way to handle this is by adding a meta tag to your html head

and then (before doing all your calls etc.) add this to configure your ajax

$.ajaxSetup({
    headers: {
       'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
    }
});

this will add the valid csrf token which is in your head to every ajax call and will ensure you not run into token missmatch exceptions.

Things to keep in mind: - if you stay very long on one page tokens might expire ( laravel-caffeine will help here ) - you need to handle validation for ajax calls

If you try to submit via Javascript make sure prevent form default action with e.preventDefault(). This code prevent the form submitted in a regular way. Just add this code to wrap your AJAX call:

$('#form-id').submit(function(e){
    e.preventDefault();

    $.ajax({...});
});