Monday, March 6, 2017

Submit form and call Ajax on click

I want to add something to database using Ajax. I have a link which submits the form and then Ajax call should work, but it's not. I use this same Ajax call on different page, but in that form I'm using simple button with type submit. But on this page, I want to submit with ...

This is the form

{!! Form::open(['id' => 'ajax-form', 'style' => 'float:right']) !!}
  <input type="hidden" name = "idUser" id="idUser" value="">
  <input type="hidden" name = "idCampaign" id="idCampaign" value="">
  <a class="fa fa-bookmark fa-2x" onclick="document.getElementById('ajax-form').submit();" aria-hidden="true" href="javascript:{}" style="color:#fd8809"></a>
{!! Form::close() !!}

This is the Ajax:

$("#ajax-form").submit(function(event) {
    event.preventDefault();
    var form = $(this);
    $.ajax({
        type: "post",
        url: "",
        dataType: "json",
        data: form.serialize(),
        success: function(data){
            if(data.status == 'failedd'){
              swal("Error!", "You have already added this campaign to favorites! If you want to remove it, go to your Favorites list page", "error")
            }
            else{
            swal("Success!", "You added the campaign "+ data.idCampaign + " to favorites!", "success")
          }
        },
        error: function(data){
            swal("Error!", "error")
        },
        complete: function (data) {
     }
    });
});

When I click on this link, it redirects me to another page which throws: MethodNotAllowedHttpException.



via harunB10

Advertisement