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

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.

Related

How to display image on successful image POST?

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");

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();
}

File Data is blank array in server side: Laravel 5.3

I am trying to post File using JQuery. Below is my code.
<script language="javascript">
$(document).ready(function() {
$('#frmUpdateProfile').on("submit", function(event) {
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
var data = {
"FileName" : event.target.FileName.files,
"_token" : "{!! csrf_token() !!}"
};
$.ajax({
url: '{{URL::route("UpdateProfile")}}',
method: "POST",
async: true,
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=utf-8",
success: function (msg) {
SuccessCallback(msg);
},
error: function (jqXHR) {
ErrorCallback(jqXHR);
}
});
});
});
</script>
I tried processData: false,. While debugging in Js, you can check that image is coming in the data. Below is the screenshot.
But when I print the request data in Laravel, it show blank array.
Html form is here
<form method="POST"
action="http://localhost:1234/AS6-Code/public/UpdateProfile"
accept-charset="UTF-8"
enctype="multipart/form-data"
id="frmUpdateProfile">
<input name="_token" type="hidden" value="26KWkWdNqe5iOFE8VRBf1dRnL5xKxwN25jg3tAFW">
<input type="hidden" name="_token" value="26KWkWdNqe5iOFE8VRBf1dRnL5xKxwN25jg3tAFW">
<input multiple="1" name="FileName" type="file">
<input class="btn btn-info" type="submit" value="Update">
</form>
Am I doing something wrong?
Try sending your request with FormData instead:
var data = new FormData($('#frmUpdateProfile')[0]);
Also set contentType to false:
contentType: false
Also Update
event.target.FileName.files
to
event.target.FileName.files[0]
event.target.FileName.files is a FileList object. I believe you need event.target.FileName.files[0] instead.

cross-domain form post with ajax jsonp returns error: {"readyState":4,"status":200,"statusText":"success"}

I'm trying to post form data to a php file that will then handle a mysql request. But before I do the mysql, I'm trying to connect to the php file.
The request is Cross-Domain.
When i submit the form, i get the error: {"readyState":4,"status":200,"statusText":"success"}
You can see the test page here: http://jonathan-tapia.mybigcommerce.com/store-locator/
form code:
<div class="map-search">
<h1>Give us your zip code. We'll tell you where to find us.</h1>
<div id="map-form">
<form id="lookup-form" action="http://dev.visioncourse.com/customers/baldguy/index.php" method="post">
<p>Within
<select id="distance" name="distance">
<option value="10">10</option>
<option selected="selected" value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
miles of
<input id="zipcode" type="text" name="postalcode" value="" size="8" />
<input id="lookup" type="submit" value="Look Up" />
</p>
</form>
</div>
</div>
<div class="map-results"> </div>
updated JS:
<script type="text/javascript">// <![CDATA[
//submit form
$('#lookup-form').submit(function(event) {
event.preventDefault();
var formdata = $(this);
var link = formdata.attr('action');
var distance = $('#distance').val();
var zipcode = $('#zipcode').val();
console.log('.\n..\n...\n....\nSubmitting Form\n....\n...\n..\n.');
$.ajax({
crossDomain: true,
type: 'POST',
url: link,
data: {
'distance': distance,
'postalcode': zipcode
},
dataType: 'jsonp',
error: function(data) {
console.log('error: ' + data);
},
success: function(data) {
console.log('success: ' + data);
},
xhrFields: {
withCredentials: true
}
});
});
// ]]>
updated php file:
<?php
$arr = array();
$distance = $_POST['distance']
$zip = $_POST['postalcode'];
if(isset($distance) && isset($zip)) {
array_push($arrr, {'d': $distance, 'z': $zip});
}
echo json_encode($arr);
?>
error i'm receiving from console:
GET http://dev.visioncourse.com/customers/baldguy/index.php?callback=jQuery17203092896034941077_1451698154204&distance=25&postalcode=85251 jquery.min.js:4
EDIT:
The php file will get the distance and zip code from the form and connect to a mysql database for a google maps store locator. so when a person submits the radius and the zip code it will display results. but all of this will be on the php file.
The file doing the form submission will submit the form, wait for the php to do it's work, then display the php file with the results
Try it with data: {"distance": distance, "zipcode": zipcode},.
In your code you insert the value of the variables twice instead of a name and a value.
Also, you need to send the zipcode with the name of 'postalcode'. Otherwise your phpscript wouldn't find it.
you can try this way:
javascript:
<script>
var formdata = $(this);
var link = formdata.attr('action');
var distance = $('#distance').val();
var zipcode = $('#zipcode').val();
$.ajax({
type: 'GET',
url: link,
data: {"distance": distance,"postalcode": zipcode},
async: false,
jsonpCallback: 'jsonp_callback',//name of function returned from php
contentType: "application/json",
dataType: 'jsonp',
success: function(r) {
console.log(r);
},
error: function(e) {
alert(e.message);
}
});
</script>
php:
<?php
$arr = array();
$distance = $_GET['distance'];//sample 123
$zip = $_GET['postalcode'];//sample 65455
if(isset($distance) && isset($zip)) {
$arr = array('d'=> $distance, 'z'=> $zip);
}
$json = 'jsonp_callback(';
$json .= json_encode($arr);
$json .= ');';
echo $json;
?>
response:
jsonp_callback({"d":123,"z":65455});

Laravel 4.2 AJAX post giving me 404 error

I'm still using Laravel 4.2 and I'm trying to post a form with AJAX, but it gives me error 404 for a post page. Here is my code:
routes.php:
Route::post('/', array(
'as' => 'postFora',
'uses' => 'HomeController#postFora'
));
HomeController.php:
public function postFora() {
$form = Input::all();
$f = New Fora;
$f->content = Input::get('contant');
$f->user_id = Input::get('user_id');
$f->save();
return Response::json(array('success' => true));
}
main.js:
$('.dodaj-foro').submit(function(e) {
var form = $(this);
$.ajax({
url : "http://localhost/belezka/",
type: "POST",
dataType: "JSON",
data: form.serialize(),
success: function (data) {
alert('ok');
}
});
e.preventDefault();
});
index:
<form class="dodaj-foro" action="/" method="post" accept-charset="utf-8">
<input type="hidden" name="user_id" value="{{$user[0]->id}}">
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
<input type="text" name="contant" placeholder="Fora tuki">
</form>
I think you have to enter the route in present in Route file instead of http://localhost/belezka/
Try to replace :
$.ajax({
url : "http://localhost/belezka/",
type: "POST",
dataType: "JSON",
.....
By :
$.ajax({
url : "postFora",
type: "POST",
dataType: "JSON",
.....
Hope this will help.
In case you did not change the defaults Laravel comes with, add public to the AJAX request URL. By default, the route '/' corresponds to http://localhost/belezka/public/ due to URL rewriting.

Resources