PHP e.preventDefault导致isset($ _ POST ['submit'])为false,$ img ['name']为空白

时间:2020-04-15 02:20:57

标签: php jquery curl

我需要将包含图像和(后来)文本的表单提交到php表单,该表单将图像上传到imgur,并返回imgur url,这必须在不更改页面的情况下完成,因此我使用e。 preventDefault()和ajax。

问题是,当我这样做时,isset($ _ POST ['submit'])为false,而$ img ['name']为空白。如果我不使用preventDefault,则页面将更改为我不想要的upload.php

我该如何将包含所有文件和帖子的表单提交给原始页面以进行提醒?任何帮助表示赞赏。

<?
header("Content-Type: text/plain");
$url = 'eg';
$img=$_FILES['img'];
if(isset($_POST['submit']))
{ 
 if($img['name']==''){  
  echo "<h2>An Image Please.</h2>";
 }else{
  $filename = $img['tmp_name'];
  $client_id="client_id";
  $handle = fopen($filename, "r");
  $data = fread($handle, filesize($filename));
  $pvars   = array('image' => base64_encode($data));
  $timeout = 30;
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($curl, CURLOPT_URL, 'https://api.imgur.com/3/image.json');
  curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
  curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Client-ID ' . $client_id));
  curl_setopt($curl, CURLOPT_POST, 1);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
  $out = curl_exec($curl);
  curl_close ($curl);
  $pms = json_decode($out,true);
  $url=$pms['data']['link'];
  echo $url;
 if($url!=""){
   echo $url;//"<h2>Image Uploaded</h2>";

   //echo "<img src='$url'/>";
  }else{
   echo "<h2>There's a Problem</h2>";
   echo $pms['data']['error'];  
  } 
 }
}else{echo 'no submit';}
?>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

</head>
<html>
<button id='dog'>dog</button>
<form id='foo' action="upload.php" enctype="multipart/form-data" method="POST">
 Choose Image : <input name="img" size="35" type="file"/><br/>
 <input type="submit" name="submit" value="Upload"/>
</form> 
</html>
<script>

        $('form').on('submit', function (e) {

          e.preventDefault();

         var xhr = $.post({
            url: 'upload.php',
            data: $('form').serialize(),
            function (data) {
              alert(data.responseText);

            }
          });
          $('#dog').click(function(){alert(xhr.responseText);});

        });

</script>

0 个答案:

没有答案
相关问题