How to post laravel form data to controller using ajax in API

laravel ajax post data to controller
how to pass data from view to controller using ajax + laravel
laravel ajax form submit with validation
get ajax post data in laravel
passing data from ajax to controller laravel
laravel route ajax post
how to insert data using ajax in laravel with datatables
how to send ajax request in laravel controller

I have a form, which is opened in the Android web view, I want to save data to the database, but when I have making an ajax call and try to print data is showing a blank array, following are my code :

<div class="card-body card-padding">
    <form id="submitdataform">
        @csrf
        @foreach($formfields as $key=>$value)
            <input type="hidden" name="campaign_id" value="{{$key}}"/>
            @foreach($value as $attrkey)
                <input type="hidden" name="attribute_id[]" value="{{$attrkey->id}}"/>
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group">
                            <label class="pure-material-textfield-outlined w-100">
                                {{--<input placeholder=" " type="text" required>--}}
                                <?php
                                if ($attrkey->attribute_type == 'alpha') {
                                    echo "<input placeholder=' ' type='text' name='attribute_value[]' required>";
                                } elseif ($attrkey->attribute_type == 'date') {
                                    echo "<input placeholder=' ' type='date' name='attribute_value[]' required>";
                                } elseif ($attrkey->attribute_type == 'numberic') {
                                    echo "<input placeholder=' ' type='number' name='attribute_value[]' required>";
                                }
                                ?>
                                <span>{{$attrkey->attribute_name}}</span>
                            </label>
                        </div>
                    </div>

                </div>
            @endforeach
        @endforeach
        <button type="button" id="submitbtn">Submit</button>
    </form>
</div>

Now ajax call

$("#submitbtn").click(function (event) {
    event.preventDefault();
    var data = $("#submitdataform").serialize();
    $.ajax({
        type: "post",
        url: "savecampaigndata",
        data: {data: data},
        contentType: 'application/x-www-form-urlencoded',
        dataType: 'json',
        success: function (data) {
            // Android.passParams('dashboard');
        },
        error: function (data) {
            // Android.passParams(url);
        }
    });
});

And this is the controller method where I want to get all my data ,

public function SaveCampaignData(Request $request)
{
    return response()->json($request->all());
    $data = $request->all();
    $attribute_id = [];
    $attribute_value = [];
    $campaign_id = $data['campaign_id'];
    $user_id = Auth::user()->id;

    foreach ($data as $key => $value) {
        if ($key == "attribute_id") {
            foreach ($value as $attrkey) {
                $attribute_id[] = $attrkey;
            }
        } else {
            if ($key == "attribute_value") {
                foreach ($value as $attrvalue) {
                    $attribute_value[] = $attrvalue;
                }
            }
        }
    }

    $mainArray = array_combine($attribute_id, $attribute_value);
    $currentdate = Carbon::now();
    foreach ($mainArray as $key => $value) {
        DB::table('campaign_attribute_values')->insert(
            [
                'campaign_id'              => $campaign_id,
                'campaign_attribute_id'    => $key,
                'user_id'                  => $user_id,
                'campaign_attribute_value' => $value,
                'created_at'               => $currentdate,
                'updated_at'               => $currentdate,
            ]
        );
    }

    if ($this->CheckSmsLimit() > 0) {
        $this->checkAutoReply($campaign_id, $user_id);
    }

    return redirect()->back()->with('success', 'Request Registered');
//        return response()->json(['status' => true, 'message' => 'Record saved succesfully', 'code' => 200]);
}

This is postman route URL :

https://subdomain.xyz.com/savecampaigndata

But it's giving a blank array as output in my controller.

$("#submitbtn").click(function (event) {
    event.preventDefault();
    var data = $("#submitdataform").serialize();
    $.ajax({
        type: "post",
        url: "{{ url('savecampaigndata) }}",
        data: {data: data},
        success: function (data) {
            // Android.passParams('dashboard');
        },
        error: function (data) {
            // Android.passParams(url);
        }
    });
});

1. if you don't want to send csrf token

then 

app/Http/Middleware/VerifyCsrfToken.php

and add this route's url to the except array

protected $except = [
   'savecampaigndata'
];

2. if want 

then add in head 
<meta name="csrf-token" content="{{ csrf_token() }}">

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

laravel 5.2 send form data to controller with ajax, I think you aren't sending the file to the server at all. I could be mistaken though, but you could try something like this: var CSRF_TOKEN� So will prefer the POST method. Laravel Ajax Post Request. Lets make it quick by changing the same form we used earlier. Change the method in the form from GET to POST. If you have noticed that when using post request while submitting the form csrf token need to be applied so we also have to place csrf token in the form.

Try to add '/' in url attribute of ajax call & add header attribute also in ajax call.

Laravel 5.8 Post Form Data From View to Controller Using Ajax , In this laravel tutorial I have explained how can we post form data from view to controller Duration: 25:58 Posted: Apr 21, 2019 In this tutorial, you can submit the form using jQuery ajax and without refresh the whole web page. When submitting an ajax form in laravel, you will add csrf token in ajax post request. Laravel Ajax Post Form Data With Validation. Follow the below steps and easily post form data on the laravel controller with jQuery validation:

It looks like the reason you're getting a blank response is because of csrf. I see that you have included it in your form, however, because you're using serialize it won't work the way you expect it to.

The are a few different ways you can add the csrf:

  1. If your script is inside your blade file you could simply add it to the data object:

    data: {
        data: data,
        _token: "{{ csrf_token() }}",
    },
    

    Or

  2. as per the documentation you could add the following inside the <head> of your page :

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

    and then included the following after you've pulled in jQuery:

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

Laravel 5.8 jQuery Ajax Form Submit | W3Schools, Laravel jwt Authentication API | Laravel 5.8 Create REST API with jwt Authentication � Laravel In Laravel, to submit form data using ajax we must have to incorporate csrf token with and inside the boot method set a default string length as given below – php artisan make:controller ajaxFormSubmit/ ContactController� we are all familiar with ajax post and get request and i think we also use ajax request with jquery many times and many project may be. But in this project i will show you how to use jquery ajax request in laravel 5.7 application. You can simple implement ajax post request with pass form data and you can access post data to controller.

Laravel 6 Ajax Request Tutorial, Laravel 6 Ajax Request Tutorial. Step 1: Create Routes. First thing is we put two routes in one for displaying view and another for post Ajax. Step 2: Create Controller. Same things as above for routes, here we will add two new method for routes. Step 3: Create Blade File. To quickly generate an API resource controller that does not include the create or edit methods, use the --api switch when executing the make:controller command: php artisan make:controller API/PhotoController --api. Nested Resources. Sometimes you may need to define routes to a nested resource.

JQuery Ajax Post Request Example in Laravel 5.7, You can simple implement ajax post request with pass form data and you can access post data to controller. You have to just do three things to� Ajax request is a basic requirement of any php project, we are always looking for without page refresh data should store in database and it's possible only by jquery ajax request. same thing if you need to write ajax form submit in laravel 6 then i will help you how you can pass data with ajax request and get on controller.

Pass form data to controller for JSON post to external API, Pass form data to controller for JSON post to external API I was starting to try to use $request as New Request and build out the values but I am not calling local This really is more of a generic Laravel framework question. src="https://fts. cardconnect.com:6443/itoke/ajax-tokenizer.html?css=%2Eerror{color:%20red;}"� {tip} If you return a PSR-7 response instance from a route or controller, it will automatically be converted back to a Laravel response instance and be displayed by the framework. Input Trimming & Normalization. By default, Laravel includes the TrimStrings and ConvertEmptyStringsToNull middleware

Comments
  • Seems that you forgot to add the _token field in the form, for csrf, or just add this route to the exceptions, but that is bad practice
  • @csrf is already added and also ajax setup in my app file
  • remove contentType: 'application/x-www-form-urlencoded', from ajax request
  • I have already tried all these thing's , but unable to send data to controller
  • One important things this view file is opening in **android webview **