How to fetch data from ajax in php

故事扮演 提交于 2019-12-12 06:16:34

问题


I am passing image from a form to a php page using ajax. Problem is that the data is not getting fetched and giving a blank output. Following is my code:

test.php

<!-- Help taken from http://stackoverflow.com/questions/24446281/passing-image-using-ajax-to-php -->

<form name="saveImg" enctype="multipart/form-data" id="saveImg">
<input type="file" name="imgVid" id="imgVid">
<button name="submit" id="submit">Upload</button>
<img src="skin/images/process.gif" id="procimg" height="32" width="auto" style="display:none;" />
</form>

<div id="msg"></div>











<!--jQuery-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<script>
document.getElementById("submit").addEventListener("click", function(event){
    event.preventDefault();
    saveImgfunc();
});

function saveImgfunc(){
    var form = new FormData(document.getElementById('saveImg'));
    var file = document.getElementById('imgVid').files[0];
    if (file) {   
        form.append('imgVid', file);
    }
    $.ajax({
        type : 'POST',
        url : 'core/img.php',
        data : form,
        cache : false,
        contentType : false,
        processData : false
    }).success(function(data){
        console.log(data);
    });
}

img.php

<?php
if(isset($_POST['submit'])){
    echo "Data can be fetched here";
}
?>

Kindly help me with this issue. Thanks in advance.


回答1:


change this:

if(isset($_POST['submit'])){

to this:

if(isset($_POST['imgVid'])){

Because you are not posting 'submit' to the php. You code of this line

data : form,

has just this:

form.append('imgVid', file);


来源:https://stackoverflow.com/questions/30166082/how-to-fetch-data-from-ajax-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!