最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to html form post - file uploading and reading json response from php server - Stack Overflow

programmeradmin2浏览0评论

i am trying file uploading to php my server.file and data uploading through multi part /form-data ,the file and data received on php server but in my php server return json response .please help me how to read json response in my webpage and if its success(code=0) means it redirect another page .the php sever is mon for both android and web pages .json response look like {"code":0,"message":"success"}

<div style="height:0px;overflow:hidden">
    <form id="myForm" action="http://192.168.2.4/digiid/api/addid" 
        method="post" enctype="multipart/form-data" runat="server">

        <input type="file" name="file" id="file" onchange="showMyImage(this)" />
        <input type="hidden" name="userid" value="<?php echo $_SESSION["userid"]?>">
        <input type="hidden" id="inputfilename" name="filename" value="here">
    </form>
</div>

<a class="button1" id="browseButton" onclick=""  style="width:12%;height: 30px; text-decoration:none;"><font color="white" size="5px">Select ID</font></a>
<br/>

<div>

            <img src='images/capture_picture_size.png' id='imgscreen'  width='200' height='200'>

<br/>


<p id="filename" style="color: #ffffff; font-size: 20px" >
    Title of the ID<br/></p>

<a class="button1"onclick="myFunction()" style= " width:12%;height: 30px; text-decoration:none;"><font color="white" size="5px">Save ID</font></a></form>

</div>  

<script>
    function myFunction() {
       document.getElementById("myForm").submit();
    }
</script>

<script>
    browseButton.onclick=function chooseFile() {
        document.getElementById("file").click(); 
    };

    function showMyImage(fileInput) {

        var files = fileInput.files;

        var file = files[0];
        var imageType = /image.*/;

        var img=document.getElementById("imgscreen");
        var reader = new FileReader();
        reader.onload = (function(aImg) {
            return function(e) {
            //x=e.target.result

            img.src = e.target.result;
            var extfilename=file.name;
            document.getElementById("filename").innerHTML=extfilename.slice(0,-5) ;

            document.getElementById("inputfilename").value=extfilename.slice(0,-5);
     };
 })(img);

 reader.readAsDataURL(file);

 }</script>

i am trying file uploading to php my server.file and data uploading through multi part /form-data ,the file and data received on php server but in my php server return json response .please help me how to read json response in my webpage and if its success(code=0) means it redirect another page .the php sever is mon for both android and web pages .json response look like {"code":0,"message":"success"}

<div style="height:0px;overflow:hidden">
    <form id="myForm" action="http://192.168.2.4/digiid/api/addid" 
        method="post" enctype="multipart/form-data" runat="server">

        <input type="file" name="file" id="file" onchange="showMyImage(this)" />
        <input type="hidden" name="userid" value="<?php echo $_SESSION["userid"]?>">
        <input type="hidden" id="inputfilename" name="filename" value="here">
    </form>
</div>

<a class="button1" id="browseButton" onclick=""  style="width:12%;height: 30px; text-decoration:none;"><font color="white" size="5px">Select ID</font></a>
<br/>

<div>

            <img src='images/capture_picture_size.png' id='imgscreen'  width='200' height='200'>

<br/>


<p id="filename" style="color: #ffffff; font-size: 20px" >
    Title of the ID<br/></p>

<a class="button1"onclick="myFunction()" style= " width:12%;height: 30px; text-decoration:none;"><font color="white" size="5px">Save ID</font></a></form>

</div>  

<script>
    function myFunction() {
       document.getElementById("myForm").submit();
    }
</script>

<script>
    browseButton.onclick=function chooseFile() {
        document.getElementById("file").click(); 
    };

    function showMyImage(fileInput) {

        var files = fileInput.files;

        var file = files[0];
        var imageType = /image.*/;

        var img=document.getElementById("imgscreen");
        var reader = new FileReader();
        reader.onload = (function(aImg) {
            return function(e) {
            //x=e.target.result

            img.src = e.target.result;
            var extfilename=file.name;
            document.getElementById("filename").innerHTML=extfilename.slice(0,-5) ;

            document.getElementById("inputfilename").value=extfilename.slice(0,-5);
     };
 })(img);

 reader.readAsDataURL(file);

 }</script>
Share Improve this question edited Sep 27, 2014 at 6:34 Mugunthan S asked Sep 26, 2014 at 5:36 Mugunthan SMugunthan S 5383 gold badges8 silver badges21 bronze badges 4
  • What does the json response look like? – Vlad Commented Sep 26, 2014 at 5:45
  • json response look like {"code":0,"message":"success"} – Mugunthan S Commented Sep 26, 2014 at 5:51
  • Can you please reformat your code? Why you try to access $_POST['photo'] ? There is no such input in your form. Access Fileuploads using $_FILE not $_POST – Frnak Commented Sep 26, 2014 at 8:02
  • post your php server side code – Sandip Pingle Commented Oct 1, 2014 at 13:15
Add a ment  | 

5 Answers 5

Reset to default 5 +25

I think it should work for you. Using AJAX, as I do

     //Your php code
        $arrToJSON = array(
        "dataPHPtoJs"=>"yourData",
        "asYouWant"=>"<div class=\".class1\">soemting</div>"    
        );  
        return json_encode(array($arrToJSON));




    //Your javaScript code
    $(document).on("event", "#idElement", function(){
        //Data you want to send to php evaluate
         var dt={ 
                  ObjEvn:"btn_Login",
                  dataJsToPHP: $("#txt_EmailLogin").val()
                };

        //Ajax      
         var request =$.ajax({//http://api.jquery./jQuery.ajax/
                                url: "yourServer.php",
                                type: "POST",
                                data: dt,
                                dataType: "json"
                            });

        //Ajax Done catch JSON from PHP 
            request.done(function(dataset){
                for (var index in dataset){ 
                     dataPHPtoJsJS=dataset[index].dataPHPtoJs;
                     asManyasYouWantJS=dataset[index].asYouWant;
                 }

                 //JavaScript conditions. Here you can control the behaivior of your html object, based on your PHP response
                 if(dataPHPtoJsJS){
                    $( "#idYourHtmlElement" ).removeClass( "class1" )
                    $( "#idYourHtmlElement" ).addClass( "class2" )
                 }


         }); 

        //Ajax Fail 
            request.fail(function(jqXHR, textStatus) {
                alert("Request failed: " + textStatus);
            }); 
    }

You should probably use an AJAX call. Here's a solution using jQuery:

<script type="text/javascript">
$(document).ready(function(){
    $("#browseButton").click(function(){
        var url = "";
        var formdata = $("#myForm").serialize();
        $.ajax({
            url: url,
            type: 'POST',
            data:  formdata,
            dataType: 'json',
            cache: false,
            contentType: false,
            processData: false,
            success: function(response){
                if(response.status == "success"){
                    // Success

                } else {
                    // Failure

                }
            },
            error: function(response){
                // Error

            }          
        });
    });
});
</script>

In order to redirect the user, you can use: window.location.href = " ... your_url ...";

Here's an explanation on how to use jQuery AJAX and multi-part data:

Sending multipart/formdata with jQuery.ajax

try json_decode.

    $data = ({"code":0, "message":"success"});
    $array = json_decode($data, true);

by passing 2nd parameter to true you will get response in array instead of object.

the array will be then populated as follow:

    array (size=2)
    'code' => int 0
    'message' => string 'success' (length=7)

Your JSON response would be a kind of associative array in php. Encode your array data into JSON using "json_encode" and return values as you want .

   $arr = array('status' => $status, 'status2' => $status2, );
   echo json_encode($arr);

NOTE: If you are using ajax to call php file then do not use any php echo/print in that file and not even HTML. ECHO only "json_encode();" Nothing else.

To sum it up:

  1. Upload your data to server using AJAX with native JS (>=IE10) or jQuery
  2. Catch (xhr.responseText in native JS) and parse the response
  3. Redirect with window.location.href="success.php"
发布评论

评论列表(0)

  1. 暂无评论