9

I am trying to understand more about how to save data from ajax request into the database on laravel, The data in this case is raw (JSON FORMATTED) data just to see how it works it works fine if I dont add this to the code (note the saving into the data base)

the saving part

 $input = Input::get('name');
 $json = new JsonTest;
 $json->json = $input;
 $json->save();

it works fine but when I have this part from above in the code (the saving part) its gives an error

   The GET method is not supported for this route. Supported methods: POST.

so how can I save the text area into the data base. the data base database

web.php

 Route::post('/customer/ajaxupdate', 'AjaxController@updateCustomerRecord')- 
 >name('jsonTest');

The Controller

public function updateCustomerRecord(Request $request)
{

    if(request()->ajax()){

        $input = Input::get('name');
        //$input = $request->all();
        $json = new JsonTest;
        $json->json = $input;
        $json->save();

        return response()->json(['status' => 'succes', 'message' => 'saved in database']);

    } else {

        return response()->json(['status' => 'fail', 'message' => 'this is not json']);

    }

}

The blade

 <!DOCTYPE html>
 <html lang="en">
<head>
<title>JavaScript - read JSON from URL</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<meta name="csrf-token" content="{{ csrf_token() }}" />
</head>

<body>
<textarea  oninput="myFunction()" id="input" name="input" style="height: 
500px;width: 500px">
</textarea>

<script>
const warning = 'This json is not correctly formatted';
const text = {status: "failed", message: "this is not correct json format"};

$.ajaxSetup({
    headers: {

        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')

    }
});

function myFunction(){

    let input = document.getElementById("input").value;

    try {
        let id = JSON.parse(input);
        if (id && typeof id === "object") {
            $.ajax({
                method: 'POST', // Type of response and matches what we said in the route
                url: '{{ route('jsonTest') }}', // This is the url we gave in the route
                data: {'id' : id}, // a JSON object to send back
                success: function(response){ // What to do if we succeed
                    console.log(response);
                },
                error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
                    console.log(JSON.stringify(jqXHR));
                    console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
                }
            });
        }
    }
    catch (e) {
        console.log(warning);
        console.log(text);
    }
    return false;
}
</script>

</body>
</html>
HashtagForgotName
  • 651
  • 1
  • 7
  • 23
  • Can you check your network tab in your dev tools console to see what request is getting sent? – Peter Mar 21 '19 at 14:22
  • It says json can not be NULL – HashtagForgotName Mar 21 '19 at 15:50
  • Where are you seeing the "GET method is not supported ..." error? – Peter Mar 21 '19 at 18:03
  • When you go to network and then click on the route from the ajax it opens another webpage with GET method is not supported – HashtagForgotName Mar 21 '19 at 19:33
  • OK, that's because your are trying to view the route in your web browser (which is a GET request). So the actual error is the `JSON cannot be null` ... where are you seeing this error? – Peter Mar 21 '19 at 20:08
  • json cannot be null is from the data base the table is called also json. when I 'dd()' the input its is null so the error is coming from that the data is not correctly sended to the controller and then when its trying to put the data into the data base its giving back and json (table of data base) error json is null – HashtagForgotName Mar 21 '19 at 23:25
  • Check your network tab to see if the data is getting sent in your ajax call. – Peter Mar 21 '19 at 23:55

4 Answers4

8

I faced the same problem once, Where the issue resides auto redirection from http to https. So the url I changed to https itself while calling api.

Nidhin
  • 1,818
  • 22
  • 23
3

It looks like you are not including the name key in your POST data. Try this:

$.ajax({
    method: 'POST', // Type of response and matches what we said in the route
    url: '{{ route('jsonTest') }}', // This is the url we gave in the route
    data: {'name' : 'testing'}, // <-- this is your POST data
    success: function(response){ // What to do if we succeed
        console.log(response);
    },
    error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
        console.log(JSON.stringify(jqXHR));
        console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
    }
});
Peter
  • 1,615
  • 1
  • 9
  • 17
1

If you are using client app like insomnia and postman don't forget to add

Accept application/json

to the header.

Mebatsion Sahle
  • 409
  • 2
  • 9
0

my url like "/users/add/comment/" I removed the last / in the URL and it does work.

But It works !!!

nafischonchol
  • 104
  • 1
  • 9