PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, January 19, 2022

[FIXED] Using Ajax and returning json array in laravel 5

 January 19, 2022     ajax, javascript, jquery, json, laravel-5     No comments   

Issue

enter image description hereI am new to "AJAX" and I have been trying to send a request "ONSELECT" using "AJAX" and receive a "JSON" response in "laravel 5".

Here is my View

<select>
<option data-id="a" value="a">a</option>
<option data-id="b" value="b">b</option>
<option data-id="c" value="c">c</option>
</select>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>

<script type="text/javascript">
$('select').change(function(){
var data = $(this).children('option:selected').data('id');

$.ajax({
    type    :"POST",
    url     :"http://localhost/laravel/public/form-data",
    dataType:"html",
    data    :{ data1:data },

    success :function(response)
    alert("thank u");
    }),
});
</script>

Here is my Controller to receive ajax request

public function formdata(){
    $data = Input::get('data1');

    //somecodes

    return Response::json(array(
                    'success' => true,
                    'data'   => $data
                )); 
}

Here is my Route

 Route::post('form-data',array('as'=>'form-data','uses'=>'FormController@formdata'));

I also have tried to change the URL of ajax with just only form-data and {{Url::route('form-data')}}.


Solution

Laravel 5 uses csrf token validation for security reasons....try this...

  1. In routes.php

    route post('form-data', 'FormController@postform');
    
  2. In master layout file

    <meta name="csrf-token" content="{{ csrf_token() }}" />
    
  3. var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
    $.ajax({
        url: '/form-data/',
        type: 'POST',
        data: {_token: CSRF_TOKEN},
        dataType: 'JSON',
        success: function (data) {
            console.log(data);
        }
    });
    


Answered By - sunil sah
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing