jlrdw's avatar
Level 75

Jquery ajax post example

Just a quick example of posting with jquery ajax:

Setup your form normally as if you were not using ajax, and instead of submitting with a button, ajax will be used via this:

<a href="#" id="postjq">postjq</a>

Just for this example I will be updating only these two fields. I don't use blade, so adjust as needed to blade:

<input type="text" name="species" id="species" value="<?php echo $data->species; ?>">
// and 
<input type="checkbox" name="ocheck" id="ocheck" value="1"<?php echo ($data->ocheck == 1 ? ' checked' : ''); ?>>
// remember to put csrf token
<?php echo csrf_field(); ?> // or <?= csrf_field(); ?>

I picked a checkbox as some have trouble with a checkbox. In the database I use tinyint, and a 0 is not checked and a 1 means checked.

Here is an image of the whole form: https://imgur.com/vfHgjBS

Here is the script:

<script>
    $(function () {
        $("#postjq").click(function (event)
        {
            event.preventDefault();
            var $post = {};
            $post.petid = $('#petid').val();
            $post.species = $('#species').val();
            $post.ocheck = ($("#ocheck").prop("checked") == true ? '1' : '0');
            $post._token = document.getElementsByName("_token")[0].value
            $.ajax({
                url: 'petupdate',
                type: 'POST',
                data: $post,
                cache: false,
                success: function (data) {
                    alert('Your data updated');
                    return data;
                },
                error: function () {
                    alert('error handing here');
                }
            });
        });
    });
</script>

You can send the csrf token via a header, but it works the same using this line:

$post._token = document.getElementsByName("_token")[0].value

I used getElementsByName because the token has a name assigned, but no id.

For the quick example I used query builder. And I am not validating in the example, but if using eloquent and laravel validation it works the same. This example is to demo ajax, not validation. Learn normal posting and validation prior to using ajax.

Here is the controller code:

    public function petupdate(Request $request)
    {

        $petid = $request->input('petid');
        $species = $request->input('species');
        $ocheck = $request->input('ocheck');
        $postdata = [
            'species' => $species,
            'ocheck' => $ocheck
        ];
        DB::table('pets')
                ->where('petid', $petid)
                ->update($postdata);

        //return redirect(Session::get('areturn'));
    }

Notice that this line is commented out:

//return redirect(Session::get('areturn'));

that because with js ajax you redirect in js, something like:

window.location.href = "whatever location";

Here is a short video showing the whole thing: https://drive.google.com/file/d/1qWttpTHSkOwwSeuZQAHHa4uQwKCMVVzl/view?usp=sharing

And I only used a simple route:

    Route::post('petupdate', array('uses' => 'PetsController@petupdate'));
   // change to
    Route::put('petupdate', array('uses' => 'PetsController@petupdate'));
   // if put is needed

And in the ajax change

type: 'POST',
// to
type: 'PUT',

More information will be in a reply.

0 likes
9 replies
jlrdw's avatar
Level 75

A little more info on the checkbox:

Notice this in the script:

$post.ocheck = ($("#ocheck").prop("checked") == true ? '1' : '0');

I am getting the 0 or 1 assigned prior to posting. However in a regular post (non ajax) you have to figure out if a checkbox is checked a little different:

In HTML if a checkbox is checked a 1 or true is posted.

However

If a checkbox is not checked nothing is posted for that field. So you need to do a check for that and assign a 0 to be put in the database for a non checked checkbox. But there are several ways to do that. Just Google or Yahoo dealing with checkbox in a post.

Uploading a image with ajax:

I can, but don't for images I highly recommend using a good package for this. One I see on the forum a lot is http://image.intervention.io/ But there are others.

The reason:

Images need proper rotation, cropping, sizing, optimization, etc.

However, there are a couple of forum post on uploading an image already:

https://laracasts.com/discuss/channels/laravel/ajax-file-upload-with-form-data-laravel-53

and

https://laracasts.com/discuss/channels/requests/upload-image-with-ajax

But unless the images are web ready with a good program like Adobe photoshop I'd use a package.

And a final note, don't attempt ajax until you get everything working without ajax. There have been so many post on laravel where the person would state the ajax isn't working, only to find out it was a code error in form or controller or model, nothing to do with ajax.

Once all is properly working, then switch to ajax and remember to switch the redirect from controller to js.

In the example I used a simple alert, but a real app I'd put a hidden div with a nice message (The record was updated), then hide the div.

1 like
cuwa's avatar

lol, there are so many things about this and your other so called "guides" that are just no. I mean, do competent developers out there actually code like this? God, I hope not.

It's funny how you're actually proud of these "guides" too. I hope you realize we're all rolling our eyes when you advertise your "guides" on peoples' questions.

meme

2 likes
jlrdw's avatar
Level 75

@cuwa the guides are starter, for someone who never used jQuery ajax. It's just to show how it works.

I inform folks to learn and use validation.

I state:

This example is to demo ajax, not validation. Learn normal posting and validation prior to using ajax.

I mean there are new to laravel folks who doesn't know what a query string is.

Look at Jeffrey's basic PHP guide it's just a starter also.

The basic guy does illustrate an Ajax post.

When new to something, you show the basics of how it works first.

Later you work in other things like validation, etc.

Even in some of jeffrey's videos, he just covers the key point at times, not every detail in every video.

If he had to cover everything , there would be only one video, 1000 hours in length.

I know some of my guides have helped someone new to this at least understand how it works.

I will agree, it's not meant for someone who already knows how an ajax post or get works already.

Again:

This example is to demo ajax, not validation. Learn normal posting and validation prior to using ajax.

Just to comment on your comment:

I was blessed with a good career programming in java at a mid sized trucking company.

A very rewarding career.

Honest, comments like you made doesn't bother me.

I only posted the guide, because some ask about ajax who have never used it.

Perhaps on the last question, where it was clear that person had used it, it may have not been necessary. As I probably need to restrict it to someone who has never used it and needs to get a quick idea of how it works.

But good luck in whatever endeavours you pursue.

cuwa's avatar

Obviously it's for starters, but the code you show is just so bad. I'm not saying show high-level production code, but from your variable names to just how you do things is just bad.

Also, if you're going to show how to do an ajax request, at least show how to return a proper json response from the controller; not just nothing. Any developer I know knows to at least do that in the controller.

1 like
cuwa's avatar

I was blessed with a good career programming in java...

Maybe you should've just stuck with that, you're not doing anyone any favors here.

Honest, comments like you made doesn't bother me

Not meant to bother you. Merely informing other people that may not know better that most of what you do is not best practice or really just good at all. I would hate to work with developers that write code like this.

Yes I know it's meant to just show concepts, but come on, at least show good code...

1 like
jlrdw's avatar
Level 75

What like

<script>
    $(function () {
        $("#postjq").click(function (event)
        {
            event.preventDefault();
            var $post = {};
            $post.petid = $('#petid').val();
            $post.species = $('#species').val();
            $post.ocheck = ($("#ocheck").prop("checked") == true ? '1' : '0');
            $post._token = document.getElementsByName("_token")[0].value
            $.ajax({
                url: 'petupdate',
                type: 'POST',
                data: $post,
                cache: false,
                success: function (data) {
                    alert('Your data updated');
                    return data;
                },
                error: function () {
                    alert('error handing here');
                }
            });
        });
    });
</script>

Which is a typical example of a jquery post.

Or were you referring to:

$petid = $request->input('petid');

A typical laravel request. Someone new can learn requesting all later, I am showing only updating 2 fields. If you wish to cut down $request->input, fine. If you don't like it, put in a pull request to have it changed. But I like it.

Or

$post.ocheck = ($("#ocheck").prop("checked") == true ? '1' : '0');

Where I explain the checkbox.

Funny it works.

siangboon's avatar

@CUWA - @cuwa it may be better to show your "good practice" code and have others learn from you instead of just comment rudely like this....

i had checked your recent replies and you seems always commented more bad things than good about others, even @jeffreyway had advised you before and never show somethings good code ever.

I understand that there are many newbies or experienced programmers like to throw many simple questions or just want to get quick answers from here without any efforts on their own research, but whether they are incapable in learning or lazy or whatsoever as long as there are people like to spending their efforts and times to help, then better just let it be and save your own time to do better stuffs if you can't put your words/advice in a nice manner, we are not teachers nor their parents, they have their own rights to chose their pace and path of programming life not everyone want to be gurus like you.

jlrdw's avatar
Level 75

@CUWA Yes, you could have followed up with an advanced example perhaps with some validation. And maybe an eloquent example. In other words something that would help someone.

As a reminder, when just showing the basic example, I pointed out to learn and use validation.

Even in the beginning tutorials of many JS frameworks, they leave out such things as validation, usually that is for another lesson.

And as said, basic lessons don't cover everything

A simple example:

<?php
$tasks = $app['database']->selectAll('todos');
require 'views/index.view.php';

From the php course, no validation.

But of course he covers it well in the course on validation. So if you really want to help, add an advanced example, or write an advanced ajax post guide.

Folks new to jquery ajax would appreciate it.

I also looked at a couple of your other replies, where instead of helping you criticized someone.

Yes, I have come on strong in the past as well, but have calmed way down.

Jeffrey reminded me one time that:

We were all new to this stuff at one time.

I admit it is frustrating when one day a question:

How to put laravel on shared host?

And weekly the same question comes up.

I now try to answer and just give a good link to how, as example:

See my 4th answer here:

https://laracasts.com/discuss/channels/laravel/next-issue-fonts-and-images-arent-visible

I give an image of folder structure, a guide to follow, etc. You are correct about one thing, most are not going to search for a previous answer.

drldejacto's avatar

Hi there, I'm having this error:

Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message
 protected function methodNotAllowed(array $others)
    {
        throw new MethodNotAllowedHttpException($others);
    }

This is my jquery

<script type="text/javascript">
  $(document).ready(function(){
      $('#saveChanges').on('click',function(e){
          e.preventDefault();
          var $formData = {};
          $formData.id = $('#edit_id').val();
          $formData.document_number = $('#edit_document_number').val();
          $formData.ors_no = $('#edit_ors_no').val();
          $formData.dv_no = $('#edit_dv_no').val();
          $formData.amount = $('#edit_amount').val();
          $formData.remarks_action = $('#edit_remarks').val();
          $formData.reference_num = $('#reference_num').val();
          $formData.assigned_to = $('#assigned_to').val();
          $formData.doc_status = $('#doc_status').val();
          $formData.date_deadline = $('#edit_date_deadline').val();
          $formData._token = $('input[name="_token"]').val();


          $.ajax({
              url : '{{ route('document.editReceived') }}',
              type : 'get', 
              data: $formData,
               success:function(data){
               
            }
          });
      });
  });
</script>

My Controller

 public function editReceived(Request $request){

      dd($request);
}

My routes

Route::get('/editReceived','DocumentController@editReceived')->name('document.editReceived');

Please or to participate in this conversation.