I started learning laravel, and attempt to make a website with it. I'm trying implement "uploading a crop image". I'm using croppie https://foliotek.github.io/Croppie/ and manage to successfully displaying on the browser.
Now, I want to save the image to the database. I'm struggling at this stage, I've spent hours searching and trying but it doesn't seem to work. I've read that laravel doesn't use the patch method to send crop images as well as I need ajax. Can someone help me how I would get the base64 from the form. This is my form:
<form action="{{route('program.updateImage', ['id'=> $program->id])}}" method="post" enctype="multipart/form-data">
{{ method_field('PATCH') }}
{{ csrf_field() }}
<div id="crop" class="croppie-container">
</div>
<a class="upload-file">
<span>Upload</span>
<input type="file" name="image" id="upload"><br>
</a>
<br>
<input type="submit" name="submit" value="Save image">
</form>
This is my route:
Route::patch('program/image/{id}', 'ProgramController#updateImage')->name('program.update');
Code for croppie
$(function() {
var basic = $('#crop').croppie({
viewport: {
width: 400,
height: 200
},
boundary: { width: 400, height: 300 },
});
basic.croppie('bind', {
url: '{{asset('images/'.$program->image)}}'
});
});
function readFile(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#crop').croppie('bind', {
url: e.target.result
});
}
reader.readAsDataURL(input.files[0]);
}
}
$('.upload-file input').on('change',function(){
readFile(this);
});
and my function:
public function updateImage(Request $request, $id){
//$this->validate($request, array('image' => 'mimes:jpeg,jpg,png'));
$program = Program::find($id);
//list($type, $data) = explode(';', $data);
//list(, $data) = explode(',', $data);
//$data = base64_decode($data);
echo $request;
}
Here jquery code for upload image
$('#crop_img_upload_button').on('click', function (e) {
var image_data = $('#crop').croppie('result', 'base64');
if (image_data != '') {
var formData = $('#crop_it_form').serialize();
$.ajax({
type: "POST",
url: "uploadUrl",
data: formData,
cache: false,
success: function (data)
{
//response here
}
});
} else {
// validation msg here
}
});
});
To get base64 of image use this :
var base64 = $('#crop').croppie('result', 'base64');
Related
I select an image, write something and then click submit. Once I click submit it posts to the DB, shows progress bar of upload successfully BUT the upload.php file is never called.
Question: What is wrong with my code, that is preventing the upload.php file from being called in the action="".
It was working at one point in time but I can't remember what changes I made for it.
UPDATED SCRIPT:
$('#feed_form').submit(function(e) {
var data = new FormData(this);
var url = $(this).attr("action");
if($('#file12').val()) {
$("#progress-div").show("slow");
e.preventDefault();
$.ajax({
type: "POST",
url: "scripts/universal/upload.php",
data: data,
processData: false,
contentType: false,
success: function() {
$("#success_post").slideDown();
setTimeout(function() {
$('#success_post').slideUp();
}, 3000);
},
uploadProgress: function (event, position, total, percentComplete){
$("#progress-bar").width(percentComplete + '%');
$("#progress-bar").html('<div id="progress-status">' + percentComplete +' %</div>')
},
resetForm: true
});
return false;
}
});
<form name="feed_form" id="feed_form" method="post" enctype="multipart/form-data">
<textarea class="list-group-item p-x-md" id="textarea_writing" name="textarea_writing" style="resize:none;padding:5px;width:100%;" placeholder="What's going on....."></textarea>
<script type="text/javascript">
var textarea = document.getElementById("textarea_writing");
textarea.oninput = function() {
textarea.style.height = "";
textarea.style.height = Math.min(textarea.scrollHeight, 300) + "px";
};
</script>
<span id="show_error_message"></span>
<br>
<label class="custom-file" style="width:100%;">
<input type="file" name="file12" id="file12" class="custom-file-input" onchange="setfilename(this.value);" accept=".jpg, .jpeg, .gif, .png, .mp4" required>
<span class="custom-file-control">Select photo, video or gif...</span>
</label>
<br><br>
<button type="submit" id="btnSubmitFormClick">Post</button>
</form>
PHP:
if(!empty($_FILES)) {
if(is_uploaded_file($_FILES['file12']['tmp_name'])) {
$sourcePath = $_FILES['file12']['tmp_name'];
$targetPath = "images/uploads/".$_FILES['file12']['name'];
move_uploaded_file($sourcePath,$targetPath);
shell_exec("ffmpeg -f mp4 -i images/uploads/".$_FILES['file12']['name']." -ss 00:00:5.000 -vframes 1 images/uploads/".basename($_FILES['file12']['name'], ".mp4").".png");
//This line does not affect the code, it works perfectly fine when I try it with some different JS
}
}
You've not specified the url in $.ajax(). Maybe that's the only problem
Below is the corrected code, try it and let me know if it worked or not
<script type="text/javascript">
$(document).ready(function () {
$('#feed_form').submit(function (e) {
var url = $(this).attr("action");
var data = new FormData(this);
if ($('#file12').val()) {
if (!$("#btnSubmitFormClick").val()) {
$("#show_error_message").innerHTML = "Please write something before clicking submit";
} else {
$("#progress-div").show("slow");
e.preventDefault();
$.ajax({
url: url,
data: data,
cache: false,
processData: false,
contentType: false,
success: function () {
$("#success_post").show();
},
uploadProgress: function (event, position, total, percentComplete) {
$("#progress-bar").width(percentComplete + '%');
$("#progress-bar").html('<div id="progress-status">' + percentComplete + ' %</div>')
},
resetForm: true
});
return false;
}
}
});
$("#btnSubmitFormClick").click(function () {
document.getElementById("close_status_modal").click();
});
$("#feed_form").submit(function (e) {
$.ajax({
type: "POST",
url: "scripts/universal/post.php",
data: $("#feed_form").serialize(), // serializes the form's elements.
success: function (data) {
$('#textarea_writing').val('');
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
});
</script>
<form name="feed_form" id="feed_form" action="upload.php" method="post" enctype="multipart/form-data">
<textarea class="list-group-item p-x-md" id="textarea_writing" name="textarea_writing" style="resize:none;padding:5px;width:100%;" placeholder="What's going on....."></textarea>
<script type="text/javascript">
var textarea = document.getElementById("textarea_writing");
textarea.oninput = function () {
textarea.style.height = "";
textarea.style.height = Math.min(textarea.scrollHeight, 300) + "px";
};
</script>
<span id="show_error_message"></span>
<br>
<label class="custom-file" style="width:100%;">
<input type="file" name="file12" id="file12" class="custom-file-input" onchange="setfilename(this.value);" accept=".jpg, .jpeg, .gif, .png, .mp4" required>
<span class="custom-file-control">Select photo, video or gif...</span>
</label>
<br><br>
<button type="submit" id="btnSubmitFormClick" style="display:none;">Post</button>
</form>
I ended up using the following code to solve my problem:
function _(el) {
return document.getElementById(el);
}
function uploadFile() {
var file = _("file12").files[0];
var formdata = new FormData();
formdata.append("file12", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.open("POST", "scripts/universal/upload.php");
ajax.send(formdata);
}
function progressHandler(event) {
var percent = (event.loaded / event.total) * 100;
$("#progress-div").show();
_("progressBar").value = Math.round(percent);
}
function completeHandler(event) {
_("progressBar").value = 0;
$("#progress-div").hide();
}
I have a html form with 2 input filed and a file upload form and i want to send these data to some index.php file using ajax what i did so far is
<form class="col-md-3" id="form" name="reg" method="post" action="index.php" enctype="multipart/form-data">
<label>Name</label>
<input type="text" name="name" class="form-control" id="name">
<label>Address</label>
<input type="text" name="address" class="form-control">
<div id="sugg">
</div>
<input type="file" name="file">
<input type="button" name="submit" class="btn-default" id="btn" value="submit">
</form>
jquery for send data using ajax is
$("#btn").click(function() {
$.ajax({
url: "index.php",
type: "POST",
data: new FormData($('form')[0]),
cache: false,
conentType: false,
processData: false,
success: function(result) {
console.log(result);
}
});
});
php file has just this
echo $_POST["name"];
but in my browser window i am undefined index
I found similar questions but all that doesn't solved my problem that's why i asking your help please help me to find my error
I am create below code according to my need and you can make changes according to your requirement:
when you click upload/select file button use this function :
$('input[type=file]').on('change', function(e){
e.preventDefault();
$this = $(this);
if($this.prop("files")){
if(setImagestoUpload(e, $this.prop("files"), $this.attr("name"))){
var reader = new FileReader();
reader.onload = function(e){
$('.brandLogo img').attr("src", e.target.result);
$this.parent().prev("img.imageSelection").attr("src", e.target.result);
};
reader.readAsDataURL(this.files[0]);
}
}
});
function setImagestoUpload(e, $file, name){
e.preventDefault();
var type = [];
var isSize = [];
$($file).each(function(i, v){
type[i] = isImage(v);
isSize[i] = isValidSize(2, v.size);
});
if($.inArray(false, type) === -1){
if($.inArray(false, isSize) === -1){
/*if(checkTotalFileInputs() > 1 && files.length>0){
$.each($file, function(ind, val){
files[name] = val;
});
files[name] = $file[0];
}else{
files = $file;
}*/
formData.append(name, $file[0]);
console.log(files);
return true;
}else{
alert("Error: Upload max size limit 2MB");
}
}else{
alert("Please select only image file format to upload !");
return false;
}
}
function isImage(file){
var type = file.type.split("/");
if(type[0] === "image"){
return true;
}else{
return false;
}
}
and when you submit form then use below function:
function fileAndFormSubmit(ev, $this, get, options){
var defaults = {
redirect : false,
redirectTo : "#",
redirectAfter : 5000
};
var settings = $.extend({}, defaults, options);
removeErrorAndSuccess();
var $form = $($this).parent('form');
/*var formData = new FormData();
if(files.length > 0){
$.each(files, function(key, val){
formData.append(key, val);
});
}*/
var doc = {
data : $form.serialize()
};
formData.append("doc", doc.data);
/*Call to ajax here*/
}
I've create one form which is given below
html code:
<form method="post" class="inline" id="upload_form" enctype="multipart/form-data">
<input style="margin-top:0px;" type="file" name="data1" id="file1" class="btn btn-block btn-primary"/>
<input type="hidden" name="_token" value="{{ csrf_token() }}" id="token">
link submit
</form>
ajax code:
function create()
{
alert();
var file = document.getElementById('file1');
var token = document.getElementById('token').value;
var data1 = new FormData($("#upload_form")[0]);
var route = "http://localhost:8080/form";
console.log(FormData);
console.log(data1);
$.ajax({
type:'POST',
url: route,
headers: {'X-CSRF-TOKEN': token},
contentType: false,
processData: false,
data:{
'data1': data1,
},
success:function(e){
if(e == 0)
{
alert("Success Full Created");
}
else
{
alert("Error");
}
}
});
}
This is my route :
Route::post('form', 'StoreController#newstore');
I've created controller which is given below
Controller :
public function newstore(Request $request)
{
$post = $request->file('data1');
dd($post);
//If there is error try dd($post) and let me know
// we need know if the data file image is passing to controller
$imageName = $post->getClientOriginalName();
$imagemove= $post->move(public_path('images'),$imageName);
$data123 = array ( "photo"=> $imageName, );
$check222 = DB::table('product') -> insert($data123);
}
when i run this code its show me this error :
MethodNotAllowedHttpException in RouteCollection.php line 218:
Try this:
<form method="post" class="inline" id="upload_form" enctype="multipart/form-data">
<input style="margin-top:0px;" type="file" name="data1" id="file1" class="btn btn-block btn-primary"/>
<input type="hidden" name="_token" value="{{ csrf_token() }}" id="token">
link submit
</form>
if for example your route is:
Route::post('form', 'yourcontroller#newstore');
JS
function create()
{
var file = document.getElementById('file1');
var route = "http://localhost:8000/form";
var token = document.getElementById('token').value;
var data1 = new FormData($("#upload_form")[0]);
// we are using "$", i hope that you have jquery library
/* alternative you can do:
var getUpload = document.queryselector('#upload_form');
var data1 = getUpload[0];
*/
//if there is error try also console.log(formData)
// if error try console-log(data1); info about the file uploaded
// if error token verify console.log(token); have the token serial number
$.ajax({
type:'POST',
url: route,
headers: {'X-CSRF-TOKEN': token},
contentType: false,
processData: false,
data:{
'data1': data1,
},
success:function(e){
if(e == 0)
{
alert("Success Full Created");
}
else
{
alert("Error");
}
}
});}
var submit = document.querySelector('#submit').onclick= create
CONTROLLER
public function newstore(Request $request)
{
$post = $request->file('data1');
//If there is error try dd($post) and let me know
// we need know if the data file image is passing to controller
$imageName = $post->getClientOriginalName();
$imagemove= $post->move(public_path('images'),$imageName);
$data123 = array ( "photo"=> $imageName, );
$check222 = DB::table('product') -> insert($data123);
}
Let me know if you get some error! i hope it work!
Q.1 I would like to convert this form to ajax but it seems like my ajax code lacks something.
On submit doesn't do anything at all.
Q2. I also want the function to fire on change when the file has been selected not to wait for a submit.
Here is JS.
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault()
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:$(this).serialize(),
cache:false
});
}));
and the HTMl with php.
<form name="photo" id="imageUploadForm" enctype="multipart/form-data" action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
<input type="file" style="widows:0; height:0" id="ImageBrowse" hidden="hidden" name="image" size="30"/>
<input type="submit" name="upload" value="Upload" />
<img width="100" style="border:#000; z-index:1;position: relative; border-width:2px; float:left" height="100px" src="<?php echo $upload_path.$large_image_name.$_SESSION['user_file_ext'];?>" id="thumbnail"/>
</form>
first in your ajax call include success & error function and then check if it gives you error or what?
your code should be like this
$(document).ready(function (e) {
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
}));
$("#ImageBrowse").on("change", function() {
$("#imageUploadForm").submit();
});
});
HTML Code
<div class="rCol">
<div id ="prv" style="height:auto; width:auto; float:left; margin-bottom: 28px; margin-left: 200px;"></div>
</div>
<div class="rCol" style="clear:both;">
<label > Upload Photo : </label>
<input type="file" id="file" name='file' onChange=" return submitForm();">
<input type="hidden" id="filecount" value='0'>
Here is Ajax Code:
function submitForm() {
var fcnt = $('#filecount').val();
var fname = $('#filename').val();
var imgclean = $('#file');
if(fcnt<=5)
{
data = new FormData();
data.append('file', $('#file')[0].files[0]);
var imgname = $('input[type=file]').val();
var size = $('#file')[0].files[0].size;
var ext = imgname.substr( (imgname.lastIndexOf('.') +1) );
if(ext=='jpg' || ext=='jpeg' || ext=='png' || ext=='gif' || ext=='PNG' || ext=='JPG' || ext=='JPEG')
{
if(size<=1000000)
{
$.ajax({
url: "<?php echo base_url() ?>/upload.php",
type: "POST",
data: data,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function(data) {
if(data!='FILE_SIZE_ERROR' || data!='FILE_TYPE_ERROR' )
{
fcnt = parseInt(fcnt)+1;
$('#filecount').val(fcnt);
var img = '<div class="dialog" id ="img_'+fcnt+'" ><img src="<?php echo base_url() ?>/local_cdn/'+data+'"></div><input type="hidden" id="name_'+fcnt+'" value="'+data+'">';
$('#prv').append(img);
if(fname!=='')
{
fname = fname+','+data;
}else
{
fname = data;
}
$('#filename').val(fname);
imgclean.replaceWith( imgclean = imgclean.clone( true ) );
}
else
{
imgclean.replaceWith( imgclean = imgclean.clone( true ) );
alert('SORRY SIZE AND TYPE ISSUE');
}
});
return false;
}//end size
else
{
imgclean.replaceWith( imgclean = imgclean.clone( true ) );//Its for reset the value of file type
alert('Sorry File size exceeding from 1 Mb');
}
}//end FILETYPE
else
{
imgclean.replaceWith( imgclean = imgclean.clone( true ) );
alert('Sorry Only you can uplaod JPEG|JPG|PNG|GIF file type ');
}
}//end filecount
else
{ imgclean.replaceWith( imgclean = imgclean.clone( true ) );
alert('You Can not Upload more than 6 Photos');
}
}
Here is PHP code :
$filetype = array('jpeg','jpg','png','gif','PNG','JPEG','JPG');
foreach ($_FILES as $key )
{
$name =time().$key['name'];
$path='local_cdn/'.$name;
$file_ext = pathinfo($name, PATHINFO_EXTENSION);
if(in_array(strtolower($file_ext), $filetype))
{
if($key['name']<1000000)
{
#move_uploaded_file($key['tmp_name'],$path);
echo $name;
}
else
{
echo "FILE_SIZE_ERROR";
}
}
else
{
echo "FILE_TYPE_ERROR";
}// Its simple code.Its not with proper validation.
Here upload and preview part done.Now if you want to delete and remove image from page and folder both then code is here for deletion.
Ajax Part:
function removeit (arg) {
var id = arg;
// GET FILE VALUE
var fname = $('#filename').val();
var fcnt = $('#filecount').val();
// GET FILE VALUE
$('#img_'+id).remove();
$('#rmv_'+id).remove();
$('#img_'+id).css('display','none');
var dname = $('#name_'+id).val();
fcnt = parseInt(fcnt)-1;
$('#filecount').val(fcnt);
var fname = fname.replace(dname, "");
var fname = fname.replace(",,", "");
$('#filename').val(fname);
$.ajax({
url: 'delete.php',
type: 'POST',
data:{'name':dname},
success:function(a){
console.log(a);
}
});
}
Here is PHP part(delete.php):
$path='local_cdn/'.$_POST['name'];
if(#unlink($path))
{
echo "Success";
}
else
{
echo "Failed";
}
You can use jquery.form.js plugin to upload image via ajax to the server.
http://malsup.com/jquery/form/
Here is the sample jQuery ajax image upload script
(function() {
$('form').ajaxForm({
beforeSubmit: function() {
//do validation here
},
beforeSend:function(){
$('#loader').show();
$('#image_upload').hide();
},
success: function(msg) {
///on success do some here
}
}); })();
If you have any doubt, please refer following ajax image upload tutorial here
http://www.smarttutorials.net/ajax-image-upload-using-jquery-php-mysql/
Image upload using ajax and check image format and upload max size
<form class='form-horizontal' method="POST" id='document_form' enctype="multipart/form-data">
<div class='optionBox1'>
<div class='row inviteInputWrap1 block1'>
<div class='col-3'>
<label class='col-form-label'>Name</label>
<input type='text' class='form-control form-control-sm' name='name[]' id='name' Value=''>
</div>
<div class='col-3'>
<label class='col-form-label'>File</label>
<input type='file' class='form-control form-control-sm' name='file[]' id='file' Value=''>
</div>
<div class='col-3'>
<span class='deleteInviteWrap1 remove1 d-none'>
<i class='fas fa-trash'></i>
</span>
</div>
</div>
<div class='row'>
<div class='col-8 pl-3 pb-4 mt-4'>
<span class='btn btn-info add1 pr-3'>+ Add More</span>
<button class='btn btn-primary'>Submit</button>
</div>
</div>
</div>
</form>
</div>
$.validator.setDefaults({
submitHandler: function (form)
{
$.ajax({
url : "action1.php",
type : "POST",
data : new FormData(form),
mimeType: "multipart/form-data",
contentType: false,
cache: false,
dataType:'json',
processData: false,
success: function(data)
{
if(data.status =='success')
{
swal("Document has been successfully uploaded!", {
icon: "success",
});
setTimeout(function(){
window.location.reload();
},1200);
}
else
{
swal('Oh noes!', "Error in document upload. Please contact to administrator", "error");
}
},
error:function(data)
{
swal ( "Ops!" , "error in document upload." , "error" );
}
});
}
});
$('#document_form').validate({
rules: {
"name[]": {
required: true
},
"file[]": {
required: true,
extension: "jpg,jpeg,png,pdf,doc",
filesize :2000000
}
},
messages: {
"name[]": {
required: "Please enter name"
},
"file[]": {
required: "Please enter file",
extension :'Please upload only jpg,jpeg,png,pdf,doc'
}
},
errorElement: 'span',
errorPlacement: function (error, element) {
error.addClass('invalid-feedback');
element.closest('.col-3').append(error);
},
highlight: function (element, errorClass, validClass) {
$(element).addClass('is-invalid');
},
unhighlight: function (element, errorClass, validClass) {
$(element).removeClass('is-invalid');
}
});
$.validator.addMethod('filesize', function(value, element, param) {
return this.optional(element) || (element.files[0].size <= param)
}, 'File size must be less than 2 MB');
$(document).on('change', '#photo', function() {
var property = document.getElementById('photo').files[0];
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
var url = './services/userProfile.php';
if (jQuery.inArray(image_extension, ['jpg', 'jpeg', 'png']) == -1) {
$('#msg').html('Invalid image file');
return false;
}
var form_data = new FormData();
form_data.append("file", property);
$.ajax({
url: url,
method: 'POST',
data: form_data,
contentType: false,
cache: false,
processData: false,
beforeSend: function() {
$('#msg').html('Loading......');
},
success: function(data) {
const obj = JSON.parse(data);
$('.image').attr('src', 'upload/' + obj['data']);
$('#msg').html(obj['msg']);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form" action="" method="post" enctype="multipart/form-data">
<img src="upload/imag.jpg" class="mx-auto img-fluid img-circle d-block image" alt="avatar">
<h6 class="mt-2">Upload a different photo</h6>
<label class="custom-file">
<input type="file" id="photo" name="profilePicture" class="custom-file-input">
<span class="custom-file-control">Choose file</span>
</label>
<span id="msg" style="color:red"></span>
</form>
Here is simple way using HTML5 and jQuery:
1) include two JS file
<script src="jslibs/jquery.js" type="text/javascript"></script>
<script src="jslibs/ajaxupload-min.js" type="text/javascript"></script>
2) include CSS to have cool buttons
<link rel="stylesheet" href="css/baseTheme/style.css" type="text/css" media="all" />
3) create DIV or SPAN
<div class="demo" > </div>
4) write this code in your HTML page
$('.demo').ajaxupload({
url:'upload.php'
});
5) create you upload.php file to have PHP code to upload data.
You can download required JS file from here
Here is Example
Its too cool and too fast And easy too! :)
I am confused a little bit and I have no clues what am I looking for.
Although I will post here important parts so you may figureout and help me.
A part of PHP file:
if (empty($vid) || empty($entry)) {
$broken = TRUE;
}
if(!$broken) {
$video = parseVideoEntry($entry);
echo "
<div class=\"video_wrap\">
<div class=\"video_thumbnail\">
<a href=\"{$video->watchURL}\">
<img src=\"$video->thumbnailURL\">
</a>
</div>
</div>
<!-- More of structure parts here -->
";
}
A part of HTML structure:
<form action="" method="GET" style="margin: 5% 0;" id="youtube_fetch">
<input type="text" name="id" value="https://www.youtube.com/watch?v=VIDEO_ID_HERE" id="videoID_input" />
<input type="submit" id="fetch_submit" />
</form>
A part of jQuery / Ajax call:
$('#fetch_submit').on('click', function (e) {
var videoID = $('#videoID_input').val();
$.ajax({
url: 'inc/YouTube_API_Fetch_ID.php',
type: 'GET',
data: { id: videoID },
success: function (state) {
var newState = $.trim(state);
if (newState == '')
alert('Return an Error later!');
else
console.log(state);
}
});
e.preventDefault();
});
Ok so when I put valid youtube ID into the input field, it will return the else from ajax call (echo the html structure in console log).
The part that I don't know how to deal with is: "How to get that echoed HTML content/structure and append it into the <div id="youtube_content"></div> for example or directly to the body.
Use the .html() method:
$('#youtube_content').html(state);
References:
.html() - jQuery API Documentation
If I understand your question correctly:
$('#fetch_submit').on('click', function (e) {
var videoID = $('#videoID_input').val();
$.ajax({
url: 'inc/YouTube_API_Fetch_ID.php',
type: 'GET',
data: { id: videoID },
success: function (state) {
var newState = $.trim(state);
if (newState == '')
alert('Return an Error later!');
else {
$('<div />', {
id: 'youtube_content'
}).appendTo('body');
$('#youtube_content').html(state);
}
}
});
e.preventDefault();
});