Tagged: Laravel 5.7 Jquery Ajax Request Example From Scratch

Laravel controller Get csrf tokens in ajax calls 0

Laravel controller Get csrf tokens in ajax calls

Today, We want to share with you Laravel controller Get csrf tokens in ajax calls.In this post we will show you Laravel 5 csrf tokens in ajax calls, hear for PHP – Laravel csrf token mismatch in ajax POST Request with example we will give you demo and example for implement.In this post, we will learn about How to send an Ajax request to Controller with an example.

Laravel controller Get csrf tokens in ajax calls

There are the Following The simple About Laravel controller Get csrf tokens in ajax calls Full Information With Example and source code.

As I will cover this Post with live Working example to develop Laravel 5.7 Jquery Ajax Request Example From Scratch, so the PHP – Laravel csrf token mismatch in ajax POST Request for this example is following below.

CSRF token mismatch exception in ajax post request

  $.ajax({
      type: "POST",
      url: "/poke",
      data: {   lat: getdatalatitiude,
                lng: getdatalongitude,
                bearing: 90,
                '_token': '{!! csrf_token() !!}'
            }
    });

CSRF Protection with Ajax and Laravel

    <meta name="csrf-token" content="{!! csrf_token() !!}">

    $.ajax({
      type: "POST",
      url: "/poke",
      data: {   lat: getdatalatitiude,
                lng: getdatalongitude,
                bearing: 90,
                '_token': $('meta[name="csrf-token"]').attr('content')
            }
    })

Laravel csrf token mismatch for ajax POST Request

//Save
$('.save').click(function()
{

    var dataobj = {};
    dataobj.user_id = user_id.trim();
    dataobj.status = status.trim();

    //Laravel csrf token mismatch for ajax POST Request
    dataobj._token = '{{csrf_token()}}';

    // alert(JSON.stringify(dataobj));
    // Your Ajax Code Here
    // Then run this on success to handle updating
    $.ajax(
        {
            type:"POST",
            dataType:"json",
            url:"{{ url('/updateStatus') }}",
            cache: false,
            data: dataobj,
            success:function(response)
            {
                $(".name").css("color", response['color'][0].color);
            }
        });

});

Send CSRF token with datatable ajax

@section('head')
<meta name="csrf_token" content="{{ csrf_token() }}" />
@endsection

$('#datatable_products').DataTable({
    "responsive": true,
    "serverSide": true,
    "processing": true,
    "paging": true,
    "searching": { "regex": true },
    "lengthMenu": [ [10, 25, 50, 100, -1], [10, 25, 50, 100, "All"] ],
    "pageLength": 10,
    "ajax": {
        "type": "POST",
        "headers": {'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')},
        "url": "/updateStatus",
        "dataType": "json",
        "contentType": 'application/json; charset=utf-8',
        "data": function (data) {
            console.log(data);
        },
        "complete": function(response) {
            console.log(response);
       }
    }
});

Angular 6 CRUD Operations Application Tutorials

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about Laravel controller Get csrf tokens in ajax calls.
I would like to have feedback on my Pakainfo.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Laravel 5.7 JQuery AJAX Tutorial Example 0

Laravel 5.7 JQuery AJAX Tutorial Example

Today, We want to share with you Laravel 5.7 JQuery AJAX Tutorial Example.In this post we will show you PHP Laravel 5.7 JQuery Ajax Pagination Tutorial, hear for Laravel 5.7 Jquery Ajax Request Example From Scratch we will give you demo and example for implement.In this post, we will learn about Laravel 5 Ajax CRUD example for web application without page refresh with an example.

Laravel 5.7 JQuery AJAX Tutorial Example

There are the Following The simple About Full Information With Example and source code.

As I will cover this Post with live Working example to develop Laravel 5.7 Ajax Pagination Example, so the some PHP Laravel 5.7 JQuery Ajax Pagination for this example is following below.

Step 1 : Install Laravel 5.7 Project

Install and configure the Laravel 5.7 Application

//install the Laravel 5.7 Project
composer create-project laravel/laravel atmiya25 --prefer-dist

//generating migration file on Laravel 5.7
php artisan make:migration create_groceries_table

generated Laravel 5.7 the migration file

public function up()
 {
   Schema::create('groceries', function (Blueprint $table) {
      $table->increments('id');
      $table->string('membername');
      $table->string('department');
      $table->integer('age');
      $table->timestamps();
    });
 }

Create Database table using migrate

php artisan migrate

Step 2: Laravel 5.7 routes, model and controllers.

Define a Laravel 5.7 model and controller

php artisan make:model Member
php artisan make:controller MemberController

routes/web.php

Route::view('/member', 'member');
Route::post('/member/post', '[email protected]');

resources/views/member.blade.php

<!doctype html>
<html lang="{{ app()->getLocale() }}">
    <head>
        <meta charset="utf-8"/>
        <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
        <meta name="viewport" content="width=device-width, initial-scale=1"/>

        <title>Member Store</title>
        <link href="{{asset('css/app.css')}}" rel="stylesheet" type="text/css"/>
    </head>
    <body>
      Member App
    </body>
</html>

On Terminal To start the development serve

php artisan serve

Step 3: HTML Interface bootstrap form.

member.blade.php

<!doctype html>
<html lang="{{ app()->getLocale() }}">
    <head>
        <meta charset="utf-8"/>
        <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
        <meta name="viewport" content="width=device-width, initial-scale=1"/>

        <title>Laravel 5.7 Jquery Ajax Request Example From Scratch</title>
        <link href="{{asset('css/app.css')}}" rel="stylesheet" type="text/css"/>
    </head>
    <body>
	<h1>Laravel 5.7 Ajax Request Example</h1>
      <div class="container">
         <form id="myForm">
            <div class="form-group">
              <label for="membername">Member Name:</label>
              <input type="text" class="form-control" id="membername">
            </div>
            <div class="form-group">
              <label for="department">Department:</label>
              <input type="text" class="form-control" id="department">
            </div>
            <div class="form-group">
               <label for="age">Age:</label>
               <input type="text" class="form-control" id="age">
             </div>
            <button class="btn btn-primary pakainfo">Submit</button>
          </form>
      </div>
    </body>
</html>

CDN for jQuery

<script src="http://code.jquery.com/jquery-3.3.1.min.js"
               integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
               crossorigin="anonymous">
</script>

Step 4: Laravel 5.7 Ajax request.

Include headers in csrf token

jQuery(document).ready(function(){
jQuery('#laraAjaxSave').click(function(e){
   e.preventDefault();
   $.ajaxSetup({
	  headers: {
		  'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
	  }
  });
});
});

Laravel 5.7 jQuery.ajax() Send Data

<script src="http://code.jquery.com/jquery-3.3.1.min.js"
      integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
      crossorigin="anonymous">
</script>
<script>
         jQuery(document).ready(function(){
            jQuery('#laraAjaxSave').click(function(e){
               e.preventDefault();
               $.ajaxSetup({
                  headers: {
                      'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                  }
              });
               jQuery.ajax({
                  url: "{{ url('/member/post') }}",
                  method: 'post',
                  data: {
                     membername: jQuery('#membername').val(),
                     department: jQuery('#department').val(),
                     age: jQuery('#age').val()
                  },
                  success: function(result){
                     console.log(result);
                  }});
               });
            });
</script>

Step 5: Insert function to store Save the data.

MemberController.php

use App\Member;

 public function store(Request $request)
 {
        $member = new Member();
        $member->membername = $request->membername;
        $member->department = $request->department;
        $member->age = $request->age;

        $member->save();
        return response()->json(['success'=>'Data is successfully added']);
 }

And then Last, I should to list the all message that I have successfully Instered the All data.

<!doctype html>
<html lang="{{ app()->getLocale() }}">
    <head>
        <meta charset="utf-8"/>
        <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
        <meta name="viewport" content="width=device-width, initial-scale=1"/>
        <meta name="_token" content="{{csrf_token()}}" />
        <title>Laravel 5 Ajax CRUD example for web application without page refresh</title>
        <link href="{{asset('css/app.css')}}" rel="stylesheet" type="text/css"/>
    </head>
    <body>
	<h1>PHP Laravel 5.7 JQuery Ajax Pagination Tutorial</h1>
      <div class="container">
         <div class="alert alert-success" style="display:none"></div>
         <form id="myForm">
            <div class="form-group">
              <label for="membername">Member Name:</label>
              <input type="text" class="form-control" id="membername">
            </div>
            <div class="form-group">
              <label for="department">Department:</label>
              <input type="text" class="form-control" id="department">
            </div>
            <div class="form-group">
               <label for="age">Age:</label>
               <input type="text" class="form-control" id="age">
             </div>
            <button class="btn btn-primary" id="laraAjaxSave">Submit</button>
          </form>
      </div>
      <script src="http://code.jquery.com/jquery-3.3.1.min.js"
               integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
               crossorigin="anonymous">
      </script>
      <script>
         jQuery(document).ready(function(){
            jQuery('#laraAjaxSave').click(function(e){
               e.preventDefault();
               $.ajaxSetup({
                  headers: {
                      'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                  }
              });
               jQuery.ajax({
                  url: "{{ url('/member/post') }}",
                  method: 'post',
                  data: {
                     membername: jQuery('#membername').val(),
                     department: jQuery('#department').val(),
                     age: jQuery('#age').val()
                  },
                  success: function(result){
                     jQuery('.alert').show();
                     jQuery('.alert').html(result.success);
                  }});
               });
            });
      </script>
    </body>
</html>

Angular 6 CRUD Operations Application Tutorials

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about Laravel 5.7 JQuery AJAX Tutorial Example.
I would like to have feedback on my Pakainfo.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

PHP Laravel AJAX Request GET and POST Example 0

PHP Laravel AJAX Request GET and POST Example

Today, We want to share with you PHP Laravel AJAX Request GET and POST Example.In this post we will show you Laravel 5.7 Jquery Ajax Request Example From Scratch, hear for Ajax requests using jQuery and Laravel 5.7 we will give you demo and example for implement.In this post, we will learn about jQuery Ajax Call to Laravel Script with JSON Return with an example.

PHP Laravel AJAX Request GET and POST Example

There are the Following The simple About PHP Laravel AJAX Request GET and POST Example Full Information With Example and source code.

As I will cover this Post with live Working example to develop Simple Ajax request example with JQuery and Laravel, so the Laravel 5.7 Jquery Ajax Request Example From Scratch is following below.

Example 1 : Laravel Requests Ajax GET and POST

resources/views/product/create.php

    $(document).ready(function()
    {

        $( ".btn-product-save" ).click(function() {

            if($('#product_info').val() == '')
            {
                $(".product_infoerror").text("Enter Describe your Products Information here in details");
            }
            else{
                $("#loading").show();

                var productsobj = {};
                productsobj.user_id  = {{Auth::user()->id}};


                productsobj.product_info =$('#product_info').val();
                productsobj.productable_type = $('#productable_type').val();
                productsobj.product_id = $('#product_id').val();

                productsobj.product_team_display = 1;

                productsobj._token = '{{csrf_token()}}';


                $.ajax({
                    type:"POST",
                    dataType:"json",
                    url:"{{ url('products') }}",
                    cache: false,
                    data: productsobj,
                    success: function (data) {
                        //  console.log(data);
                    },
                    error: function (data) {
                        console.log('Error:', data);
                        var obj = {
                        };
                    }
                });
            }
        });
    });

routes/web.php

	Route::post('products', '[email protected]');

app/http/controllers/ProductController

	public function products(Request $request)
    {

          DB::table('productslist')->insert([
            'product_info' => $request['product_info'],
            'product_id' => $request['product_id'],
            'user_id' => $request['user_id'],
            'product_team_display' => $request['product_team_display'],
            'productable_type' => $request['productable_type'],
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ]);

        $product_id = DB::getPdo()->lastInsertId();

        $affected = DB::table('products')->where('id', '=', $request['product_id'])->update(array('productable_type' => 1));

        }

        $productslist = DB::table('productslist')
            ->join('users', 'productslist.user_id', '=', 'users.id')
            ->select('productslist.*', 'users.name AS uname')
            ->where('productslist.id', '=', $product_id)->get();
        return response()->json(['product'=>$productslist]);
    }

Example 2 : Laravel AJAX Calling For API

index.php

$( ".btn-product" ).click(function() {
    var productsobj = {};
    productsobj.product_id = $('#product_id').val();
    $.ajax({
        type:"POST",
        dataType:"json",
        url:"<?php echo $api_url.'updateproduct'?>",
        cache: false,
        data: productsobj,
        beforeSend: function(xhr){ xhr.setRequestHeader('Authorization', '<?php echo $your_secreate_key;?>'); },
        success: function (data) {
            //console.log(data['message']);
            window.location = 'index.php?res='+data['message'];
        },
        error: function (data) {
            console.log('Error:', data);
            var obj = {
            };
        }
    });
});

routes/api.php

Route::post('updateproduct', 'API\[email protected]');

app/http/controllers/API/ProductController

public function updateproduct(Request $request)
{
    $affected = DB::table('products')->where('id', '=', $request['product_id'])->update(array('status_id' => 0));
    return $this->sendResponse($request['product_id'], 'The Product has been updated!.');
}

Angular 6 CRUD Operations Application Tutorials

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about PHP Laravel AJAX Request GET and POST Example.
I would like to have feedback on my Pakainfo.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.