Elie Morin
Elie Morin

Reputation: 1514

Add data to MySQL from AJAX post request in Laravel controller

I know a lot of people are resolving this issue through jQuery, but I'm not familiar with that.

The problem is that I try to send data to MySQL using a form in html, retrieving this data with javascript, sending them to php with ajax then I try to "save" them with my controller. I got this error:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'first_name' cannot be null

There is the code of my ajax.js:

function ajaxSaveAddClient() {
var first_name = document.getElementById("first_name").value;
var last_name = document.getElementById("last_name").value;
var phone = document.getElementById("phone").value;
var cellphone = document.getElementById("cellphone").value;
var email = document.getElementById("email").value;
var city = document.getElementById("city").value;
var stock = document.getElementById("stock").value;
var source = document.getElementById("source").value;

var newClient = new Array();
newClient["first_name"] = first_name;
newClient["last_name"] = last_name;
newClient["phone"] = phone;
newClient["cellphone"] = cellphone;
newClient["email"] = email;
newClient["city"] = city;
newClient["stock"] = stock;
newClient["source"] = source;

var token = document.getElementById("csrf_token").content;
var requestSaveAddClient = new XMLHttpRequest();
requestSaveAddClient.onreadystatechange = function() {
    console.log("orsc: ", requestSaveAddClient.readyState);
};
console.log("Before open: ", requestSaveAddClient.readyState);
requestSaveAddClient.open( "POST", "newclient", true);
requestSaveAddClient.setRequestHeader("X-CSRF-TOKEN", token);
requestSaveAddClient.send(newClient);

There is my route.php:

    Route::post('newclient', 'DashController@store');

There is my DashController.php:

public function store(Request $request)
{
    $client = new Client;
    $client -> user_id      = Auth::user()->id;
    $client -> first_name   = Request::get('first_name');
    $client -> last_name    = Request::get('last_name');
    $client -> phone        = Request::get('phone');
    $client -> cellphone    = Request::get('cellphone');
    $client -> email        = Request::get('email');
    $client -> city         = Request::get('city');
    $client -> stock        = Request::get('stock');
    $client -> source       = Request::get('source');
    $client -> save();
    die();
}

dahsboard.blade.php :

                <div>
                <table id="addClientTable" name="addClientTable" class="addClientTable">
                    <meta name="csrf-token" id="csrf_token" content="{{ csrf_token() }}">
                    <tr>
                        <th class="rightCellCT">
                            NOM :
                        </th>
                        <th class="centerLargeInputCT">
                            <input id="last_name" type="text"/>
                        </th>
                        <th class="rightCellCT">
                            TÉLÉPHONE :
                        </th>
                        <th class="centerSmallInputCT">
                            <input id="phone" type="text"/>
                        </th>
                        <th class="rightCellCT">
                            VILLE :
                        </th>
                        <th class="centerLargeInputCT">
                            <input id="city" type="text"/>
                        </th>
                        <th class="rightCellCT">
                            STOCK :
                        </th>
                        <th class="centerSmallInputCT">
                            <input id="stock" type="text"/>
                        </th>
                    </tr>
                    <tr>
                        <td class="rightCellCT">
                            PRÉNOM :
                        </td>
                        <td class="centerLargeInputCT">
                            <input id="first_name" type="text"/>
                        </td>
                        <td class="rightCellCT">
                            CELLULAIRE :
                        </td>
                        <td class="centerSmallInputCT">
                            <input id="cellphone" type="text"/>
                        </td>
                        <td class="rightCellCT">
                            COURRIEL :
                        </td>
                        <td class="centerLargeInputCT">
                            <input id="email" type="text"/>
                        </td>
                        <td class="rightCellCT">
                            SOURCE :
                        </td>
                        <td class="centerSmallInputCT">
                            <input id="source" type="text"/>
                        </td>
                    </tr>
                </table>
            </div>

Upvotes: 0

Views: 794

Answers (2)

Joseph Waelchli
Joseph Waelchli

Reputation: 60

The problem is that the XmlHttpRequest send method cannot use an array like you are passing it, so the params you try to send to do not make it to the controller.

A simple alternative might be using the FormData object. A quick example might look like this:

var token = document.getElementById("csrf_token").content,
    requestSaveAddClient = new XMLHttpRequest(),
    newClient = new FormData();

requestSaveAddClient.open( "POST", "newclient", true);
requestSaveAddClient.setRequestHeader("X-CSRF-TOKEN", token);
newClient.append("first_name", first_name);
//etc...
requestSaveAddClient.send(newClient);

I would also strong suggest you do a bit more research into using jQuery or something like it to help you write the scripts for your site, there's a bit more of a learning curve but it will save you a lot of time and heart ache in the future and will make you a better developer overall.

Upvotes: 1

Mike Barwick
Mike Barwick

Reputation: 5367

Change Request::get('some_name') to Request::input('some_name');. Do this for all your inputs in the store method.

In fact, I'd clean that function up quite a bit...like below. I won't touch on the actual javascript. It's not good either.

$request->merge([
    'user_id' => Auth::user()->id
]);

$task = Client::create($request->all());

Upvotes: 0

Related Questions