emy
emy

Reputation: 7

Returning JS var from ajax request Laravel

I keep reading about this but still don't' get it

I need to send a variable to controller. The form data is being send but not the js variable

JS

$('#form').submit(function(e){
    e.preventDefault();
    var hash = '9999';
    $('#form').append('hash', hash);
    var form_input = $('#form').serialize()+'&_token={{csrf_token()}}';

$.ajax({
     url : '{{route('pag_submit')}}',
     type: "POST",
     data: form_input,
     success : function (data) {
      if (data.success == 1){
         alert (data.msg);
      }
     },
     error   : function ( jqXhr, json, errorThrown ) {
      var errors = jqXhr.responseJSON;
      var errorsHtml= '';
      $.each( errors, function( key, value ) {
           errorsHtml += '<li>' + value[0] + '</li>';
      });
       toastr.error( errorsHtml , "Error " + jqXhr.status +': '+ errorThrown);
                    }
                });
       });  

CONTROLLER

public function pag(Request $request){

        $name= $request->name;
        $date= $request->date;
        $test = $request->test;
        $hash = $request->hash;

        return ['success'=>1, 'msg'=> [$name, $date, $test, $hash], 'response' => $this->payment_success_html()];
    }

Only hash returns as null, can someone help me with this?

Upvotes: 0

Views: 39

Answers (1)

Nick Synev
Nick Synev

Reputation: 387

Try to append input to a form

$('#form').append('<input type="hidden" name="hash" value=' + hash + '/>');

Upvotes: 2

Related Questions