-1

I get some inputs from database with $.ajax in jQuery and it will appear when user click on button:

HTML

<div id="div1"></div>
<input type="button" id="button1"/>

JQuery

$("#button1").click(function() {
   $.ajax({
      type: 'POST',
      url: "get.php",
      data: {vals: "send"},
      success : function(response) { 
         $("#div1").append(response);
   }});
})

After import elements to div, it will have one input type="file" like this:

EDIT: My Form Code is here:

HTML

<input name="upload1" id="upload1" type="file"/>
<input type="button" value="submit" id="button2"/>

JQuery

$("#button2").click(function() {
    $.ajax({
        type: 'POST',
        url: "uploadPhoto.php",
        data: {filename: filename},
        success : function(response) {      
            alert(response);
        }
    });
})

PHP

$filename = $_POST['filename ']; 

$target_dir = "image/";
$target_file = $target_dir . $filename;

var  $src_temp = $_FILES["upload1"]["tmp_name"];    
if (move_uploaded_file($src_temp, $target_file)) {
echo 'success';
}

END EDIT 1

When I want get $_FILES["upload1"]["tmp_name"] for this button to find temp folder of uploaded file in PHP code, it can't find the input that have upload1 name.

How can find a input name in PHP codes?

MojtabaSh
  • 627
  • 1
  • 11
  • 26

1 Answers1

1

Try following code to get values in $_FIELS

$("#button1").on('click', function() { 
   var filename = document.getElementById('image id here').value.replace(/C:\\fakepath\\/i, '');
   var image = document.getElementById('image id here').files[0];
   Data = new FormData();
   Data.append('upload1', image);
   Data.append('file_name', filename); //pass file name
   var xmlReq = new XMLHttpRequest(); //creating xml request
   xmlReq.open("POST", 'enter your url', true); //send request
   xmlReq.onload = function(answer) {
    if (xmlReq.status == 200) {
        var response = jQuery.parseJSON(xmlReq.responseText);
        console.log(response); 
    } else {
        console.log("Error " + xmlReq.status + " occurred uploading your file.<br \/>");
    }
};
     xmlReq.send(Data); //send form data
 });
Basheer Kharoti
  • 4,202
  • 5
  • 24
  • 50
  • Thanks for your answer, I send input id and name with $.ajax to a separate php file when user click on submit button and it's not possible your
    for submit in this one
    – MojtabaSh Oct 20 '15 at 10:38
  • what is your mean? $image_name? – MojtabaSh Oct 20 '15 at 10:52
  • is there anywhy for find input name in php codes when for is submitted with ajax? – MojtabaSh Oct 20 '15 at 10:59
  • Thanks @Basheer Kharoti, my data in ajax have some other variable for send like this {filename: filename} how can send formData with {filename: filename} – MojtabaSh Oct 20 '15 at 11:16
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/92846/discussion-between-basheer-kharoti-and-mojtabash). – Basheer Kharoti Oct 20 '15 at 11:33