javascript - Form submit to upload file and also other fields using ajax - Stack Overflow

I have tested every question here and have also googled alot, but did not find the something that work.

I have tested every question here and have also googled alot, but did not find the something that work.

Here is my HTML:

<div id="createarea">
    <form id="createform" action="index/create/createcontrols.php" method="post" enctype="multipart/form-data">
      <input id="title" type="text" name="title" size="30" value="Title"><br><br>
      <input id="description" type="text" name="description" size="30" value="Description"><br><br>
      <input id="keywords" type="text" name="keywords" size="30" value="Keywords"><br><br>
      <input id="link" type="text" name="link" size="30" value="Link"><br><br>
      <input id="file" type="file" name="file"><br><br>
      <input id="submit" type="button" name='submit' value="Create" onclick="myFunction()">
    </form>
    <div id="createformresults">
    </div>
</div>  

And here is the javascript:

function myFunction() {
  $(function () {
    $('#createform').on('submit', function (e) {
      $.ajax({
        type: 'post',
        url: 'index/create/createcontrols.php',
        data: $('#createform').serialize(),
        success: function () {
          document.getElementById('createarea').innerHTML = "SUCCESS";
        }
      });
      e.preventDefault();
    });
  });
}

MY PHP CODE:

 <?php





$db=mysql_connect('','','') or die(mysql_error());
mysql_select_db("", $db) or die(mysql_error());




$title = $_POST["title"];
$description = $_POST["description"];
$keywords = $_POST["keywords"];
$link = $_POST["link"];
        $image=$_FILES["file"]["name"];


        $allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/pjpeg") || ($_FILES["file"]["type"] == "image/x-png") || ($_FILES["file"]["type"] == "image/png")) && ($_FILES["file"]["size"] < 20000) && in_array($extension, $allowedExts)) {

    if ($_FILES["file"]["error"] > 0) {

        echo "Return Code: " . $_FILES["file"]["error"] . "<br>";

        }

        else {

                if (file_exists("temp/" . $_FILES["file"]["name"])) {
                echo $_FILES["file"]["name"] . " already exists. ";
                }

            else {
                move_uploaded_file($_FILES["file"]["tmp_name"], "temp/" . $_FILES["file"]["name"]);
            }
        }
}

else { 

    echo "Invalid file"; 

             }


            $qry="insert createcontent values('null','$title','$description','$keywords','$link','$image')";

            $res=  mysql_query($qry) or die(mysql_error());

            if(mysql_affected_rows()==1) {

                    echo "Success"; 

            }  

else {

    echo "Not Saved";                    

}



 ?> 

PHP code is working fine the issue is somewhere in js file.

I have tested every question here and have also googled alot, but did not find the something that work.

Here is my HTML:

<div id="createarea">
    <form id="createform" action="index/create/createcontrols.php" method="post" enctype="multipart/form-data">
      <input id="title" type="text" name="title" size="30" value="Title"><br><br>
      <input id="description" type="text" name="description" size="30" value="Description"><br><br>
      <input id="keywords" type="text" name="keywords" size="30" value="Keywords"><br><br>
      <input id="link" type="text" name="link" size="30" value="Link"><br><br>
      <input id="file" type="file" name="file"><br><br>
      <input id="submit" type="button" name='submit' value="Create" onclick="myFunction()">
    </form>
    <div id="createformresults">
    </div>
</div>  

And here is the javascript:

function myFunction() {
  $(function () {
    $('#createform').on('submit', function (e) {
      $.ajax({
        type: 'post',
        url: 'index/create/createcontrols.php',
        data: $('#createform').serialize(),
        success: function () {
          document.getElementById('createarea').innerHTML = "SUCCESS";
        }
      });
      e.preventDefault();
    });
  });
}

MY PHP CODE:

 <?php





$db=mysql_connect('','','') or die(mysql_error());
mysql_select_db("", $db) or die(mysql_error());




$title = $_POST["title"];
$description = $_POST["description"];
$keywords = $_POST["keywords"];
$link = $_POST["link"];
        $image=$_FILES["file"]["name"];


        $allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/pjpeg") || ($_FILES["file"]["type"] == "image/x-png") || ($_FILES["file"]["type"] == "image/png")) && ($_FILES["file"]["size"] < 20000) && in_array($extension, $allowedExts)) {

    if ($_FILES["file"]["error"] > 0) {

        echo "Return Code: " . $_FILES["file"]["error"] . "<br>";

        }

        else {

                if (file_exists("temp/" . $_FILES["file"]["name"])) {
                echo $_FILES["file"]["name"] . " already exists. ";
                }

            else {
                move_uploaded_file($_FILES["file"]["tmp_name"], "temp/" . $_FILES["file"]["name"]);
            }
        }
}

else { 

    echo "Invalid file"; 

             }


            $qry="insert createcontent values('null','$title','$description','$keywords','$link','$image')";

            $res=  mysql_query($qry) or die(mysql_error());

            if(mysql_affected_rows()==1) {

                    echo "Success"; 

            }  

else {

    echo "Not Saved";                    

}



 ?> 

PHP code is working fine the issue is somewhere in js file.

Share Improve this question edited Mar 20, 2014 at 2:47 mega6382 asked Mar 20, 2014 at 2:24 mega6382mega6382 9,39617 gold badges50 silver badges72 bronze badges 7
  • why do you call onload inside of your myFunction()? – 13ruce1337 Commented Mar 20, 2014 at 2:31
  • What error are you getting? – Femi Commented Mar 20, 2014 at 2:32
  • @13ruce1337 there is no on load inside function – mega6382 Commented Mar 20, 2014 at 2:32
  • @mega6382 im referencing the JQuery onload at $(function(){}); – 13ruce1337 Commented Mar 20, 2014 at 2:33
  • @MjrKusanagi there is no error and if I add any alert() or any other code outside the success it works. – mega6382 Commented Mar 20, 2014 at 2:33
 |  Show 2 more ments

3 Answers 3

Reset to default 5

I would use FormData for this task.

Here is an example of your code using FormData :

$(function () { //On dom ready:

$("#createform").submit(function (e) { //will be triggered on submit:

     e.preventDefault();

     if( window.FormData !== undefined ) 
     //make sure that we can use FormData ie>9, chrome > 7, opera > 12 safari >5, android > 3  gecko mobile > 2, opera mobile >12 <- wil support XHR too
     {

         var formData = new FormData($('#createform')[0]); // use "[0]" <- important
    // you can append aditional values (regular text): formData.append("be","some value");
         $.ajax({
                 url: 'index/create/createcontrols.php',  //Server script to process data
                 type: 'POST',
                 data: formData,
                 xhr: function() {  },
                 success: function(response){ $("#createformresults").text("SUCCESS"); },
                 error: function (jqXHR, textStatus, errorThrown) { $("#createformresults").text(errorThrown); },
                 //Options to tell jQuery not to process data or worry about content-type.
                 cache: false,
                 contentType: false,
                 processData: false
          });
      } else {

          //Fallback

      }

      return false;
});

});

FormData will support multi file upload!

Add to your Form tag the attribute: enctype="multipart/form-data"

NOTE: You may find that the $_FILES array is empty on server side page - In this case you need to make sure your server configuration allows file uploads, size limit of file upload is enough, post time is enough etc....

The best way to begin is to make sure that file uploads is allowed and then testing with very small files to be sure everything in your code is OK.

Finally it is done!!

Add this source to x.html

//Program a custom submit function for the form
$("form#data").submit(function(event){

  //disable the default form submission
  event.preventDefault();

  //grab all form data  
  var formData = new FormData($(this)[0]);

  $.ajax({
    url: 'formprocessing.php',
    type: 'POST',
    data: formData,
    async: false,
    cache: false,
    contentType: false,
    processData: false,
    success: function (returndata) {
      alert(returndata);
    }
  });

  return false;
});
<form id="data">
  <input type="hidden" name="id" value="123" readonly="readonly">
  User Name: <input type="text" name="username" value=""><br />
  Profile Image: <input name="profileImg[]" type="file" /><br />
  Display Image: <input name="displayImg[]" type="file" /><br />
  <input type="submit" value="Submit">
</form>

And this to a PHP file (formprocessing.php):

$id = $_POST['id'];
$username = $_POST['username'];
$profileImg = $_FILES['profileImg'];
$displayImg = $_FILES['displayImg'];

I did it with the help this link http://digipiph./blog/submitting-multipartform-data-using-jquery-and-ajax

ajax doesn't support file uploading at all. However, there are work-arounds. One of them is a jQuery plugin called Iframe Post Form, read more from:

http://plugins.jquery./iframe-post-form/

$('form').iframePostForm({
      plete : function (response) {
           $('#createarea').text("SUCCESS");
    }
});

Apparently, you will have to specify the url action and enctype="multipart/form-data" in the form tag.

Hope this helps!

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745321048a4622443.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信