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

断了今生、忘了曾经 提交于 2021-01-04 07:46:25

问题


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.


回答1:


$("#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'
];
  1. if want

then add in head

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

and in script

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



回答2:


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




回答3:


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')
        }
    });
    


来源:https://stackoverflow.com/questions/55180403/how-to-post-laravel-form-data-to-controller-using-ajax-in-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!