Vue JS Axios Post Request Sending Null to PHP












0















So I have an image uploaded in Vue JS and I send the POST request to a Laravel Route. The image gets uploaded, saved on my local and sent to an API. The API request returns its JSON response on client side (as expected) BUT I cannot do anything with this response on PHP, it returns null in PHP. I can only see the JSON response client side, which is weird. I have been trying to figure this out for a couple of days.



Here is my Vue JS code that uploads a picture:



let token = document.head.querySelector('meta[name="csrf-token"]');
export default{
data(){
return {
image: ''
}
},
methods: {
onFileChange(e) {
let files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
this.createImage(files[0]);
},
createImage(file) {
let reader = new FileReader();
let vm = this;
reader.onload = (e) => {
vm.image = e.target.result;
};
reader.readAsDataURL(file);
},
upload(){
let formData = new FormData();
formData.append('image', this.image);
console.log(this.image) ;
axios.post( 'nova-vendor/ad-asset-upload/add',
formData,
{
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': token.content
}
}
).then(function (response){
console.log(response);
})
.catch(function(){
console.log('FAILURE!!');
});
},
}
}


Vue JS returns a base64 image and I convert it in the PHP controller to jpg or png and it uploads to the API / locally. I see the response on client side like this:



{"error":false,"size":27410,"filename":"yJCH2T","ext":"png","url":"https://vgy.me/u/yJCH2T","image":"https://vgy.me/yJCH2T.png","delete":"https://vgy.me/delete/eGGhib4gPY2a"}


In PHP no matter what I do I cannot get the JSON data, BUT I CAN get the JSON when I replicate my steps on vanilla php without Larval or Vue.



Here is my PHP code once the base64 string is converted into an image.



 $ch = curl_init('https://vgy.me/upload');
$file = new CURLFile($file, $type, $filename );
$data = array('file' => $file, 'title' => 'Beautiful Flowers', 'description' => 'A beautiful photo of flowers at the local park.');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$ok = curl_exec($ch);
$json = json_decode($ok, true);


So I would expect$json['image'] to return the image url from JSON string, but its null.



In case you were wondering about my image conversion logic here it is...



        $data = $request->input('image');
$pos = strpos($data, ';');
$type = explode(':', substr($data, 0, $pos))[1];
$folderPath = "storage/";
$image_parts = explode(";base64,", $request->input('image'));
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
if ( $type == "image/jpeg" || $type == "image/jpg"){

$file = $folderPath . uniqid() . '.jpg';
$filename = uniqid() . '.jpg';
} else if ( $type == "image/png" )
{

$file = $folderPath . uniqid() . '.png';
$filename = uniqid() . '.png';
}
$img = file_put_contents($file, $image_base64);









share|improve this question



























    0















    So I have an image uploaded in Vue JS and I send the POST request to a Laravel Route. The image gets uploaded, saved on my local and sent to an API. The API request returns its JSON response on client side (as expected) BUT I cannot do anything with this response on PHP, it returns null in PHP. I can only see the JSON response client side, which is weird. I have been trying to figure this out for a couple of days.



    Here is my Vue JS code that uploads a picture:



    let token = document.head.querySelector('meta[name="csrf-token"]');
    export default{
    data(){
    return {
    image: ''
    }
    },
    methods: {
    onFileChange(e) {
    let files = e.target.files || e.dataTransfer.files;
    if (!files.length)
    return;
    this.createImage(files[0]);
    },
    createImage(file) {
    let reader = new FileReader();
    let vm = this;
    reader.onload = (e) => {
    vm.image = e.target.result;
    };
    reader.readAsDataURL(file);
    },
    upload(){
    let formData = new FormData();
    formData.append('image', this.image);
    console.log(this.image) ;
    axios.post( 'nova-vendor/ad-asset-upload/add',
    formData,
    {
    headers: {
    'Content-Type': 'application/json',
    'X-CSRF-TOKEN': token.content
    }
    }
    ).then(function (response){
    console.log(response);
    })
    .catch(function(){
    console.log('FAILURE!!');
    });
    },
    }
    }


    Vue JS returns a base64 image and I convert it in the PHP controller to jpg or png and it uploads to the API / locally. I see the response on client side like this:



    {"error":false,"size":27410,"filename":"yJCH2T","ext":"png","url":"https://vgy.me/u/yJCH2T","image":"https://vgy.me/yJCH2T.png","delete":"https://vgy.me/delete/eGGhib4gPY2a"}


    In PHP no matter what I do I cannot get the JSON data, BUT I CAN get the JSON when I replicate my steps on vanilla php without Larval or Vue.



    Here is my PHP code once the base64 string is converted into an image.



     $ch = curl_init('https://vgy.me/upload');
    $file = new CURLFile($file, $type, $filename );
    $data = array('file' => $file, 'title' => 'Beautiful Flowers', 'description' => 'A beautiful photo of flowers at the local park.');
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $ok = curl_exec($ch);
    $json = json_decode($ok, true);


    So I would expect$json['image'] to return the image url from JSON string, but its null.



    In case you were wondering about my image conversion logic here it is...



            $data = $request->input('image');
    $pos = strpos($data, ';');
    $type = explode(':', substr($data, 0, $pos))[1];
    $folderPath = "storage/";
    $image_parts = explode(";base64,", $request->input('image'));
    $image_type_aux = explode("image/", $image_parts[0]);
    $image_type = $image_type_aux[1];
    $image_base64 = base64_decode($image_parts[1]);
    if ( $type == "image/jpeg" || $type == "image/jpg"){

    $file = $folderPath . uniqid() . '.jpg';
    $filename = uniqid() . '.jpg';
    } else if ( $type == "image/png" )
    {

    $file = $folderPath . uniqid() . '.png';
    $filename = uniqid() . '.png';
    }
    $img = file_put_contents($file, $image_base64);









    share|improve this question

























      0












      0








      0








      So I have an image uploaded in Vue JS and I send the POST request to a Laravel Route. The image gets uploaded, saved on my local and sent to an API. The API request returns its JSON response on client side (as expected) BUT I cannot do anything with this response on PHP, it returns null in PHP. I can only see the JSON response client side, which is weird. I have been trying to figure this out for a couple of days.



      Here is my Vue JS code that uploads a picture:



      let token = document.head.querySelector('meta[name="csrf-token"]');
      export default{
      data(){
      return {
      image: ''
      }
      },
      methods: {
      onFileChange(e) {
      let files = e.target.files || e.dataTransfer.files;
      if (!files.length)
      return;
      this.createImage(files[0]);
      },
      createImage(file) {
      let reader = new FileReader();
      let vm = this;
      reader.onload = (e) => {
      vm.image = e.target.result;
      };
      reader.readAsDataURL(file);
      },
      upload(){
      let formData = new FormData();
      formData.append('image', this.image);
      console.log(this.image) ;
      axios.post( 'nova-vendor/ad-asset-upload/add',
      formData,
      {
      headers: {
      'Content-Type': 'application/json',
      'X-CSRF-TOKEN': token.content
      }
      }
      ).then(function (response){
      console.log(response);
      })
      .catch(function(){
      console.log('FAILURE!!');
      });
      },
      }
      }


      Vue JS returns a base64 image and I convert it in the PHP controller to jpg or png and it uploads to the API / locally. I see the response on client side like this:



      {"error":false,"size":27410,"filename":"yJCH2T","ext":"png","url":"https://vgy.me/u/yJCH2T","image":"https://vgy.me/yJCH2T.png","delete":"https://vgy.me/delete/eGGhib4gPY2a"}


      In PHP no matter what I do I cannot get the JSON data, BUT I CAN get the JSON when I replicate my steps on vanilla php without Larval or Vue.



      Here is my PHP code once the base64 string is converted into an image.



       $ch = curl_init('https://vgy.me/upload');
      $file = new CURLFile($file, $type, $filename );
      $data = array('file' => $file, 'title' => 'Beautiful Flowers', 'description' => 'A beautiful photo of flowers at the local park.');
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
      $ok = curl_exec($ch);
      $json = json_decode($ok, true);


      So I would expect$json['image'] to return the image url from JSON string, but its null.



      In case you were wondering about my image conversion logic here it is...



              $data = $request->input('image');
      $pos = strpos($data, ';');
      $type = explode(':', substr($data, 0, $pos))[1];
      $folderPath = "storage/";
      $image_parts = explode(";base64,", $request->input('image'));
      $image_type_aux = explode("image/", $image_parts[0]);
      $image_type = $image_type_aux[1];
      $image_base64 = base64_decode($image_parts[1]);
      if ( $type == "image/jpeg" || $type == "image/jpg"){

      $file = $folderPath . uniqid() . '.jpg';
      $filename = uniqid() . '.jpg';
      } else if ( $type == "image/png" )
      {

      $file = $folderPath . uniqid() . '.png';
      $filename = uniqid() . '.png';
      }
      $img = file_put_contents($file, $image_base64);









      share|improve this question














      So I have an image uploaded in Vue JS and I send the POST request to a Laravel Route. The image gets uploaded, saved on my local and sent to an API. The API request returns its JSON response on client side (as expected) BUT I cannot do anything with this response on PHP, it returns null in PHP. I can only see the JSON response client side, which is weird. I have been trying to figure this out for a couple of days.



      Here is my Vue JS code that uploads a picture:



      let token = document.head.querySelector('meta[name="csrf-token"]');
      export default{
      data(){
      return {
      image: ''
      }
      },
      methods: {
      onFileChange(e) {
      let files = e.target.files || e.dataTransfer.files;
      if (!files.length)
      return;
      this.createImage(files[0]);
      },
      createImage(file) {
      let reader = new FileReader();
      let vm = this;
      reader.onload = (e) => {
      vm.image = e.target.result;
      };
      reader.readAsDataURL(file);
      },
      upload(){
      let formData = new FormData();
      formData.append('image', this.image);
      console.log(this.image) ;
      axios.post( 'nova-vendor/ad-asset-upload/add',
      formData,
      {
      headers: {
      'Content-Type': 'application/json',
      'X-CSRF-TOKEN': token.content
      }
      }
      ).then(function (response){
      console.log(response);
      })
      .catch(function(){
      console.log('FAILURE!!');
      });
      },
      }
      }


      Vue JS returns a base64 image and I convert it in the PHP controller to jpg or png and it uploads to the API / locally. I see the response on client side like this:



      {"error":false,"size":27410,"filename":"yJCH2T","ext":"png","url":"https://vgy.me/u/yJCH2T","image":"https://vgy.me/yJCH2T.png","delete":"https://vgy.me/delete/eGGhib4gPY2a"}


      In PHP no matter what I do I cannot get the JSON data, BUT I CAN get the JSON when I replicate my steps on vanilla php without Larval or Vue.



      Here is my PHP code once the base64 string is converted into an image.



       $ch = curl_init('https://vgy.me/upload');
      $file = new CURLFile($file, $type, $filename );
      $data = array('file' => $file, 'title' => 'Beautiful Flowers', 'description' => 'A beautiful photo of flowers at the local park.');
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
      $ok = curl_exec($ch);
      $json = json_decode($ok, true);


      So I would expect$json['image'] to return the image url from JSON string, but its null.



      In case you were wondering about my image conversion logic here it is...



              $data = $request->input('image');
      $pos = strpos($data, ';');
      $type = explode(':', substr($data, 0, $pos))[1];
      $folderPath = "storage/";
      $image_parts = explode(";base64,", $request->input('image'));
      $image_type_aux = explode("image/", $image_parts[0]);
      $image_type = $image_type_aux[1];
      $image_base64 = base64_decode($image_parts[1]);
      if ( $type == "image/jpeg" || $type == "image/jpg"){

      $file = $folderPath . uniqid() . '.jpg';
      $filename = uniqid() . '.jpg';
      } else if ( $type == "image/png" )
      {

      $file = $folderPath . uniqid() . '.png';
      $filename = uniqid() . '.png';
      }
      $img = file_put_contents($file, $image_base64);






      php json vue.js






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 24 '18 at 0:57









      Joe EliaJoe Elia

      367




      367
























          1 Answer
          1






          active

          oldest

          votes


















          0














          I figured it out by adding



          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);


          to my CURL code. But now I guess I have to go back and rework my original Guzzle Package I created that works in just regular old PHP / HTML.






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53454301%2fvue-js-axios-post-request-sending-null-to-php%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            I figured it out by adding



            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);


            to my CURL code. But now I guess I have to go back and rework my original Guzzle Package I created that works in just regular old PHP / HTML.






            share|improve this answer




























              0














              I figured it out by adding



              curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);


              to my CURL code. But now I guess I have to go back and rework my original Guzzle Package I created that works in just regular old PHP / HTML.






              share|improve this answer


























                0












                0








                0







                I figured it out by adding



                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);


                to my CURL code. But now I guess I have to go back and rework my original Guzzle Package I created that works in just regular old PHP / HTML.






                share|improve this answer













                I figured it out by adding



                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);


                to my CURL code. But now I guess I have to go back and rework my original Guzzle Package I created that works in just regular old PHP / HTML.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 24 '18 at 2:04









                Joe EliaJoe Elia

                367




                367






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53454301%2fvue-js-axios-post-request-sending-null-to-php%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Contact image not getting when fetch all contact list from iPhone by CNContact

                    count number of partitions of a set with n elements into k subsets

                    A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks