unable to upload images in the folder while using ajax - ajax

I am supposed to upload images using using Ctrl keys for which I am using Ajax, but the problem is that while uploading the image names in the database successfully I am not able to upload them in the folder under the name images
I have the following code which is able to upload my images using ajax on database but unable to upload images in the folder
<script>
function showChar(e){
if(e.ctrlKey && e.charCode == 98){
e.preventDefault();
var j = $('#fl').click();
if(j){saveImage();}
}
}
function saveImage(){
//var abc = $('#form1').serialize();
//alert(abc);return false;
var fl = $('#fl').val();
if(fl != ''){
alert('t');
$.ajax({
type: 'post',
url: 'sent.php',
data: 'fl='+fl,
success:function(msg){
}
});
//$.ajaxFileUpload();
}
}
</script>
</head>
<body onkeypress="showChar(event);">
<form enctype="multipart/form-data" method="post" id="form1">
<input type="file" name="fl" id="fl" value=""/>
<input type="button" name="submit" id="submit" value="Submit" onclick="saveImage();"/>
</form>
and the query as
$fl = $_REQUEST['fl'];
$name = $_FILES['fl']['name'];
$temp = $_FILES['fl']['tmp_name'];
move_uploaded_file($temp, 'images/'.$fl);
$query = "INSERT INTO tbl_browse (fld_name) VALUES ('$fl')";
$res = mysql_query($query);
if(mysql_num_rows($res)>0){ return 'U'; }

Try this method
https://stackoverflow.com/a/24839628/1640577
check question and answer
$.ajax({
type: 'post',
url: 'sent.php',
data: 'fl='+fl,
processData: false,
contentType: false ,
success:function(msg){
}
});

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.

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

ajax not append data on div?

I dont know what the problem is here, I try to append the content, but its not.
var InPro = false;
$(document).ready(function(){
var form = $('#form32');
var submit = $('#submit');
form.on('submit', function(e) {
if(InPro) return;
InPro = true;
// prevent default action
e.preventDefault();
// send ajax request
$.ajax({
url: 'post.php',
type: 'POST',
cache: false,
data: form.serialize(),
success: function(data){
InPro = false;
var item = $(data).hide().fadeIn(800);
$('#post-show').append(data);
$("#form32")[0].reset();
},
});
});
});
and here the post.php:
<?php
include_once("config.php");
include_once("verifica.php");
// No direct access to this file
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if(!IS_AJAX) {die('Restricted access');}
session_start();
$user = $_SESSION['user'];
$comment = $_POST['comment'];
if($comment==""){
die();
}
$ip = getenv("REMOTE_ADDR");
$data = date ("ymdHis");
$i=mysql_query("INSERT INTO posts (id, foto, user, titulo, youtube, button, data, ip) VALUES ('','0','$user','$comment','$youtube','$button','$data','$ip')");
$idpostfeed = mysql_insert_id();
echo"$comment";
?>
and my form:
<form id="form32" method="post"> <textarea name="comment" id="comment" class="comment" placeholder=""></textarea> <input type="submit" id="submit" class="button" value="Submit Comment"> </form> <div id=post-show></div>
so, I want to show result in #post-show div, but it is not working. what is wrong?
thank you!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

How to insert into database after processing data through ajax formdata

My goal is to upload a file and insert data into a database table with ajax using formdata. I can do both separately. Or at least, I can use formdata to upload a file and I can use ajax to insert data into a database, but putting it together has proven difficult. The tutorial for this code seemed to indicate it would do it, and based on what I understand, the ajax is processing the entire form, but it's only uploading the file. I'm not having any issue with that and unfortunately, that's what most of the questions and tutorials I'm finding seem to be directed towards.
I think the issue is with my php insert code. Should I be inserting differently because of how the data is passed through ajax? Or am I more lost than that and just think I'm passing it all through ajax? I feel like I'm so close now, but I can't figure out what I'm doing wrong.
Thank you for any help.
The form and ajax:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<form name="multiform" id="multiform" action="upload.php" method="POST" enctype="multipart/form-data">
Name: <input type="text" name="dname" /> <br/>
Age :<input type="text" name="age" /> <br/>
Image :<input type="file" name="photo" /><br/>
<input type="submit" value="Ajax File Upload" />
</form>
<script>
//Callback handler for form submit event
jQuery(document).ready(function() {
$("#multiform").submit(function(e)
{
var formObj = $(this);
var formURL = formObj.attr("action");
var formData = new FormData($(this)[0]);
$.ajax({
url: formURL,
type: 'POST',
data: formData,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(data, textStatus, jqXHR)
{ alert(data)
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
e.preventDefault(); //Prevent Default action.
});
$("#multiform").submit(); //Submit the form
});
</script>
The php:
<?php
$username="...";
$password="...";
$database="...";
$target = "...";
$target = $target . time() . '_' . basename( $_FILES['photo']['name']);
$File = time() . '_' . basename($_FILES['photo']['name']);
$name = $_POST['dname'];
$age = $_POST['age'];
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Death");
print_r($_POST);
print_r($_FILES);
mysql_query("INSERT INTO wp_demo('name','age','File')VALUES('$name','$age','$File')");
if(isset($_FILES["photo"]))
{
//Filter the file types , if you want.
if ($_FILES["photo"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
//move the uploaded file to uploads folder;
move_uploaded_file($_FILES["photo"]["tmp_name"],$target);
echo $_FILES['photo']['name'] . " is now available";
}
}
?>
EDIT: Nevermind. I still don't know what's wrong here, but it ultimately just needs to work in wordpress. I got it to work there with this:
global $wpdb;
if($wpdb->insert('wp_demo',array(
'name' => $name,
'age' => $age,
'File' => $File
))===FALSE) {
echo "error";
}
else {
echo "success";
}
Now I just need to figure out why it submits on page load...

Resources