This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 8 years ago.
i created a form. Thats shown below...
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#sbt").click(function(){
var re=$("#file").val();
$.ajax({
type: "POST",
url: "loadajax.php",
data: $("#data").serialize()+ '&photo=' +re,
success: function(data) {
$("#datas").html(data);
},
error: function(){
alert('error handing here');
}
});
});
});
</script>
Ajax response page
<?php
echo "<pre>";
print_r($_POST);
var_dump($_FILES);
?>
All input values are returned.but file is not uploaded.I don't know how to upload file using ajax. Please help me...
Try This
$("#sbt").click(function(){
var pht = $("#ph").val();
var str2 = "your_folder/"; // destination folder, if needed
var upvid = str2.concat(pht);
var data = new FormData();
data.append( 'photo', $('#photo')[0].files[0] );
data.append( 'pht', pht );
$.ajax({
type: "POST",
url: "loadajax.php",
processData: false,
contentType: false,
cache:true,
data: data,
success: function(data){
$("#datas").html(data
} ,
error: function(){
alert('error handing here');
}
});
});
<?php
$a = $_POST['pht'];
$file = str_replace( "\\", '/', $a );
$ofile = basename($file);
?>
You have to use a plugin for this, jQuery doesn't support this out of the box. The best know plugin is ajaxForm
This will post the form to the given url in the form action field using ajax. There are events available to add validations and post-submit funcions.
you can also do like this:
function upload() {
// id of the form "documentUploadForm"
var form = document.getElementById("documentUploadForm");
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
var url = '<c:url value="/loadajax.php"/>';
xhr.open('POST', url, true);
xhr.onload = function(e) {
if (xhr.status === 200) {
outputData = JSON.parse(xhr.responseText);
console.log("Response:" +outputData);
}
};
xhr.send(formData);
}
Related
trying to upload a file without using a form and using $.post to transfer the file
I suppose the problem is on php side, but I'm not sure
<input type='file' id='inpfile'>
$(inpfile).on('change', function(){
var fd = new FormData();
var file = $(inpfile)[0].files[0];
fd.append('file', file);
fd = JSON.stringify(fd);
$.post('pro.php', {fn: 'upload', args: [fd]}, function(data){
console.log(data);
});
});
pro.php
if(isset($_POST['fn'], $_POST['args'])){
$fn = $_POST['fn']; $args = $_POST['args'];
$fn(...$args);
}
function upload($fd){
$fd = json_decode($fd);
$fname = $fd->file;
$destination = 'upload/' . $fname;
move_uploaded_file($fname, $destination);
}
you cannot upload file simply with $.post method and form data when changed to string cannot send file. you need to add contentType:false and processData:false, and remove this code fd = JSON.stringify(fd); Moreover, your jquery does not recognize the change since you have not addressed it properly. it should be $('#inpfile').on('change', function()
instead of just $(inpfile).on('change', function()
you can try this code.
<input type='file' id='inpfile'>
$('#inpfile').on('change', function(){
var fd = new FormData();
var files = $('#inpfile')[0].files;
fd.append('file',files[0]);
$.ajax({
url: 'pro.php',
method: 'post',
data: fd,
contentType: false,
processData: false,
success: function(response){
//your code.....
}
});
});
and in the PHP server side you check it with files method instead of post method. that is
if(isset($_FILES['file']['fd'])){
your code.......
}
This question already has answers here:
Load a file automatically without using a click button
(4 answers)
Closed 4 years ago.
Code:
<script type='text/javascript'>
$(document).ready(function(){
// Upload
$("#but_upload").click(function(){
var fd = new FormData();
var files = $('#file')[0].files[0];
fd.append('file',files);
fd.append('request',1);
// AJAX request
$.ajax({
url: 'addremove.php',
type: 'post',
data: fd,
contentType: false,
processData: false,
success: function(response){
if(response != 0){
var count = $('.uploaded-images .image-content').length;
count = Number(count) + 1;
// Show image preview with Delete button
$('.uploaded-images').append("<div class='image-content' id='content_"+count+"' ><img class='image-responsive' src='"+response+"' width='125' height='125'><span class='delete' id='delete_"+count+"'>×</span><span class='under-approval'>Under Approval</span></div>");
}else{
alert('file not uploaded');
}
}
});
});
// Remove file
$('.uploaded-images').on('click','.image-content .delete',function(){
var id = this.id;
var split_id = id.split('_');
var num = split_id[1];
// Get image source
var imgElement_src = $( '#content_'+num+' img' ).attr("src");
// AJAX request
$.ajax({
url: 'addremove.php',
type: 'post',
data: {path: imgElement_src,request: 2},
success: function(response){
// Remove <div >
if(response == 1){
$('#content_'+num).remove();
}
}
});
});
});
</script>
This is my Questions:
How do I automatically submit an upload form when a file is selected?
how to replace upload button my code is below
Anyone who have experience in this field, please suggestion me any solution for this problem, thank you.
You can use the following JQuery code:
$("#fileInput").change(function () {
$('#form').submit();
});
You can use this:
$('#file').on('change', function() {
$("#but_upload").click();
});
or better just put your click code into change event.
$('#file').on('change', function() {
var fd = new FormData();
var files = this.files[0];
...
});
This question already has answers here:
event.preventDefault() vs. return false
(14 answers)
Closed 6 years ago.
after submitting a form to email i get 2 email instead 1 how can i fix it? I need that only 1 letter come to email
js:
app.controller('threeCtrl',function($scope){
$("#subBusinessOne").click(function() {
var url = "businessFormOne.php";
$.ajax({
type: "POST",
url: url,
data: $("form#businessFormOne").serialize(),
success: function(data)
{
var name = $("input[name=name]").val("");
var rel= $("input[name=phone]").val("");
}
});
return false; // avoid to execute the actual submit of the form.
});
});
php:
<?php
$ToEmail = 'myemail.com';
$EmailSubject = 'Охрана бизнес-обьектов';
$mailheader = "From: ".$_POST["email"]."\r\n";
$MESSAGE_BODY = "Имя: ".$_POST["name"]."";
$MESSAGE_BODY .= "Телефон: ".$_POST["phone"]."";
mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure");
?>
I guess that #subBusinessOne is a form submit button. You're sending an AJAX request and then submitting the form again as a normal HTTP request.
Instead of detecting button click event, you should check if the form has been submitted, then prevent default action and send the AJAX request. Your JS code would then look like this:
app.controller('threeCtrl',function($scope){
$("#businessFormOne").submit(function(e) {
e.preventDefault(); // this is to avoid the actual submit
var url = "businessFormOne.php";
$.ajax({
type: "POST",
url: url,
data: $("form#businessFormOne").serialize(),
success: function(data)
{
var name = $("input[name=name]").val("");
var rel= $("input[name=phone]").val("");
}
});
});
});
app.controller('threeCtrl',function($scope){
$("#subBusinessOne").submit(function(e) {
e.preventDefault();
var url = "businessFormOne.php";
$.ajax({
type: "POST",
url: url,
data: $("form#businessFormOne").serialize(),
success: function(data)
{
var name = $("input[name=name]").val("");
var rel= $("input[name=phone]").val("");
}
});
});
});
Use .preventDefault()
app.controller('threeCtrl',function($scope){
$("#subBusinessOne").click(function(e) {
e.preventDefault();
var url = "businessFormOne.php";
$.ajax({
type: "POST",
url: url,
data: $("form#businessFormOne").serialize(),
success: function(data)
{
var name = $("input[name=name]").val("");
var rel= $("input[name=phone]").val("");
}
});
return false; // avoid to execute the actual submit of the form.
});
});
I guess you are trying to make cross AJAX request, and it's reason why you got 2 email instead 1. Because first request with method OPTIONS (to check available to send requests from other domains) and second request with method POST
i already had a form which uses ajax to save the the data to the database. so i have this sample
Html code
<input id="product_name" type="text" >
<input id="product_description"/>
<input id="product_img" type="file" accept="image/*"/>
<button id="btnSave">Save</button>
Javascrip Code
$("#btnSave").click(function(){
p_name = $("#product_name").val();
p_des = $("#product_description").val();
p_image = $("#product_img").prop('files')[0];
data = {
'product_name':p_name,
'product_description':p_des
}
$.post('url_here',data,function(response){
console.log(response);
});
});
i do have this info Jquery input.files equivalent but i cant make it passed as a $_FILE for php.Please give me some example codes combining the input type text and file without using the form tag and using jquery ajax.
You can use FormData:
document.getElementById('btnSave').addEventListener('click', function() {
var fd = new FormData();
fd.append('product_name', document.getElementById('product_name').value);
fd.append('product_description', document.getElementById('product_description').value);
fd.append('product_name', document.getElementById('product_img').files[0]);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'url_here');
xhr.addEventListener('load', function(e) {
console.log(xhr.responseText);
});
xhr.send(fd);
});
UPDATE
Since you want to use jQuery AJAX (I have no idea why, since it was not prepared to use XHR2), you can workaround by telling it to not process the data parameter, e.g:
$('#btnSave').click(function() {
p_name = $('#product_name').val();
p_des = $('#product_description').val();
p_image = $('#product_img').prop('files')[0];
var data = new FormData();
data.append('product_name', p_name);
data.append('product_description', p_des);
data.appned('product_img', p_image);
$.ajax({
url: 'url_here',
data: data,
processData: false,
contentType: false,
type: 'POST',
success: function(response){
console.log(response);
}
});
});
this is the js code, ajax has two arguments, the first is url, 2nd is a object which contains type data and onsuccess. (I didn't use jQuery but the function I define myself, the code is at the end of the question)
I just want to send the 'text' string to php, so is there any problem to do like this? I also have tried change the data to data: {searchinput:"text"}, but still don't work.
ajax(
'http://localhost/test.php',
{
type: 'POST',
data: "searchinput=text",
onsuccess: function (responseText, xhr) {
console.log(responseText);
}
}
);
this is the php code, sorry for changing the code wrong while pasting it on.
$searchinput = $_POST["searchinput"];
# $db = new mysqli('localhost', 'root', '', 'text');
if (mysqli_connect_errno()) {
echo "error:can not connect database";
}
$query = "select * from text where data like'".$searchinput."%' ";
$result = $db->query($query);
then the error is
Undefined index: searchinput
I have search some method like change onsuccess function to setTimeout, and do ajax again, but it doesn't work, just send the data again but the php still can't get the data
this is the ajax function
function ajax(url, options) {
if (!options.type) {
options.type = "post"
};
var xhr = new XMLHttpRequest();
xhr.open(options.type, url, true);
xhr.send(options.data);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
options.onsuccess(xhr.responseText, xhr)
} else {
options.onfail(xhr.responseText, xhr);
}
};
}
}
Well, since you used the ajax wrong, I'm not surprised. There should be a error in the console.
jQuery AJAX is used like this:
$.ajax({
url: "http://localhost/test.php",
type: 'POST',
data: {searchinput: text},
success: function (responseText, xhr) {
console.log(responseText);
}
}
);
url is a part of the object the ajax expects, so it needs to be inside and not outside of it. Also, data is expecting another object, you gave it a plain string.
Also, as #Muhammad Ahmed stated in his answer, you are using a wrong variable in your php code.
Edit: AJAX in JavaScript without jQuery:
var request = new XMLHttpRequest();
request.open('POST', 'http://localhost/test.php', true);
request.onreadystatechange = function() {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
// worked
var data = JSON.parse(this.responseText);
} else {
// failed
}
}
};
request.send();
request = null;
$searchcon = $_POST["searchinput"];
# $db = new mysqli('localhost', 'root', '', 'text');
if (mysqli_connect_errno()) {
echo "error:can not connect database";
}
$query = "select * from text where data like'".$searchinput."%' ";
$result = $db->query($query);
In This code there is a mistake on ist line you are using variable $searchcon
and on query you are using $searchinput change ist varaible name to $searchinput instead of $searchcon. and also change your ajax code.
$.ajax({
url: "http://localhost/test.php",
type: 'POST',
data: {searchinput: text},
success: function (responseTxt, xhr) {
console.log(responseTxt);
}
}
);
send data value like below and use print_r($_POST) on php page to see values are coming or not
$.ajax(
{ url: 'test.php',
type: 'POST',
data:{
searchinput:text
},
onsuccess: function (responseText, xhr) {
console.log(responseText);
}
}
);
Try with this code you were using ajax in wrong manner. You can learn more about how ajax works and how to code for ajax over http://api.jquery.com/jquery.ajax/
$.ajax(
{
type: 'POST',
url : 'http://localhost/test.php',
data: {searchinput:text},
success: function (responseText, xhr) {
console.log(responseText);
}
}
);
and within your PHP file you need to update your typo i.e. you were getting value of your POST in $searchcon variable
$searchcon = $_POST["searchinput"];
^^^^^^^^^^
and within your query you were using
$query = "select * from text where data like'".$searchinput."%' ";
^^^^^^^^^^^^^^
it should be like
$query = "select * from text where data like'".$searchcon."%' ";
^^^^^^^^^^
Try this code :
var other_data = $('form').serializeArray();
$.ajax({
url: 'work.php',
data: other_data,
type: 'POST',
success: function(data){
console.log(data);
}
});
or
you can also pass the data in url also.
Try the code which suits your requirement.
$.ajax({
url: 'work.php?index=checkbox&action=empty',
type: 'POST',
success: function(data){
console.log(data);
}
});