Hướng dẫn javascript in laravel controller

I'm getting the error of MethodNotAllowedHttpException when I run the below code:

Nội dung chính

  • How to pass value from JavaScript to controller in Laravel?
  • Can we use JavaScript in laravel controller?
  • How to pass data using Ajax in Laravel?
  • How to pass data from view to controller using Ajax Laravel?

<h2>Temp Form</h2>
<form method="post" action="" role="form">
  <input type="hidden" name="_token" value="{{ csrf_token() }}">
  <div class="panel panel-default ">
    <div class="container">
      <div class="panel-body">
        <div class="form-group">
          <label for="firstName">First Name *</label>
          <input name="fname" type="text" class="form-control" id="firstName" placeholder="Enter First Name" required>
        </div>
        <div class="form-group">
          <label for="lastName">Last Name *</label>
          <input name="lname" type="text" class="form-control" id="lastName" placeholder="Enter Last Name" required>
        </div>
        <div class="form-group">
          <label for="qualification">Qualification *</label>
          <input name="qualification" type="text" class="form-control" id="qualification" placeholder="BE, MCA, MBA Etc." required>
        </div>
        <div class="form-group">
          <label for="emailAddress">Email address *</label>
          <input name="email" type="email" class="form-control" id="emailAddress" placeholder="Enter Email" required>
        </div>
        <div class="form-group">
          <label for="contactmessage">Message</label>
          <textarea name="desc" type="text" class="form-control" id="contactmessage" placeholder="Message" rows="2"></textarea>
        </div>
        <input type="submit" id="add" class="btn btn-primary" onclick="addUpdateData(id)" value="Add"></button>
      </div>
    </div>
  </div>
</form>

Code for routes.php :

Route::post('welcome/addupdate','[email protected]');

code for controller :

 public function addUpdateData(Request $req)
 {
    $id = $req->input('id');
    if($id=="add")
    {
        $bs = new Basicusers;

        $bs->fname = $req->fname;
        $bs->lname = $req->lname;
        $bs->qualification = $req->qualification;
        $bs->email = $req->email;
        $bs->desc = $req->desc;

        $bs->save();

        return "Data Successfully Added";
    }
  }

What I want is, when user clicks on add button, value in variable data add is passed, and on controller, I will check value for variable and if its add, than I will perform add operation.

meanwhile if the user click on edit button which is provided below in form, that row will be filled in form elements and the add button is changed to update button and value of variable data will be now update and I want to perform update operation...

I'm getting error when I am passing data using POST method moreover I don't know how to get data passed using POST method..

for GET method I am using $id = Input::get('id'); method and its working

Here is JavaScript Function :

function addUpdateData(data) {
  $(function() {
    $.ajax({
      method: "post",
      url: "welcome/addupdate",
      data: {
        id: data
      },
      success: function(response) {
        alert(response);
      }
    });
  });
}

I need to send data via JS to a Laravel controller on a button click. I'm not using any form because the data is being created dynamically.
Every time i try to send the data, i get an Internal Server Error (500), but unable to catch that exception in the controller or the laravel.log file.

Here's what i'm doing:

Route:

Route::post('section/saveContactItems', '[email protected]');

Controller:

public function saveContactItems($id, $type, $items, $languageID = "PT"){ ... }

JS:

$('button').on("click", function (evt) {

    evt.preventDefault();

    var items = [];
    var id = $("#id").val();
    var languageID = $("#languageID").val();
    var data = { id: id, type: type, items: JSON.stringify(items), languageID: languageID };

    $.ajax({
        url: "/section/saveContactItems",
        type: "POST",
        data: data,
        cache: false,
        contentType: 'application/json; charset=utf-8',
        processData: false,
        success: function (response)
        {
            console.log(response);
        }
    });
});

What am i doing wrong? How can i accomplish this?

UPDATE: Thanks to @ShaktiPhartiyal's answer (and @Sanchit's help) i was able to solve my issue. In case some else comes into a similar problem, after following @Shakti's answer i wasn't able to access the data in the controller. So, i had to stringify the data before sending it to the server:

data: JSON.stringify(data),

How to pass value from JavaScript to controller in Laravel?

var data = { value : value }; $. ajax({ type: "POST", url: '/session/storeValue', data: data, headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]'). attr('content') }, success: function() { console. log("Value added " + value); } });

Can we use JavaScript in laravel controller?

Laravel does not require you to use a specific JavaScript framework or library to build your applications. In fact, you don't have to use JavaScript at all.

How to pass data using Ajax in Laravel?

Import jquery library in your view file to use ajax functions of jquery which will be used to send and receive data using ajax from the server. On the server side you can use the response() function to send response to client and to send response in JSON format you can chain the response function with json() function.

How to pass data from view to controller using Ajax Laravel?

pass data from ajax to controller in laravel.

Change your route method to "GET".

In your controller method signature: Change request class to Request..