0

I have a form and a save button. On click, I want to post all that data from the form to my Controller using Ajax. I could have done that using Input::all(), but I'm trying to avoid my page to refresh.

I want to be able to access those form data, just like input::all(), but using Ajax instead.

How would one go about and implement something like this ?


I've tried

JS

$('.saveRateLimitBTN').click(function (event) {

    var url = '{{env("APP_URL")}}{{$cpe_mac}}'+'/device/'+'{{$device_mac}}'+'/rate/update';

    var inputs = {};
    $("#editRateLimitForm :input").each(function() {
        inputs[$(this).attr("name")] = $(this).val();
    });

    $.ajax({
        url: url,
        type: 'PUT',
        dataType: 'json',
        data: inputs,
        success: function (data, textStatus, xhr) {
            console.log(data);
        },
        error: function (xhr, textStatus, errorThrown) {
            console.log('PUT error.', xhr, textStatus, errorThrown);
        }
    });

});

DeviceController > updateRate() function

public function updateRate(){

        dd('Here'); // This never get run.
}

Route

Route::put('{cpe_mac}/device/{device_mac}/rate/update',['as'=>'device.update', 'uses'=>'DeviceController@updateRate']);

Form (Blade Syntax)

{!! Form::open(array('url' => '/'.$cpe_mac.'/device/'.$device_mac.'/rate/update', 'class' => 'form-horizontal', 'role' =>'form','method' => 'PUT', 'id' => 'editRateLimitForm')) !!}

        <span class="pull-left">
            <div class="col-sm-6">
                <p>Downlink </p>
                <select type="text" id="rateDownSelect" class="form-control" name="max_down" >

                    @foreach ($rate_limit as $key => $value)
                    <option value="{{$value or ''}}"
                    >{{$value or ''}} Kbps</option>
                    @endforeach
                </select>
            </div>
            <div class="col-sm-6">
                <p>Uplink</p>
                <select type="text" id="rateUpSelect" class="form-control" name="max_up" >
                    @foreach ($rate_limit as $key => $value)
                    <option value="{{$value or ''}}">{{$value or ''}} Kbps</option>
                    @endforeach
                </select>
            </div>
        </span><br>


        {!! Form::hidden('cpe_mac', $cpe_mac)!!}
        {!! Form::hidden('device_mac', $device_mac)!!}



        <span class="pull-right">
            <button class="saveRateLimitBTN btn btn-xs btn-info pull-right" type="button">Save</button>
        </span>


{!! Form::close();!!}

Result

XMLHttpRequest cannot load http://localhost/000D6751560C/device/0800277B6BDE/rate/update. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8888' is therefore not allowed access.

3 Answers 3

2

Serialize the form like below to access all types of form field values.

$( "form" ).on( "submit", function( event ) {
  event.preventDefault();
  console.log( $( this ).serialize() );
  // Your Ajax here !
});

Useful URLs:
https://api.jquery.com/serializeArray/
https://api.jquery.com/serialize/

Sign up to request clarification or add additional context in comments.

10 Comments

I've tried $( "#editRateLimitForm" ).on( "submit", function( event ) { event.preventDefault(); console.log( $( this ).serialize() ); // Nothing printing out }); Nothing is printing out ! :(
do you have form tag first ? please share html code as well.
test by adding input type=submit button rather keeping button
Check the jsfiddle url - jsfiddle.net/0br4qcgg/1 will see rest after 4 - 5 hours :) its 1.10 am here
Change the button to type=submit, I saw the serialize data now. How do I get them to spit out an array/object instead ?
|
1

@ihue Instead of using .serialize() which I see you used in the other comments, use .serializeArray() to get the data object for your PUT request. But the other problem here, based on your error is that you can't send ajax requests from one domain to another domain. It says you are on localhost:8888 and are sending request to localhost, which is a different domain.

Try changing the AJAX request to go to http://localhost:8888/[yourURL] instead of using the relative /[yourURL] and see if that makes a difference.

If that doesn't work you need to allow CORS (Cross-Origin Request Sharing) within your Laravel API. Here is some information about CORS http://www.html5rocks.com/en/tutorials/cors/ and here is a Laravel package to help take care of it https://github.com/barryvdh/laravel-cors

3 Comments

Thanks for updating, I will keep looking at your issue
see my edit - based on the error you're getting this is a CORS problem
Thank-you for your answer ! I'll try those suggestions now. My function in my controller doesn't seem to get execute. Do you know why ?
0

You APP_URL is probably set to http://localhost but your application's current url is http://localhost:8888 . Due to this, it is being treated as cross domain request for which you need to allow cross domain requests by adding this your htaccess file:

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

Other solution, which you should ideally do is to change your AJAX url like this:

var url = '{{ url($cpe_mac."/device/".$device_mac."/rate/update") }}';

This will define the AJAX url using the url you are using currently to access your website.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.