Wyślij kształt, aby pobrać plik, a także inne pola za pomocą AJAX


Sprawdziłem tutaj każde pytanie i dużo googlowałem, ale nie znalazłem takiego, które działa.
Oto mój 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">
<input id="description" type="text" name="description" size="30" value="Description">
<input id="keywords" type="text" name="keywords" size="30" value="Keywords">
<input id="link" type="text" name="link" size="30" value="Link">
<input id="file" type="file" name="file">
<input id="submit" type="button" name='submit' value="Create" onclick="myFunction()">
</form>
<div id="createformresults">


A oto 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();
});
});
}

MÓJ KOD PHP:
<?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"] . ""; } 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"; } ?>

Kod PHP działa poprawnie, problem jest gdzieś w pliku js.
Zaproszony:
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

Do tego zadania użyłbym
FormData
.
Oto przykład kodu używającego 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 będzie obsługiwać przesyłanie wielu plików!
Dodaj atrybut do tagu formularza:
enctype = "multipart/form-data"

NOTE
: może się okazać, że tablica
$ _FILES
jest pusta po stronie serwera - w takim przypadku musisz się upewnić, że konfiguracja serwera pozwala na przesyłanie plików, wystarczy ograniczenie rozmiaru wysyłanego pliku, czas publikacji
wystarczy, itd ...
Najlepszym sposobem na rozpoczęcie jest upewnienie się, że przesyłanie plików jest dozwolone, a następnie przetestowanie bardzo
Małe pliki, aby upewnić się, że wszystko jest w swoim kodzie OK.
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

To w końcu zrobione !!
Dodaj to źródło do 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="">
Profile Image: <input name="profileImg[]" type="file"/>
Display Image: <input name="displayImg[]" type="file"/>
<input type="submit" value="Submit">
</form>

A to dotyczy pliku PHP (formprocessing.php):
$id = $_POST['id'];
$username = $_POST['username'];
$profileImg = $_FILES['profileImg'];
$displayImg = $_FILES['displayImg'];

Zrobiłem to za pomocą tego linku

http://digipiph.com/blog/submi ... -ajax
http://digipiph.com/blog/submi ... -ajax
Anonimowy użytkownik

Anonimowy użytkownik

Potwierdzenie od:

Ajax w ogóle nie obsługuje przesyłania plików. Istnieją jednak również obejścia. Jedną z nich jest wtyczka jQuery o nazwie Iframe Post Form. Przeczytaj więcej tutaj:
http://plugins.jquery.com/iframe-post-form
http://plugins.jquery.com/iframe-post-form/
/
$('form').iframePostForm({
complete : function (response) {
$('#createarea').text("SUCCESS");
}
});

Najwyraźniej będziesz musiał określić akcję url i
enctype = "multipart/form-data"
w tagu
form
.
Mam nadzieję że to pomoże!

Aby odpowiedzieć na pytania, Zaloguj się lub Zarejestruj się