How to display image on successful image POST? - ajax

I am currently using Ajax to POST formdata (images) to my PHP application, where I then simply save the image.
My form:
<form method="POST" enctype="multipart/form-data" id="fileUploadForm">
<label>
Open file dialog
<input type="file" style="position: fixed; top: -100em" name="file">
</label>
</form>
My script:
$( document ).ready(function() {
$("#upload-pictures").click(function(){
var form = $('#fileUploadForm')[0];
var formData = new FormData(form);
$.ajax({
method: "POST",
type: "POST",
url: "http://localhost:8080/index/index.php",
enctype: "multipart/form-data",
data: formData,
processData: false,
contentType: false,
success: function (data) {
console.log("SUCCESS : ", data);
$('body').html('<img src="' + data + '" />'); //doesn't work
}
});
});
});
What's the best way for me to display this image (after it has been successfully uploaded) on my webpage? I tried using $('body').html('<img src="' + data + '" />');
but it didn't seem to work.
Any help would be truly appreciated.
Thanks

Thanks to #RatajS for the help. I finally got it working:
In my PHP:
$contents = base64_encode(file_get_contents($_FILES['file']['tmp_name']));
In my HTML/Javascript:
$("<img>").attr({src: "data:image/jpeg;base64," +data}).appendTo("body");

Related

Uploading file using link instead of button but receiving $_FILES array empty

In my upload file I keep receiving the rest of the form data
but $_FILES array comes up empty. Can you guys help me with why
i'm on sending the hidden input data but no the files data ?
I have this for the link
<li><a href='#' id='upload_linko' onClick='imgUpload(1)'><i class='icon-image2'></i> Update cover photo</a></li>
And this for the form
<form id='upform' method='post' enctype='multipart/form-data'>
<input type='file' id='upload1' name='upload1' style='visiblity: hidden ; width: 1px; height: 1px' />
<input type='hidden' id='profid' name='profid' value='xyz'>
<input type='hidden' id='query_type' name='query_type' value='cover'>
</form>
and my script is like this
$(document).on('change','#upload1' , function(){
var fd = new FormData($("#upform"));
var file_data = $('input[type="file"]')[0].files;
$.each(file_data, function(key, value)
{
fd.append('file', value);
});
var other_data = $('#upform').serializeArray();
$.each(other_data,function(key,input){
fd.append(input.name,input.value);
});
$.ajax({
url: 'xxxxxxxx.php',
type: 'POST',
data: fd,
success:function(data){
// $('#output').html(data);
},
cache: false,
contentType: false,
processData: false
});
});
function imgUpload(optype)
{
document.getElementById('upload1').click();
}

Joomla sending Data (special Image) with Ajax (Formdata)

Using Joomla:
My problem is when I submit the button, ajax send an empty data array back to my client. Debbuging in the console shows me that datas in the header but the preview and response values are empty.
Here is my code (I am using a modal form from bootstrap).
HTML in my default script:
<form action="<?php echo JRoute::_('index.php?option=com_addproduct&view=addproducts'); ?>" method="post" name="modalMessageForm" id="modalMessageForm" enctype="multipart/form-data">
<input type="file" id="message-image-upload" accept="image/*" style="display:none;" name="message-image-upload">
<textarea class="form-control message-textarea" id="message-textarea" placeholder="Nachricht..." name="new-message" rows="4"></textarea>
<button type="button" id="button-close-message" class="btn btn-default btn-block btn-message-close" style="display:none; margin-top:5px;"><?=JText::_( 'COM_ADDPRODUCT_MODAL_MESSAGES_CLOSE')?></button>
</form>
JQuery / Ajax:
$(document).on("submit", "#modalMessageForm", function(e)
{
var form = $('#modalMessageForm').get(0);
e.preventDefault();
var formData = new FormData(form);
for(var pair of formData.entries()) {
console.log(pair[0]+ ', '+ pair[1]);
}
$.ajax({
crossDomain: true,
type: "POST",
url: "index.php?option=com_addproduct&task=sendMessages&format=json",
data: formData,
dataType: "json",
processData: false
})
.done(function(data, textStatus, jqXHR){
console.log('Message: '+data.new-message+' PicName: '+data.img);
})
});
Here my controller.php:
public function sendMessages()
{
JResponse::setHeader('Content-Type', 'application/json', true);
$app = JFactory::getApplication();
$input = $app->input;
$new-message = $input->getString('new-message', '', 'RAW');
$img = $_FILES['message-image-upload']["name"];
$img = JFile::makeSafe($img);
$results=array(
'new-message' => 'new-message',
'img' => $img
);
echo json_encode($results);
$app->close();
}
I got the datas / variables in the console log.
it is:
new-message: null,
img: null
trying to set contentType: false will give me an 500 error.
Thank you very much
That´s the info from my network
enter image description here
I figure something out.
It´s the URL in my ajax command.
When I am using a normal url like
url: 'upload.php'
that will work and then I can set the
contentType: false,
But this is not safety enought.
I just want to use this url
url: "index.php?option=com_addproduct&task=sendMessages&format=json",
But then I got the error message that the view is not found. That´s very strange.

Form validation in codeigniter when ajax used to form submit

Form submit is not happened in this scenario..
$.ajax({
type: "POST",
async: false,
url: base_url+"register/registration_val",
data: "register_first_name="+first_name,
success: function(data){
$('#inferiz').html(data);
},
error: function(){
alert('error');
}
In your view you can add this:
<script type="text/javascript">
var base_url = "<?php print base_url(); ?>";
</script>
Plus try to alert and see the value of final url in ajax i.e alert(url);
Try adding a id to the firstname input
<script type="text/javascript">
$(document).on('submit','#form-reg',function(){ // #form-reg is id on form open tag
$.ajax({
url: "<?php echo base_url('register/registration_val');?>",
type: 'POST',
data: {
firstname: $('#firstname').val(),
},
dataType: 'html', // I perfer to use json
success: function(data){
$('#inferiz').html(data);
},
error: function(){
alert('error');
}
}
});
});
</script>
I would use dataType: json much easier that way to get data from controller
You used data: "register_first_name="+first_name, it's not correct. Correction is data: {register_first_name:first_name},
base_url like this var base_url = <?php echo base_url(); ?>
So, Bellow final code :
<script type="text/javascript">
jQuery(document).ready(function ($) {
var base_url = <?php echo base_url(); ?>
$.ajax({
url: base_url+"register/registration_val", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: {register_first_name:first_name}, // Data sent to server, a set of key/value pairs representing form fields and values
contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
}).done(function (data) {
$('#inferiz').html(data);
}).fail(function (data) {
console.log('failed');
});
}(jQuery));
</script>
Please verify your view part that whether you provided id same as in ajax function.
view part:
<form id="form-reg">
<input name="firstname" id="firstname" type="text" required placeholder="Enter firstname " >
<span id="name_validation" class="text-danger"></span>
<button name="submit" id="submit_button" onClick="myFunction();" >submit</button>
</form>
Then correct the base url path which has to be given inside php tag.
function myFunction() {
$.ajax({
url: "<?php echo base_url();?>register/registration_val",
type: "POST",
data:'firstname='+$("#firstname").val(),
success: function(msg)
{
alert('done..!');
}
});
}

Populate data from mysql to ListView (JQuery Mobile) using ajax

<div data-role="main" class="ui-content">
<ul data-role="listview" id="responsecontainer" >
</ul>
This is my html file.
var output = $('#responsecontainer');
$.ajax({
url: 'http://192.168.1.28/mobile/db_select.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var landmark = '<li><a href="#"><h2>'+item.tr_issue+'</h2>'
+ '<p>'+item.tr_assign+'</p></a></li>';
output.html(landmark);
console.log(output);
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
This is my JavaScript.
I want to populate my listview from my database(mysql) but the problem is when it generates the theme of jquery mobile di not work.
its like a simple unordered list. thanks in advance
Add $('ul').listview('refresh'); after appending the HTML
Show change your success callback as below
success: function(data, status){
$.each(data, function(i,item){
var landmark = '<li><a href="#"><h2>'+item.tr_issue+'</h2>'
+ '<p>'+item.tr_assign+'</p></a></li>';
output.html(landmark);
console.log(output);
});
$('ul').listview('refresh');
},

Pass ASP MVC3 textbox value to Ajax call

I have a simple ASP MVC3 #Html.TextBox that I'm using to input search criteria. However, I need to append the value to the URL in an Ajax call as a query string. How would I go about this? Below is the HTML in the view:
<div class="editor-field">
#Html.TextBox("searchString")
<span onclick='GetCompName(searchString);'>
<input type="image" src="#Url.Content("~/Content/Images/Filter.bmp")" alt="Filter" />
</span>
</div>
And here is the Ajax
function GetCompName(searchString) {
var request = $.ajax({
type: 'POST',
url: 'http://quahildy01/OrganizationData.svc/AccountSet?$select=AccountId,Name,neu_UniqueId&$filter=startswith(Name,' + searchString + ')',
dataType: 'html',
success: function (data) {
alert(data);
},
error: function (data) {
alert("Unable to process your resquest at this time.");
}
});
}
I will also want to output the returned value into another text box. If anyone knows how to do that that would be really helpful as well. Thanks!
the basic problem with your code is the searchString in onclick='GetCompName(searchString); always gonna be literally "serchString", you must specified the parameter in base the value in the input, like this $('.searchbox').val()
keep your javascript unobstructive.
HTML code
<div class="editor-field">
#Html.TextBox("searchString", null, new { #class = "serachbox" })
<span class="searchbox-trigger">
<input type="image" src="#Url.Content("~/Content/Images/Filter.bmp")" alt="Filter" />
</span>
</div>
Set de handler for the event span click
$(document).ready(function() {
$('.searchbox-trigger').click(GetProgramDetails);
});
and your ajax request
function GetProgramDetails() {
var request = $.ajax({
type: 'POST',
url: 'http://quahildy01/OrganizationData.svc/AccountSet?$select=AccountId,Name,neu_UniqueId&$filter=startswith(Name,' + $('.searchbox').val() + ')',
dataType: 'html',
success: function (data) {
alert(data);
},
error: function (data) {
alert("Unable to process your resquest at this time.");
}
});
}

Resources