Home > OS >  Javascript & PHP ajax error: "Undefined array key"
Javascript & PHP ajax error: "Undefined array key"

Time:12-31

for several days I have been facing the problem that PHP cannot find my index.

What I've tried:

  • Change the data name in ajax
  • I added the code from PHP Create.php to create.php (at the beginning and at the end of the code)
  • Various ajax possibilities

The goal

I want to save an image which I have cropped with (cropper.js), using PHP on a SQL server.

My code:

OnSetData.js

canvas = cropper.getCroppedCanvas({
  width:700,
  height:700
});

canvas.toBlob((blob) => {
  url_img = URL.createObjectURL(blob);
  //url_img = blob:https://localhost/a37a7cd8-ad48...
  $.ajax(
  {
      url:'assets/php/PHPCreate.php',
      type: 'POST',
      data: {'image':url_img}, 
      success:function(output) {
        console.log('Upload success: '   output);
        //Upload sucess: <output is empty>
      },
      error() {
        console.log('Upload error');
      },
    });
  }, 'image/png');

PHPCreate.php

if (isset($_POST['save_submit'])) 
{ 
  $data = $_POST["image"];
  //Warning: Undefined array key "image" in ..\assets\php\PHPCreate.php on line ..
  echo($data);
}

create.php

<link  href="assets/assets/cropperjs-main/dist/cropper.css" rel="stylesheet">
<script src="assets/assets/cropperjs-main/dist/cropper.js"></script>
    
<script src="assets/js/jquery.min.js"></script>
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
<script src="assets/js/OnSetData.js"></script>

<?php
  include './assets/php/PHPCreate.php';
?>
.
.
.
.
<form id="formUpload" action="" method="post"  enctype="multipart/form-data">

  <button  role="button" name="save_submit" type="submit">Save</button>

</form>

CodePudding user response:

i think you will open create.php in browser

create.php has a form that sends "save_submit" to izself as a new request so create.php will be opened again but this time with "save_submit", nothing else, so yes, there is no image, that is correct

now lets look at OnSetData.js: it makes a separate request to PHPCreate.php with "image", but no "save_submit" so PHPCreate.php will do nothing

to clearify:

  • the button in the form will make a site navigation
  • OnSetData.js will make a request on its own

both request are handled in separate

  • Related