Good evening guys, I got a problem in the back-end of my system when I submit my form. It said Unidentified index: file1 . I can't fine the error here in my code.
I'm not a newbie in javascript and seeking for help from you guys. Advance thank you.
So here is my HTML form
<form id="submit_form" action="<?php echo base_url()?>Homepage/add_blog" enctype="multipart/form-data" method="POST" >
<input type="text" class="form-control" id="title" name="title" autocomplete="off">
<input type="text" class="form-control" id="lead" name="lead" autocomplete="off">
<input type="text" id="tags" name="tags" data-role="tagsinput" placeholder="Add tags" class="form-control" >
<input type="file" id="file1" name="file1" >
<textarea id="content" name="content" rows="10" cols="80">
Put the content here!!!
</textarea>
</form>
Here is my script
<script>
function _(el)
{
return document.getElementById(el);
}
$(document).ready(function()
{
$('#submit').click(function(e)
{
e.preventDefault();
var file = _("file1").files[0];
var title = $('#title').val();
var lead = $('#lead').val();
var tags = $('#tags').val();
var content = $('#content').val();
if(title == '' || lead == '' || tags == '' || content =='')
{
$('#response').html('<br><div class="panel panel-danger"><div class="panel-body"><center><span class="text-danger">All fields are required</span></center></div></div>');
$('#response2').html('<div class="panel panel-danger"><div class="panel-body"><center><span class="text-danger">All fields are required</span></center></div></div><br>');
}
else
{
$.ajax({
url:"<?php echo base_url()?>Homepage/add_blog",
method:"POST",
data:$('#submit_form').serialize(),
beforeSend:function()
{
$('response').html('<span class="text-danger">Loading...</span>');
$('#submit').prop("disabled", true);
var formdata = new FormData();
formdata.append("file1",file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress",progressHandler,false);
ajax.addEventListener("load",completeHandler,false);
ajax.addEventListener("error",errorHandler,false);
ajax.addEventListener("error",abortHandler,false);
ajax.open("POST","<?php echo base_url()?>Homepage/add_blog");
ajax.send(formdata);
},
success:function(data)
{
$('form').trigger("reset");
$('#tags').tagsinput('removeAll');
$('#tags').tagsinput('destroy');
CKEDITOR.instances.content.setData('');
$('#response').fadeIn().html(data);
}
});
}
});
$('#title,#lead,#tags,#content').focus(function(){
$('#submit').prop("disabled", false);
});
});
function progressHandler(event)
{
_("loaded_n_total").innerHTML = "Uploaded "+event.loaded;
var percent = (event.loaded/event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% uploaded.. please wait";
}
function completeHandler(event)
{
_("progressBar").value = 0;
}
function errorHandler(event)
{
_("status").innerHTML = "Upload Failed.";
}
function abortHandler(event)
{
_("status").innerHTML = "Upload Aborted.";
}
</script>
And the problem relies here in the back-end Homepage/add_blog:
$filename = $_FILES["file1"]["name"];
echo $filename;
If you any more details needed to solve this. Just comment. Need to fix this as soon as possible. Thank you again.
Undefined index notice that the array $_FILES does not contain the "file1" key set. Probably the way you are trying to send the file via ajax is not working properly.
I'd recommend you try to use FormData. I believe the link below is a good reference to solve your problem.
How to use FormData for ajax file upload
Related
I've been following along a tutorial, but I just can't make it to work. One hour of trying to figure it out, but nothing. This AJAX request returns nothing. I'm a beginner. Help is appreciated.
<form id="postForm">
<input type="text" name="name" id="name1">
<input type="submit" value="submit">
</form>
<script type="text/javascript">
document.querySelector('#postForm').addEventListener('submit', loadText5)
function loadText5(e) {
e.preventDefault();
let name = document.getElementById('name1').value;
let params = "name"+name;
let response = new XMLHttpRequest();
response.open('POST', 'process.php', true);
response.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
response.onload = function() {
console.log(this.responseText);
}
response.send(params);
}
</script>
Process.php
if (isset($_POST['name'])) {
return 'POST: Your name is ' . $_POST['name'];
}
I have 2 files in VIEW folder: addcustomer.php and phoneError.php.
addcustomer.php
<input type="text" id="textHint" onKeyUp="showHint(this.value)" name="phone" placeholder="1235558888">
<span id="txtHint"></span>
<script type="text/javascript" >
function showHint(str) {
var base_url = <?php echo base_url(); ?>
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
// Get $p from phoneError.php
(xmlhttp.open("GET", "phoneError.php?p=" + str, true));
xmlhttp.send();
}
}
</script>
<input type="text" id="textHint" onKeyUp="showHint(this.value)" name="phone" placeholder="1235558888">
<span id="txtHint"></span>
phoneError.php
<?php
defined('BASEPATH') || exit('No direct script access allowed');
$p = $_REQUEST['p']; // required
$string_exp = "/^[0-9]{3}[0-9]{3}[0-9]{4}$/";
if ($p == !preg_match($string_exp, $p)) {
echo $error_message .= '<span style="color:red">Oops! The Phone you entered does not appear to be valid.</span>';
}
?>
I want to add Ajax function into onkeyup event in addcustomer form to check valid phone number entered. I called addcustomer method and also loaded phoneError in Controller but did not work. I am not sure I put correct url for xmlhttp.open "GET".
Well if your are using Codeigniter you should know basic structure of it.
So put php code in same controller file which loads your view and name it as
public function phoneError(){
// your php code..
}
In html side
change id of span as id should be unique in same page.
Replace
<span id="txtHint"></span>
with this
<span id="txtResult"></span>
In input tag remove onKeyUp attr.
So replace with this
<input type="text" id="textHint" name="phone" placeholder="1235558888">
And some change in js
So basically your view file is as
addCustomer.php
<input type="text" id="textHint" name="phone" placeholder="1235558888" value="">
<span id="txtResult"></span>
<script type="text/javascript" >
$(document).ready(function () {
$("#textHint").keyup(function () {
var str = $(this).val();
$.get("http://localhost/sitename/controllername/phoneError?p=" + str, function (data) {
$("#txtResult").html(data);
});
});
});
</script>
Now try with this.
You can use this jquery code for your purpose. This code do exactly same that you want.
$("#textHint").keyup(function () {
$.get("phoneError.php?p=" + $(this).val(), function (data) {
$("#txtHint").html(data);
});
});
i am quite new to javascript.
What this example code does, is easy, I know.
Everything is working fine - at the end 'firstname' and 'lastname' is printed to the #status div.
Can anyone tell me how to fade that div after 5 seconds once it was filled through javascript?
This is my code:
index.html
<html>
<head>
<script src="ajax.js"></script>
</head>
<body>
<h3>Testpage</h3>
First Name: <input id="fn" name="first_name" type="text"> <br><br>
Last Name: <input id="ln" name="last_name" type="text"> <br><br>
<input name="sbmt" type="submit" value="Submit" onclick="ajax();"> <br><br>
<div id="status"></div>
</body>
</html>
ajax.js
function ajax_post(){
var hreq = new XMLHttpRequest();
var url = "php.php";
var fn = document.getElementById("fn").value;
var ln = document.getElementById("ln").value;
var vars = "fn="+fn+"&ln="+ln;
hreq.open("POST", url, true);
hreq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hreq.onreadystatechange = function() {
if(hreq.readyState == 4 && hreq.status == 200) {
var return_data = hreq.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hreq.send(vars);
document.getElementById("status").innerHTML = "processing...";
}
php.php
<?php
echo 'Firstname: '. $_POST['fn'] . '<br>Lastname: ' . $_POST['ln'];
?>
Thanks in advance!
Regards,
Andreas
You can use setTimeOut function after firstname and lastname is printed like below
setTimeout(function(){ document.getElementById("status").style.display='none' }, 5000);
What do I need to add to my code here to add the ability to upload a video?
<div id="title">Upload Videos</div>
<div class="vidUpload">
<form id="vidUpload" enctype="multipart/form-data">
<input name="vidName" type="text" required="required" id="vidName" placeholder="Enter Video Name Here" title="Video Name">
<br>
<textarea name="videoDescription" id="videoDescription" required class="videoDescription" placeholder="Enter Video Description Here" title="Enter Video Description Here"></textarea>
<select name="select" required class="choosevidCat" id="choosevidCat">
<option value="">Choose the Catagory for your Video Here</option>
<?php
$sql = ("SELECT albumId, albumName, albumSelect FROM albums");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($mysqli, $sql);
while($row = mysqli_fetch_array($result)) {
$albumid = ($row['albumId']);
$album_name = ($row['albumName']);
$album_name1 = ($row['albumSelect']);
echo "<option value=".$album_name1. ">$album_name</option>";
}
?>
<option id="createCat" value="createCatagory">Create New Catagory Here</option>
</select>
<input type="file" name="video" id="video">
<input type="button" name="videoToUpload" id="videoToUpload" value="Upload">
</form>
<div id="loader"></div>
<div id="viduploadResult"></div>
jquery
<script type="text/javascript">
$(document).ready(function() {
$("#videoToUpload").click(function() {
var vidName = $("#vidName").val();
var videoDescription = $("#videoDescription").val();
var albumName1 = $("#choosevidCat").val();
var vidFile =$("#video").val();
// Put an animated GIF image insight of content
$("#loader").empty().html('<img src="/images/loader.gif" class="vidloader1"/>');
$.post("includes/vid_upload.inc.php",{vidName: vidName, videoDescription: videoDescription, albumName1: albumName1, vidFile: vidFile}, function(json)
{
if(json.result === "success") {
$("#viduploadResult").html( "The Video "+vidName+" has been Uploaded!");
// // First remove all the existing options
// $('#choosevidCat').empty();
//
// // Load the content:
// $('#choosevidCat').load(location.href + "#choosevidCat > *");
}else{
$("#viduploadResult").html(json.message);
}
});
});
})
</script>
I have spent hours looking at API's like blueimp etc, I just want to upload a video file and put it on my server from the form I have here.
Any help would be greatly appreciated
You are just passing the value of input type file. You should pass the file stream to your server script. Here is a sample code for uploading files using jquery.
Note: I am writing only jquery code to submit file. You must have to write server side code (PHP script) to upload the requested file.
Following code will help you to upload files. Customize it according to your scenario
if($("#video")[0].files.length)
{
this.total_files = $("#video")[0].files.length;
this.start_process = 0;
$.each($("#video")[0].files, function(i,o){
var files = new FormData();
files.append(1, o);
});
$.ajax({
url:"http://example.com",
method:"POST",
contentType:false,
processData: false,
data:files,
async:true,
xhr: function()
{
if(window.XMLHttpRequest)
{ var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with upload progress
}
}, false);
}
},
success:function(data){
alert("file uploaded..");
}
});
}
After further research I found this script and video tutorial which provided a resolution, so thought I would add it to my own question
Web Tutorial
https://www.developphp.com/video/JavaScript/File-Upload-Progress-Bar-Meter-Tutorial-Ajax-PHP
Video Tutorial
http://www.youtube.com/watch?v=EraNFJiY0Eg
I am trying to get my HTML form to pass through Javascript that will then pass it to PHP that will send it to MySQL.
However I either get the page to load the JS file in the browser, or the PHP file to load in the browser.
Here is my HTML form:
<div class="form" id="form" onclick="submitForm()">
<form id='contactform' action="js/contactform.js" method="post" onSubmit="submitForm()">
<input type="text" id="name" placeholder="Name" autofocus required><br>
<input type="text" id="email" placeholder="Email" required><br>
<input type="tel" id="telephone" placeholder="Telephone"><br>
Enquiry : <input type="radio" id="subject" value="enquiry" required>
Booking : <input type="radio" id="subject" value="booking" required><br>
<textarea id="message" required rows="20" cols="20" placeholder="Enter your message and I will try to get back to you within 2 days."></textarea><br>
<input type="submit" name="submit" value="Submit" class="submitbutton"/>
<input type="reset" name="clearbutton" value="Clear" class="clearbutton"/>
</form>
<div id="outcome"></div>
I want the outcome of the form submit placed into the "outcome" div
My JS code:
function getOutput() {
getRequest(
'php/getinfo.php',
drawOutput,
drawError
);
return false;
}
// handles drawing an error message
function drawError () {
var container = document.getElementById("content");
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById("content");
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req .readyState == 4){
return req.status === 200 ?
success(req.responseText) : error(req.status)
;
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
function submitForm(){
var name = document.getElementById('name').value;
var booking = document.getElementById('subject').value;
var enquiry = document.getElementById('subject').value;
var email = document.getElementById('email').value;
var telephone = document.getElementById('telephone').value;
var message = document.getElementById('message').value;
getRequest(
'php/form.php?' + params, //URL for the PHP file
procesOutput,
processError
);
return false;
}
function processOutput(){
var container = document.getElementById('outcome');
container.innerHTML = responseText;
}
function processError(){
alert("There has been an error, please try again");
}
and my PHP code:
$con=mysqli_connect("DBLocation","Username","Password",'DBName');
if (mysqli_connect_errno()){
die("Error: " . mysqli_connect_error());
}
$result = mysqli_query($con,"INSERT INTO `Contact`(`Name`, `Email`, `Telephone`, `Enquiry`, `Booking`, `Message`) VALUES ([value-2],[value-3],[value-4],[value-5],[value-6],[value-7])");
if ($conn->query($sql) === TRUE){
echo "Thank you for contacting us, I will replay to you soon!";
}
else {
echo "I'm sorry but an Error has occured. Please try again shortly";
}
mysql_close($conn);
?>
I've had a look at w3schools pages and some other questions on here but I can't seem to get my head around it.
A couple of things, first off what is getRequest? Second off, where is responseText defined? Third, I would check your console as I'm pretty sure there is an error in submitForm. I see lots of getElementByIds, but none of your inputs have ids associated with them:
<input type="text" name="name" placeholder="Name" autofocus required>
Should be:
<input type="text" id="name" placeholder="Name" autofocus required>
I believe you want to use Ajax, which you can easily use with jQuery.
I believe the answer for your question is right on this page: https://learn.jquery.com/ajax/ajax-and-forms/
If jQuery is new for you, you might want to read a little about jQuery: https://learn.jquery.com/about-jquery/
If you don't want to use jQuery, you can use directly XMLHttpRequest in javascript instead.
Here is a demo in JSFiddle.
Remove onClick, onSubmit, action="js/contactform.js" method="post" attributes as you don't need them. Capture the form submit in js. How to? - link
Add id's on the form elements so than you can select them like:
var name = document.getElementById('name').value;
Make a $.post request with jQuery (How to? - Link) and handle the success and failure callbacks. (I don't understand why are you making a post request, I would recommend you a $.get request.