POST an image to PHP in AJAX

后端 未结 3 1885
终归单人心
终归单人心 2021-01-27 15:35

I would like to send an image to a php file using AJAX.

Here\'s my JS code:

$.ajax({
    type: \"POST\",
    url: \"http://website.com/a         


        
3条回答
  •  悲哀的现实
    2021-01-27 16:09

    If you are just looking to get it working, I recommend Ravishanker Kusuma's Hayageek jQuery File Upload plugin. I don't usually recommend plugins, but this one is excellent. It does almost all the work for you. Why re-invent the wheel?

    http://hayageek.com/docs/jquery-upload-file.php

    He breaks down the process into four simple steps, that basically look like this:

    Look for //1 //2 //3:

    
      // (1) Load the js files (note that it requires jQuery, which we also load)
        
        
           // (1)
    
    
        
    Upload
    // (2) Create DIV

    The final (fourth) step is to create a PHP file with same name as specified above in the jQuery code (in this case my_php_processor.php) to receive and process the file:

    my_php_processor.php:

    Note the relationship between myfile in the PHP ($_FILES["myfile"]), and the filename myfile specified in the jQuery code block.

    On the Hayageek web page, study the upload.php example on the Server tab.

    Note that you can also pass additional variables to the my_php_processor.php processor file by using dynamicFormData. See this other example:

    $("#fileuploader").uploadFile({
        url:"my_php_processor.php",
        fileName:"myfile",
        dynamicFormData: function(){
            return {
                //my_php_processor.php will receive POST vars below
                newSubj: $("#newSubj").val(),
                newBody: $("#newBody").val(),
            };
        },
        onSuccess:function(files,data,xhr,pd){
            //files: list of files
            //data: response from server
            //xhr : jquery xhr object
            alert(xhr.responseText); //displays data ECHOd by `my_php_processor.php`
        }
    });
    

    my_php_processor.php:

    jsFiddle Sample Code - Click on Image Example

提交回复
热议问题