makri aymen abderraouf
makri aymen abderraouf

Reputation: 828

I can't retrieve my data from request AJAX in Laravel

Here the code of my Blade and it works and send the request, but I can't retrieve the data from the AJAX.

Javascript

function addUser() {
    var name=document.getElementById("name").value;
    var email=document.getElementById("email").value;
    var password=document.getElementById("password").value;

    $.ajaxSetup({
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
    });
    $.ajax({
        type:'POST',
        url:'addUser',
        data: {name:name,email:email,password:password,},
        success:function(data) {
            $("#msg").html(data.msg);
        },
        error: function (data, textStatus, errorThrown) {
            console.log(data);
        },
        contentType: false,
        processData: false,
    });
}

Controller

public function index(Request $request) {
    $msg=User::create([
        'name' => $request->name,
        'email' => $request->email,
        'password' => bcrypt( $request->password),
    ]);
    return response()->json(array('msg'=> $msg), 200);
 }

Upvotes: 2

Views: 257

Answers (1)

Nathan
Nathan

Reputation: 1223

Remove

contentType: false,
processData: false,

processData by default is set to true and assumes that the data passed is an object, setting it to false will prevent the default parse behavior - which you do not want! This may be good in cases where want to send raw JSON, but this is different to form data.

contentType is also passed as application/x-www-form-urlencoded by default. If you set contentType to false, you are not setting any content header! So by removing both values you will have the correct defaults to successfully send the ajax call.

Upvotes: 2

Related Questions