0

I have a problem here. I am developing my web application and I want it to connect to my API through ajax. I am trying to send an image to my api through ajax from my form in the client side, which is the web.

So, here's my form in the client side..

{{ Form::open(['enctype' => "multipart/form-data", 'id' => 'addplant', 'method' => 'POST', 'files' => true, 'class' => 'col s12']) }}
  {{ csrf_field() }}

    <div class="row" style="margin-top:10%;">
      <div class="col s12  center">
        <img class="circle" id="image_url" src=""></a>
        {!! Form::file('image_url', array('id' => 'image', 'class' => 'form-control')) !!}
      </div>
    </div>
    <div class="row">
      <div class="input-field col s6">
        {{ Form::text('herbal_name', null, array('id' => 'herbal_name', 'class' => 'form-control validate')) }}
        {{ Form::label('herbal_name', 'Herbal Name') }}
      </div>
      <div class="input-field col s6">
        {{ Form::text('scientific_name', null, array('id' => 'scientific_name', 'class' => 'form-control validate')) }}
        {{ Form::label('scientific_name', 'Scientific Name') }}
      </div>
    </div>
{{ Form::submit('Add plant', array('class' => 'btn btn-primary right add')) }}
{{ Form::close() }}

Here's my ajax, still in the client side

<script type="text/javascript">
 $(".add").click(function() {
    $.ajax({
        url: 'http://127.0.0.1/identificare_api/public/api/plants',
        data: new FormData($("#addplant")[0]),
        type: "POST",
        success: function( msg ) {
            console.log(msg);
        },
        error: function(){
            alert('pangit');
        }
    });
 });
</script>

EDIT: and in my api, I just have this one

return json_encode($request->file('image_url'));

What am I missing here? Did I missed something?

UPDATE: I tried to apply the answer of @bfcior but when I try to console.log(base64img), it will return this very long string and it's longer than you expected.

click for image

Carriane Lastimoso
  • 233
  • 1
  • 2
  • 7

3 Answers3

0

I'm not entirely sure if this is the issue but aren't you supposed to be using a button instead of a submit? I'd imagine using a submit is preventing the ajax from working because the form is being submitted to the server for processing.

EDIT: What happens when you click the submit button? Telling us will help stackoverflow users diagnose the problem.

VenomRush
  • 1,622
  • 3
  • 15
  • 25
  • still no go when changing the submit to button. Anyway, when I click the submit button, it returns null. – Carriane Lastimoso Jan 19 '17 at 12:51
  • It could be that your ajax call can't access the url you've specified. Are you using XAMP or Homestead to test locally? – VenomRush Jan 19 '17 at 13:05
  • null came from the url I've specified. Yes, I'm using xampp and ran php artisan serve in my client side – Carriane Lastimoso Jan 19 '17 at 13:12
  • What I would do is change the API to return a hardcoded message like "It works!" and then test. If you still receive a null response then you know the problem is your ajax call not being able to access the url. If it returns the message then the problem lies in your API. – VenomRush Jan 19 '17 at 13:18
0

You handle the file by using:

$request->file('image_url');

https://laravel.com/docs/5.3/requests#files

Piotr
  • 1,777
  • 17
  • 24
0

Another approach is to convert img into base64 and pass it as a param. Then in your controller/route you can decode the base64 and save to a file (if is needed).

{{ Form::open(['enctype' => "multipart/form-data", 'id' => 'addplant', 'method' => 'POST', 'files' => true, 'class' => 'col s12']) }}
    <div class="row" style="margin-top:10%;">
      <div class="col s12  center">
        <img class="circle" id="image_url" src=""></a>
        {!! Form::file('image_url', array('id' => 'image', 'class' => 'form-control')) !!}
      </div>
    </div>
    <div class="row">
      <div class="input-field col s6">
        {{ Form::text('herbal_name', null, array('id' => 'herbal_name', 'class' => 'form-control validate')) }}
        {{ Form::label('herbal_name', 'Herbal Name') }}
      </div>
      <div class="input-field col s6">
        {{ Form::text('scientific_name', null, array('id' => 'scientific_name', 'class' => 'form-control validate')) }}
        {{ Form::label('scientific_name', 'Scientific Name') }}
      </div>
    </div>
{{ Form::submit('Add plant', array('class' => 'btn btn-primary right add')) }}
{{ Form::close() }}
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': '{{ csrf_token() }}'
        }
    });

    var base64img = null;

    $(document).ready(function() {
        $('#image').change(function(){

            var file = this.files[0];
            var reader  = new FileReader();

            reader.addEventListener("load", function () {
                base64img = reader.result;
            }, false);


            if (file) {
                reader.readAsDataURL(file);
            }

        });

        $(".add").click(function(e) {

            e.preventDefault();

            $.ajax({
                url: 'http://127.0.0.1:8000/identificare_api/public/api/plants',
                data: $("#addplant").serialize() + '&image_url=' + base64img,
                type: "POST",
                success: function( msg ) {
                    console.log(msg);
                },
                error: function(){
                    alert('pangit');
                }
            });
         });
    });
</script>

and route

Route::post('identificare_api/public/api/plants', function (Request $request) {
    return json_encode($request->all());
});
Piotr
  • 1,777
  • 17
  • 24
  • Why does $_POST['image_url'] is too long? – Carriane Lastimoso Jan 20 '17 at 03:17
  • Look at: [http://stackoverflow.com/questions/6135427/increasing-the-maximum-post-size](http://stackoverflow.com/questions/6135427/increasing-the-maximum-post-size) – Piotr Jan 20 '17 at 08:26
  • Please refer to my update above to see what does `base64img` returns. – Carriane Lastimoso Jan 20 '17 at 17:06
  • What I mean is $_POST['image_url'] is very long when I tried decoding it using base64_decode($_POST['image_url']. When I tried to return the decoded `$_POST['image_url']`, it returned false. According to (base64decode.net/php-base64-decode), base64_decode() will return false if the input contains character from outside the base64 alphabet. – Carriane Lastimoso Jan 22 '17 at 13:21