I am trying to pass my data along with an image to php but it was throwing error undefined index my code is as follows
HTML
<form class="form-horizontal" name="event" id="event" enctype="multipart/form-data">
<input type="text" name="txtEName" id="txtEName" required/>
<input type="text" name="txtEFree" required placeholder="(in minutes)"/>
<input type="text" name="txtEFirstPay" required/>
<input type="text" name="txtEFirstDuration" placeholder="(in minutes)"/>
<input type="file" name="files[]" multiple/>
<button type="button" id="saveEvent">SAVE</button>
</form
AJAX
$("#saveEvent").on('click',(function() {
var formData = new FormData($("#event"));
$.ajax({
url: "saveEvent.php",
type: 'POST',
data: formData,
contentType: false,
cache: false
processData:false,
success: function(data)
{
//further...
}
});
}));
PHP
<?php
require_once ("Php/db_connect.php");
$name=$_REQUEST['txtEName'];
echo var_dump($name);
$free=$_REQUEST['txtEFree'];
fpay=$_REQUEST['TxtEFirstPay'];
$fduration=$_REQUEST['txtEFirstDuration'];
$filename=$_FILES['filename']['name'];
//upload code follows...
?>
When i try to echo $name its showing the error
Notice: Undefined index: txtEName
what is the problem in this.
anybody please help..
Related
Hi I have problem for no reasons. I need help. I am trying to upload files and text input to my db and I am using ajax and PHP code for that. I have looked through many StackOverflow posts and stuffs but still unable to fix this.
HTML:
<form method = "POST" enctype = "multipart/form-data" id="myform">
<label class="form-label text-start">Enter your Name</label>
<input class="form-control" name="name" type="text" id="myname" placeholder="John">
<label class="form-label">Title</label>
<input class="form-control" type="text" name="name" id="title" placeholder="Operator">
<label class="form-label">Your Cute Photo (format: jpg and png only, less than 500kb)</label>
<input class="form-control" name="file" id="imgfile" type="file">
</form>
JQuery/Javascript:
var file_data = $('#imgfile').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('name', $('#name').val());
form_data.append('title', $('#title').val());
$.ajax({
type: 'POST',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
url: 'save_data.php',
data: {form_data},
success: function(data){
//alert(php_script_response);
alert(data)
window.location = 'account.php';
}
});
Error:
Undefined index name
Undefined index title
Undefined index file
PHP:
$name = $_POST['name'];
$title = $_POST['title'];
$file = $_FILE...
//all the other PHP codes
JQuery version
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
There are two elements in your form with the same name so it is a lottery which is used when you request it. Admittedly you were using the element ID rather than the names so probably perfectly OK. With FormData you can supply a reference to the form itself as the argument and that should take care of the rest for you. You can supply that formdata object directly as the data parameter in the ajax request. I'm not a user of jQuery so had to mix your jQuery with some vanilla js but you should see the idea.
const form = document.forms.usrupload;
form.bttn.onclick = () => {
var form_data = new FormData(form);
$.ajax({
type: 'POST',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
url: 'save_data.php',
data: form_data,
success: function(data) {
alert(data)
window.location = 'account.php';
}
});
}
label {
display: block;
width: 100%;
margin: 1rem;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--
`label` elements should be associated with an input in one of two ways:
Using the `for="elemID"` or by wholly encompassing the input element as below
-->
<form name="usrupload" method="POST" enctype="multipart/form-data">
<label class="form-label text-start">Enter your Name
<input class="form-control" name="name" type="text" placeholder="John" />
</label>
<label class="form-label">Title
<input class="form-control" type="text" name="title" placeholder="Operator" />
</label>
<label class="form-label">Your Cute Photo (format: jpg and png only, less than 500kb)
<input class="form-control" name="file" type="file" />
</label>
<input type='button' name='bttn' value='Submit' />
</form>
The error is on
data: {form_data},
To change to
data: form_data,
I need to handle inputs from form post and I have no idea, how to do it in php, because when I write for example $_POST["header"], it var_dumps null.
I am creating formData object and inserting all inputs from form. Then posting it with ajax.
Can you please help me? I need to handle "header", "content", "password" and files.
<form method="post" enctype="multipart/form-data" id="uploadFiles">
<label for="newsHeader" id="headerLabel">Nadpis</label>
<input type="text" name="newsHeader" id="newsHeader">
<label for="content" id="contentLabel">Text novinky</label>
<textarea name="content" id="content"></textarea>
<label for="files" id="filesLabel">Fotky</label>
<input type="file" name="files" id="files" accept="image/jpeg" multiple>
<label for="password" id="passwordLabel">Heslo pro upload</label>
<input type="text" name="password" id="password">
<button type='submit' id='uploadFilesSubmit'>NAHRÁT</button>
</form>
$("#uploadFiles").submit(function(event){
event.preventDefault();
var formDataObj = new FormData(),
header = $("#newsHeader").val(),
content = $("#content").val(),
password = $("#password").val();
formDataObj.append("header", header);
formDataObj.append("content", content);
formDataObj.append("password", password);
$.each($("#files")[0].files, function(i, file) {
formDataObj.append('file', file);
});
console.log(Array.from(formDataObj));
$("#uploadFilesSubmit").html("<div class='buttonSubmitIcon'><i class='fas fa-sync'></i></div>");
$.ajax({
method: "POST",
url: "uploadNews.php",
data: {
formDataObj: formDataObj
},
dataType: 'json',
contentType: false,
processData: false,
success: function(results){
}, error: function(){
}
});
});
In uploadNews.php I have this:
exit(json_encode(var_dump($_POST["header"])));
It always returns "Undefined index: header", same as content or count($_FILES["file"]["name"])
All I want is to get somehow to posted values.. Thank you very much
You just to pass the actual formDataObj variable via your $.ajax. This is not the correct syntax to pass FormData via ajax => formDataObj: formDataObj
A FormData itself is an object which stores your data so what you are doing is making another object on top of it when you pass it via data
You can now var_dump(header) or var_dump($_FILES["file"]["name"]) to see everything coming to your PHP file.
Live Demo: (Change you jQuery code to this below and it will just work fine)
$("#uploadFiles").submit(function(event) {
event.preventDefault();
var formDataObj = new FormData(),
header = $("#newsHeader").val(),
content = $("#content").val(),
password = $("#password").val();
formDataObj.append("header", header);
formDataObj.append("content", content);
formDataObj.append("password", password);
$.each($("#files")[0].files, function(i, file) {
formDataObj.append('file', file);
});
$("#uploadFilesSubmit").html("<div class='buttonSubmitIcon'><i class='fas fa-sync'></i></div>");
$.ajax({
method: "POST",
url: "uploadNews.php",
data: formDataObj, //just pass the form Data object.
dataType: 'json',
contentType: false,
processData: false,
success: function(results) {
},
error: function() {
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" enctype="multipart/form-data" id="uploadFiles">
<label for="newsHeader" id="headerLabel">Nadpis</label>
<input type="text" name="newsHeader" id="newsHeader">
<label for="content" id="contentLabel">Text novinky</label>
<textarea name="content" id="content"></textarea>
<label for="files" id="filesLabel">Fotky</label>
<input type="file" name="files" id="files" accept="image/jpeg" multiple>
<label for="password" id="passwordLabel">Heslo pro upload</label>
<input type="text" name="password" id="password">
<button type='submit' id='uploadFilesSubmit'>NAHRÁT</button>
</form>
I am not able to get the response to ajax success call back function. The response form the server is being directly printed on the browser
<body>
<script>
$(document).ready(function() {
$.ajax({
url: $("#form").attr("action"),
type: "POST",
data: $("#form").serialize(),
success: function(data) {
alert(data);
}
});
});
</script>
<form action="a.php" method="post" id="form">
<input type="text" name="name" id="name" placeholder="name" />
<input type="submit" value="submit" />
</form>
</body>
my php code
<?php
echo 'hii';
?>
Can you Replace AJAX script below mentioned.
<form method="post" id="form">
<input type="text" name="name" id="name" placeholder="name" />
<input type="submit" value="submit" />
</form>
$("#form").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: 'a.php',
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
I am building a site, on which you can upload posts, just like facebook.
Everything works great except that at the moment you upload a post and after you uploaded it you can upload images to that post.
I would like to be able to upload the images to the post and then upload the post with the pictures. Here is my attempt:
The database image table
+-------------------------------------------------+
| image_id | user_id | image_name | post_id |
| 1 | 1 | bla | 2 |
+-------------------------------------------------+
The view
<script>
$(function () {
$("#imageUpload").submit(function (e) {
e.preventDefault();
var formData = new FormData($('#imageUpload')[0]);
$.ajax({
url: 'post/create', //Trying to call the controller
type: 'post',
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
});
});
</script>
<form action="<?php echo Config::get('URL');?>post/create" method="post" id="imageUpload" enctype="multipart/form-data">
<input type="text" name="post_text" placeholder="Post something" />
<input type="file" name="images[]" multiple required />
<input type="submit" value='post' autocomplete="off" />
</form>
The controller
public function create()
{
PostModel::createPost(strip_tags($_POST['post_text']));
PostModel::uploadPostImages($_POST['post_id']);
}
I leave out the model, as the functions there work fine.
How can I get the post id to use it in the image table before posting the post?
I would be beyond thankful for any kind of help!!
UPDATE
<script>
$("#imageUpload").submit(function (e) {
var fd = new FormData();
var imagefile= document.getElementById('imagefile');
var files = imagefile.files;
for (var i = 0; i < files.length; i++)
{
var file = files[i];
fd.append('imagefile[]', file, file.name);
}
fd.append("post_text", document.getElementById('post_text').value);
fd.append("post_id", document.getElementById('post_id').value);
$.ajax({
url: 'post/create',
type: 'POST',
data: fd,
cache: false,
contentType: false,
processData: false
});
return false;
});
});
</script>
<form action="<?php echo Config::get('URL');?>post/create" method="post" id="imageUpload" enctype="multipart/form-data">
<input type="text" name="post_text" id="post_text" placeholder="Post something" />
<input type="file" name="images[]" id="imagefile" multiple required />
<input type="hidden" name="post_id" id="post_id" value="post_id" />
<input type="submit" value='post' autocomplete="off" />
</form>
You cannot directly upload image via jquery ajax. Moreover you are allowing multiple files to be uploaded via ajax. Here is your code. It will let you upload multiple images with the input text value too.
$("#imageUpload").submit(function (e) {
var fd = new FormData();
var imagefile= document.getElementById('imagefile');
var files = imagefile.files;
for (var i = 0; i < files.length; i++)
{
var file = files[i];
fd.append('imagefile[]', file, file.name);
}
fd.append("post_text", document.getElementById('post_text').value);
fd.append("post_id", document.getElementById('post_id').value);
$.ajax({
url: 'post/create', //Trying to call the controller
type: 'POST',
data: fd,
cache: false,
contentType: false,
processData: false
});
return false;
});
});
Your updated html
<form action="<?php echo Config::get('URL');?>post/create" method="post" id="imageUpload" enctype="multipart/form-data">
<input type="text" name="post_text" id="post_text" placeholder="Post something" />
<input type="file" name="images[]" id="imagefile" multiple required />
<input type="hidden" name="post_id" id="post_id" value="<?=$_GET['post_id']?>" />
<input type="submit" value='post' autocomplete="off" />
I am trying to upload a file with ajax and php without page refresh and for submit.
my code is able to run and alert the valid message if I just do the preg_match, but when I add the rest of the validation which need to use the $_FILES[$filrec]["tmp_name"], it won't alert me the valid message.
What is wrong here? isn't it possible to upload the file without submitting the form with the following method?
There are bunch of different suggestions and examples with more complicated javascript or jquery methods, but I am trying to simply the ajax and leave the rest for PHP. is that possible with my bellow ajax function ?
Javascript :
var fileselected = $("#browse").val().replace(/C:\\fakepath\\/i, '');
setTimeout(function() {
$.ajax({
type: 'POST',
url: "ajax/extval.php",
data: {fileprs: fileselected},
dataType: 'json',
cache: false,
success: function(resuval) {
// file validation result
if (resuval === "valid"){
alert ("valid")
PHP :
<form id="upload" method="post" class="<?php echo $orvalue."<separator>".$user_id ?>" action="" enctype="multipart/form-data">
<div id="formcontent">
<label class="required" for="unitprice" title="Unit price"><input type="text" id="unitprice" name="unitprice" />Unit price</label>
<label class="required" for="qty" title="How many pcs"><input type="text" id="qty" name="qty" />Quanity</label>
<label class="required" for="express" title="Express within China"><input type="text" id="express" name="express" />Express</label>
<label class="required" for="linkURL" title="Insert a full URL http:\\"><input type="text" id="linkURL" name="linkURL" />Link</label>
<label for="yourdesc" title="Describe your need clearly"><textarea id="yourdesc" name="yourdesc"></textarea>Description<li><font size="-2">You can type 400 letters only, you typed :</li><li id="lettercounter"></li>letters</font></label>
<label for="formsubmit" class="nocontent"><input type="button" id="submitButton" href="#" class="progress-button" value="Add to order" /><strong>Note:</strong> Items marked <img src="../../images/required.jpg" alt="Required marker" width="20" height="20" /> are required fields</label>
</div>
</form>
PHP :
$filrec =mysql_real_escape_string($_POST['fileprs']);
if(preg_match("/\.(gif|png|jpg|JPG|jpeg|bmp|BMP)$/", $filrec))
{
$fileType = exif_imagetype($_FILES[$filrec]["tmp_name"]);
$allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
$allin = "valid";
echo json_encode($allin);
}
Appreciated
You can use the following PHP code to get the file received from Ajax:
$data = split(",",file_get_contents('php://input'));
$img_data = base64_decode($data[1]);
file_put_contents( 'uploads/' . $_SERVER['HTTP_X_FILENAME'],
$img_data );
You can use Following Ajax POST Request this will help you
<script>
$(document.body).on('click','.postDefects',function(){
var form_data = new FormData();
var defect = $(this).closest('tr').find( "input[name='defect_id']" ).val();
var txt_defect=$("#text_defect").val();
var upload_defect = document.getElementById("upload_defect").files[0];
form_data.append("upload_defect",upload_defect);
form_data.append("defect_id",defect_id);
form_data.append("txt_defect",txt_defect);
console.log(form_data);
$.ajax({
url:"postsample_defects.php",
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
beforeSend:function(){
$('#uploaded_image').html("<label class='text-success'>Image Uploading..</label>");
},
success:function(data)
{
$('#uploaded_image').html(data);
}
});
});
</script>