Reputation: 619
Hello everyone,
I'm trying to send some (POST) data using jQuery to PHP file but I'm getting "Undefined index" errors every time I submit my form.
upload.html
<form id="formx" action="upload.php" onSubmit="return false" method="post" enctype="multipart/form-data">
<b>Upload new image</b> <br />
<input type="button" id="get_file" value="Grab file">
<div id="customfileupload">Select a file</div>
<input type="file" id="file_input" name="uploadedfile">
<br />
<input type="submit" name="upload" id="upload" value="Upload image" />
<div id="status"></div>
</div>
</form>
upload.js
var options = {
target: '#status',
type: "POST",
data: "dir=music",
dataType: "html",
beforeSubmit: beforeSubmit,
uploadProgress: OnProgress,
success: afterSuccess,
error: function(hr, ajaxOptions, thrownError)
{
status.html("<font color='red'> ERROR: unable to upload file.</font>"+thrownError);
},
resetForm: true
};
$('#formx').submit(function(event) {
$(this).ajaxSubmit(options);
event.preventDefault();
});
upload.php
<?php
echo "->".$_POST['dir'];
?>
It's obvious that I'm not sending the data correctly. I have tried changing the dataType , but still not getting the desired result. I would really appreciate if someone could advise me on how to fix this issue.
Thanks in advance,
Alex
Upvotes: 0
Views: 132
Reputation: 5672
Try sending the data as a JavaScript object and add the url that you want to send to. Your script will not take the URL from the form attribute by default.
data: {
"dir": "music"
},
url: "upload.php"
Taken from jQuery documentation
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
https://api.jquery.com/jQuery.ajax/
Upvotes: 2
Reputation: 776
the dataType parameter is actually for the data you get from the php file it does not relate to the data you send.
That being said, I think there should be a url element in the options array that should send the data to upload.php so you would have something like this:
var options = {
target: '#status',
url: '/path/to/upload.php',
type: "POST",
data: "dir=music",
dataType: "html",
beforeSubmit: beforeSubmit,
uploadProgress: OnProgress,
success: afterSuccess,
error: function(hr, ajaxOptions, thrownError)
{
status.html("<font color='red'> ERROR: unable to upload file.</font>"+thrownError);
},
resetForm: true
};
Upvotes: 0