Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

theUnforgiven's avatar

Laravel, Ajax, Post updating

Hi all,

I'm a newbie when it comes to ajax and jQuery, but having a go at updating a row in my database on form submit which is returning a 500 Internal Server Error

Here's the form:

{{ Form::model($product, ['method' => 'PUT', 'route' => ['admin.products.update', $product->id], 'class' => 'form-horizontal','id' => 'editForm', 'files' => true]) }}



            Product Name
                 
                     name }}">
                 
            



            <div class="form-group">
            <div class="col-sm-2">Category</div>
                 <div class="col-lg-3">
                 <?php $selected_category = ($product->slug ?: null) ?>
                    {{ Form::select('category_id', $category, $selected_category, ['class' => 'form-control'])}}

                 </div>
            </div>



            @foreach($options as $option)
               id }}" id="option_id">
               Size
               
                   size; ?>
                   {{ Form::select('size', $sizes, $selected_size, ['class' => 'form-control', 'id' => 'size'])}}
               

              Colour
               
               colour; ?>
                   {{ Form::select('colour', $colours, $selected_colour, ['class' => 'form-control', 'id' => 'colour'])}}
               
               Stock
                
                    stock }}" id="stock">
                
            @endforeach
           



            <div class="form-group">
            <div class="col-sm-2">Status</div>
                 <div class="col-lg-3">
                  <?php $options = array('Inactive', 'Active'); ?>
                  {{ Form::select('status', $options, Input::old('status'), array('class' => 'form-control')) }}
                 </div>
            </div>

            <div class="form-group">
                 <div class="col-lg-3">
                     <button class="btn btn-success">Update</button>
                 </div>
            </div>

   {{ Form::close() }}

Here's the ajax

 $("document").ready(function(){
        var base_url = 'http://localhost';

        $("#editForm").submit(function(e){
            e.preventDefault();
            var option_id = $("input#option_id").val();
            var size = $("input#size").val();
            var colour = $("input#colour").val();
            var stock = $("input#stock").val();

            var dataString = 'size='+size+'&amp;optionID='+option_id+'&amp;stock='+stock+'&amp;colour='+colour;
            $.ajax({
                type: "POST",
                url : base_url + "/admin/updateProductOption",
                data : dataString,
                success : function(data){
                    console.log(data);
                }
            },"html");

    });
 });//end of document ready function

here is the method to handle the update.

public function updateProductOption()
    {
        $data = Input::all();
        if(Request::ajax())
        {
            $id = Input::get('id');
            $option = Options::where('id', $id)->first();
            $option->size = $data['size'];
            $option->colour = $data['colour'];
            $option->stock = $data['stock'];
            $option->update();
        }
    }

But it's not updating and throwing a 500 error. Anyone have any idea's/advice help to give on this please ?

0 likes
37 replies
theUnforgiven's avatar

It's only showing optionId of 30 even if i edit 31 but it looks like I'm going to need to a put each in a form to update each row seperately.

abhimanyusharma003's avatar

dd(Input::all()) or return Input::all(); in your method to see what you are getting in response ?

public function updateProductOption()
    {
       return Input::all();
    }

Check the url in network tab

And what if you do it like this

var dataString = 'size='+size+'&optionID='+option_id+'&stock='+stock+'&colour='+colour;
theUnforgiven's avatar

In both network tab and on screen

[{"id":1,"name":"New In","slug":"new-in"},{"id":2,"name":"Dresses","slug":"dresses"},{"id":3,"name":"Tops","slug":"tops"},{"id":4,"name":"Play Suits &amp; Jumpsuits","slug":"playsuits-jumpsuits"},{"id":5,"name":"Coats &amp; Jackets","slug":"coats-jackets"}]

Which is just a list of categories. Which is not right.

bashy's avatar

In the network tab of your browser oOn the 500 error request, press on that and check the response, it should have an error if you have it on.

If you get a response like the above, it sounds like it's doing what you asked it to do?

theUnforgiven's avatar

In the network tab i get this:

<pre class='xdebug-var-dump' dir='ltr'>
<b>array</b> <i>(size=4)</i>
  'size' <font color='#888a85'>=&amp;gt;</font> <small>string</small> <font color='#cc0000'>'undefined'</font> <i>(length=9)</i>
  'optionID' <font color='#888a85'>=&amp;gt;</font> <small>string</small> <font color='#cc0000'>'30'</font> <i>(length=2)</i>
  'stock' <font color='#888a85'>=&amp;gt;</font> <small>string</small> <font color='#cc0000'>'1'</font> <i>(length=1)</i>
  'colour' <font color='#888a85'>=&amp;gt;</font> <small>string</small> <font color='#cc0000'>'undefined'</font> <i>(length=9)</i>
</pre>

Which is only getting the optionID of 30 even though I set the optionID of 31

abhimanyusharma003's avatar

If i'm not wrong there can be only one id on a page, so it is catching the first ID only form that input area.

theUnforgiven's avatar

yes, but i need it to be like 4 form inside a form that would grab the id of the form then update the row.

abhimanyusharma003's avatar

use var dataString = $(this).serializeArray(); or make input name in an array like this, don't catch the input area with their id

{{ Form::select('size['.$option->id.']', $sizes, $selected_size, ['class' => 'form-control', 'id' => 'size'])}}

I hope this helps.

theUnforgiven's avatar

so then how would i captcha that data and post to PHP so i can save and update the row corresponding to the optionID set.

theUnforgiven's avatar

I need to be able to click a button at the side of each row like shown here - http://cl.ly/image/112v1Y2V0C08 then will then send ajax request to update the new value in the database, if nothing is changed then it doesn't need to do anything. It also needs to do this request without refreshing the page.

So my question is how would I do this based on my 1st post?

bashy's avatar

Why don't you POST form data instead of query strings?

var jqxhr = $.post("/admin/updateProductOption", { product_id : product_id }, function() {
     //
})
.done(function() {
    var json_response = jQuery.parseJSON(jqxhr.responseText);

    if (json_response.error === true)
    {
        // show error
    }
    else if (json_response.success === true)
    {
        // do something to the row or button
        $("#product_id_" + product_id).remove();
    }
})
.fail(function(response, status, xhr) {
     // show failed response
})
.always(function() {
     btn.button('reset')
});
2 likes
theUnforgiven's avatar

Think I already tried that, but because the image i posted has a foreach and different options id from the product id this wont work @bashy! I;m still on with the thing I was doing before, i cant get this damn thing to work! Getting pissed off too.....

bashy's avatar

If you can get the values for the query string, you can get them for form-data. Just add variables for each one instead of doing ?foo=&bar= you do foo = foo bar = bar

theUnforgiven's avatar

I'm not sure I follow here @bashy, you see the image put a bout 3/4 posts back, I need to click that button so it updates the new values to the db without refreshing the page based on it's optionID

bashy's avatar

I did, you can copy the code I put and make it pick out the values for that particular one and update with with AJAX. If you don't understand JavaScript/JQuery, it will be hard to know how to do it.

Grabbing values from inputs is difficult if it's not built right.

theUnforgiven's avatar

So this yu put:

var jqxhr = $.post("/admin/updateProductOption", { product_id : product_id }, function() {
     //
})
.done(function() {
    var json_response = jQuery.parseJSON(jqxhr.responseText);

    if (json_response.error === true)
    {
        // show error
    }
    else if (json_response.success === true)
    {
        // do something to the row or button
        $("#product_id_" + product_id).remove();
    }
})
.fail(function(response, status, xhr) {
     // show failed response
})
.always(function() {
     btn.button('reset')
});

I should put where?

bashy's avatar

Well that's just the request part of the AJAX so use that where you do the request to the route.

You'll need to get the values (product_id etc etc etc) of all the fields you want to get and send in the POST data.

Also make sure you have the "on click"

$(document).on('click', '.update-product-btn', function() {
    var btn = $(this)
    var product_id = $(this).data("product-id")

    btn.button('loading')

    // request stuff here
});

See the $(this).data('product-id') part? That is where you need to set your form fields you'll be posting. You can use another method of getting them since you have form inputs?

theUnforgiven's avatar

Right ok think I understand(ish) let me have a go with this.

theUnforgiven's avatar

Tried it like this:

$(document).on('click', '.update-product-btn', function() {
    var btn = $(this);
    var product_id = $(this).data("product-id");
    var option_id  = $(this).data('option_id');

    // request stuff here
    var jqxhr = $.post("/admin/updateProductOption", { product_id : product_id }, function() {
         //
    })
    .done(function() {
        var json_response = jQuery.parseJSON(jqxhr.responseText);

        if (json_response.error === true)
        {
            // show error
        }
        else if (json_response.success === true)
        {
            // do something to the row or button
            $("#product_id_" + product_id).remove();
        }
    })
    .fail(function(response, status, xhr) {
         // show failed response
    })
    .always(function() {
         btn.button('reset')
    });
});

And does nothing not even in console.

bashy's avatar

Debug it with console.log() and alert() in places.

Probably this part, you need a class="update-product-btn", or change it accordingly.

Also data() is the data-name="" part of elements. Probably don't want that. I just used that in my product since I could.

theUnforgiven's avatar

@bashy, tried a different more simpler solution like so:

$(document).ready(function(){

        $('.update').click(function()
        {
            var url             = "http://clothing.app/updateProductOption";
            var $post             = {};
            $post.id            = $(this).attr('rel');
            $post.size            = $('#size_' + $post.id).val();
            $post.colour        = $('#colour_' + $post.id).val();
            $post.stock            = $('#stock_' + $post.id).val();
            $.ajax({
                type     : "POST",
                url         : url,
                data     : $post,
                dataType : "JSON",

            success : function(json){
                console.log(json);

            },
            error : function(xhr, status)
            {
                alert(JSON.stringify(json));
            }
            });
        });
     });

But in Chrome console i get this error:

Object {message: "Updated"} edit/17:161
Resource interpreted as Document but transferred with MIME type application/json:

Any idea's what this is? and why it's redirecting to a page that i haven't specified

bashy's avatar

The response has a content-type of application/json but it should be application/javascript?

theUnforgiven's avatar

I've not set any content type anywhere so not sure what you mean there.

bashy's avatar

Responses are application/json by default?

JSON

{message: "Updated"}
theUnforgiven's avatar

but it should be application/javascript you said not sure what your meaning here i know its json be default but why is this error showing? Based on this new JS i did

Next

Please or to participate in this conversation.