I'm having a problem of uploading a image with names in my database my code is working fine but it is only for image I can't add the name and other data in it
var formdata = new FormData(this);
formdata.append("movieprice", movieprice);
formdata.append("movietitle", movietitle);
formdata.append("moviecategory", moviecategory);
formdata.append("upload", upload);
formdata.append("image", image);
var upload ="upload";
$.ajax({
url:"uploadmovie.php",
method:"POST",
data:formdata,
contentType:false,
processData:false,
success:function(data){
if (data === "YES"){
alert(data)
swal("Successfully Uploaded", "", "success")
.then((value) => {
window.location.reload();
});
}else{
alert(data)
swal("Error", "", "warning")
}
}
});
}
Also this for the variables:
var movieprice = $('#movieprice').val();
var movietitle = $('#movietitle').val();
var moviecategory = $('#moviecategory').val();
How can I pass this value to ajax ?
here is the html for those looking for i didnt add the validation on javascript for the empty fields
<form method="POST" enctype="multipart/form-data" >
<div class="w3-col m12 02">
<div class="w3-rest w3-container w3-blue" style="width:100%;">
<label id="label"><i class="fa fa-tag" style="font-size:24px;"> Movie Category</i></label>
</div>
<select id="moviecategory" name="moviecategory">
<option>Romance</option>
<option>Comedy</option>
<option>Action</option>
<option>Drama</option>
<option>Horror</option>
<option>Sci-Fi</option>
</select>
</div>
<div class="w3-col m12 02">
<div class="w3-rest w3-container w3-blue" style="width:100%;">
<label id="label"><i class="fa fa-address-card" style="font-size:24px;"> Movie Title</i></label>
</div>
<input type="text" name="movietitle" id="movietitle">
</div>
<div class="w3-col m12 02">
<div class="w3-rest w3-container w3-blue" style="width:100%;">
<label id="label"><i class="fa fa-money" style="font-size:24px;"> Movie Price</i></label>
</div>
<input type="number" name="movieprice" id="movieprice">
</div>
<div class="w3-col m12 02">
<div class="w3-rest w3-container w3-blue" style="width:100%;">
<label id="label"><i class="fa fa-file" style="font-size:24px;">Movie Image</i></label>
</div>
<input type="file" name="image" id="image" /><br />
</div>
<footer class="w3-container">
<button class="w3-right btn btn-danger" id="close" style="float: right; width:90px; margin-left:10px;">close</button>
<button type="submit" class="btn btn-primary" name="upload" id="upload" value="Upload Image" style="float: right; width:90px;">Add</button>
</footer>
</form>
and for the uploadmovie.php i got the error that image is undefined
using this $image = $_FILES["image"]["tmp_name"];
if (move_uploaded_file($_FILES["image"]["tmp_name"], $target)) {
$target = "images/".basename($_FILES["image"]["tmp_name"]);
You could add custom data into the FormData instance using the method append() :
var movieprice = $('#movieprice').val();
var movietitle = $('#movietitle').val();
var moviecategory = $('#moviecategory').val();
// create FormData object
var formdata = new FormData(this);
// add custom data :
formdata.append("movieprice", movieprice);
formdata.append("movietitle", movietitle);
formdata.append("moviecategory", moviecategory);
// send data
$.ajax({
url:"uploadmovie.php",
method:"POST",
data:formdata,
contentType:false,
processData:false,
success:function(data){
// ...
}
});
The server-side will receive the data "movieprice","movietitle" and "moviecategory" in your $_POST array.
Related
I have a case as follow:
Step 1: Open pop-up, upload file -> Success.
Step 2: Edit file just uploaded.
Step 3: without reload website, reopen pop-up.
Step 4: select file just edited to upload.
Expected result: Upload success.
Actual result : upload error: Data format of the uploaded file is not EXCEL file.
How i can fix it??
This is my code
Code js
function handlerUploadFile() {
var form = $(‘'#uploadFile_action')[#];
var data = new FormData(form);
loading_ajax();
$.ajax({
type: "POST",
enctype: 'multipart / form - data ',
url: '../sac0#12/uploadFile.action',
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 620000,
success: function(data, status, xhr) {
close_loading_ajax(
};
var messageld = "";
var ct = xhr.getResponseHeader('content - type ') || °";
if (ct.indexOf('html') > -1) {
showNotifyDialog("fileNotFormatExcel");
return; +
if (ct.indexOf('json') > -1) {
var obj = JSON.parse(data);
if (obj.result == "SUCCESS”) {
showNotifyDialog("fileUploadSuccess") $("#myModalUpload”).css("
display”, “none ")};
$('#itemDetails')
}.empty(); loadContent(limit, offset, transactionId, scrollTop);
}
else {
if (obj.code == "EA-0003") {
messageId = "EA-0003";
contentConfirm = mesSystem[messageId];
alert(contentConfirm);
} else if (obj.code == "ERROR_PLT_ID_LENGTH") {
messageId = "ERROR_PLT_ID_LENGTH";
contentConfirm = mesSystem[messageId];
alert(contentConfirm);
} else {
alert("Data format of the uploaded file is not correct.");
}
}
}
},
error: function(e) {
close_loading_ajax();
alert("Data format of the uploaded file is not EXCEL file.");
}
});
}
code jsp
<form id="uploadFile_action" name="uploadFile_action" method="post" enctype="multipart/form-data">
<div class="row" style="margin: 5px 0 0; border-bottom: 1px solid gray; height: 40px;">
<div class="col-md-12">
<div class="col-md-2 col-sm-2 col-xs-2 file" style="margin-top: 5px; width: auto;">
<b style="font-weight: 900;">Upload File:</b>
</div>
<div class="col-md-9 col-xs-9 col-sm-9 file-return" contentEditable=false data-text="File path"></div>
<div class="col-md-1 col-xs-1 col-sm-1 input-file-container">
<input type="hidden" name="confirm" value="false" id="uploadFile_action_confirm" />
<input type="file" name="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" class="input-file" value="" id="uploadFile_action_file" />
<button tabindex="0" for="my-file" class="input-file-trigger" value="Browse"><b style="font-weight: 800;">Browse</b></button>
</div>
</div>
<div class="col-md-12">
<p id="emptyFileUpload" style="display: none;"></p>
</div>
</div>
<div class="row">
<input type="submit" name="upload" class="btn btn-primary btn-danger textWhite" id="uploadFile_action_0" style="height: 34px" value="Upload" />
<input type="button" value="Back" class="cancelButton">
</div>
<s:hidden name="transactionId"></s:hidden>
</form>
I'm trying to save a data using ajax
this is my global function for api's, I'm using this global function even in show of data to table.
ajax = (action, data, method, callback) => {
return $.ajax({
type: method,
// url: `https://dev2.bliimo.net/${action}`,
url: `http://localhost:8080/${action}`,
contentType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", `Bearer ${gon.global.currentUser.access_token}`);
},
data: { data: data },
async: !1,
cache: false,
error: e => {
console.log(e.responseText);
console.log("Error occured");
}
});
};
when i click the "add new catalog" button, the modal appears,
inside the modal there is a form
Now, this is the form:
<form id="add-new-catalog-form" class="uk-form-stacked" method="post">
<div class="uk-grid uk-margin-remove uk-padding-remove uk-width-1-1">
<div class="uk-width-1-3 uk-padding-remove">
<div>
<div class="uk-margin">
<label class="uk-form-label uk-text-bold" for="add-catalog-name">Catalog Name</label>
<div class="uk-form-controls">
<input class="uk-input uk-form-width-medium category-input" id="add-catalog-name" type="text" autocapitalize="words" placeholder="Catalog Name" />
</div>
</div>
<div class="uk-margin">
<label class="uk-form-label uk-text-bold" for="iconimg-output">Icon Image</label>
<%= image_tag('', id: 'iconimg-output')%>
<div class="js-upload" uk-form-custom>
<button class="uk-button uk-button-default upload-cloudinary-icon" type="button" tabindex="-1">UPLOAD</button>
</div>
</div>
</div>
</div>
<div class="uk-width-2-3 uk-margin-remove uk-padding-remove">
<div class="uk-grid uk-width-1-1 uk-margin-remove uk-padding-remove">
<div class="uk-width-1-2 uk-margin-remove uk-padding-remove">
<label class="uk-form-label uk-text-bold" for="landingpageimg-output">Landing Page Image</label>
<%= image_tag('', id: 'landingpageimg-output')%>
<div class="js-upload" uk-form-custom>
<button class="uk-button uk-button-default upload-cloudinary-landing" type="button" tabindex="-1">UPLOAD</button>
</div>
</div>
<div class="uk-width-1-2 uk-margin-remove uk-padding-remove">
<label class="uk-form-label uk-text-bold" for="categorypageimg-output">Catalog Cover Image</label>
<%= image_tag('', id: 'categorypageimg-output')%>
<div class="js-upload" uk-form-custom>
<button class="uk-button uk-button-default upload-cloudinary-category" type="button" tabindex="-1">UPLOAD</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="uk-modal-footer uk-text-right">
<button class="uk-button uk-button-default uk-modal-close" type="button">Cancel</button>
<button class="uk-button uk-button-primary" type='submit'>Save</button>
</div>
</form>
when I click the save button in the modal, it will run this function
This is my submit function:
$('#add-new-catalog-form').on('submit', e => {
let catalog_name = $('#add-catalog-name').val();
let catalog_icon = $("#iconimg-output").attr('src');
let catalog_landing_image = $('#landingpageimg-output').attr('src');
let catalog_cover_image = $('#categorypageimg-output').attr('src');
let data = `name=${catalog_name}&thumbnail=${catalog_icon}&landingPageImage=${catalog_landing_image}&coverImage=${catalog_cover_image}`;
ajax("api/catalogs", `${data}`, "POST");
});
it says "Invalid mime type \"json\": does not contain '/'","code":500"
how to solve this?
dataType and contentType are not the same:
dataType: "json",
contentType: "application/json; charset=utf-8",
...
Done!
$('#add-new-catalog-form').on('submit', e => {
e.preventDefault();
let catalog_name = $('#add-catalog-name').val();
let catalog_icon = $("#iconimg-output").attr('src');
let catalog_landing_image = $('#landingpageimg-output').attr('src');
let catalog_cover_image = $('#categorypageimg-output').attr('src');
let data = { "name": catalog_name, "thumbnail": catalog_icon, "landingPageImage": catalog_landing_image, "coverImage": catalog_cover_image };
ajax("api/catalogs", JSON.stringify(data), "POST");
window.location.replace("/catalog");
});
I'm struggling with formData in Ajax calls. I read everything I could with the same information, tried get the form with this, getElementById and nothing works (even tried several solutions from SO).
I have a form with id add-lang-form:
<form class="js-validation-addlang" method="post" enctype="multipart/form-data" id="add-lang-form" name="add-lang-form">
<div class="form-group row">
<label class="col-6 col-form-label">Language Name</label>
<label class="col-6 col-form-label">Language Code</label>
<div class="col-md-6">
<div class="input-group">
<input type="text" class="form-control" id="lang_name" name="lang_name">
<span class="input-group-addon"><i class="fa fa-file"></i></span>
</div>
</div>
<div class="col-md-6">
<div class="input-group">
<input type="text" class="form-control" id="lang_code" name="lang_code">
<span class="input-group-addon"><img src="/assets/img/flags/def.png" id="flag-icon"/></i></span>
</div>
</div>
</div>
<div class="form-group row">
<label class="col-12" for="lang_tags">Language Tags</label>
<div class="col-lg-12">
<div class="input-group">
<input type="text" class="form-control" id="lang_tags" name="lang_tags">
<span class="input-group-addon"><i class="fa fa-list"></i></span>
</div>
</div>
</div>
<div class="form-group row">
<label class="col-md-12">Image</label>
<div class="col-md-12">
<input type="file" id="lang_img" name="lang_img" class="dropify" />
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<button type="submit" class="btn btn-alt-primary pull-right">Submit</button>
</div>
</div>
</form>
And I have a function that is called after form validation with submitHandler:
function AddLang(e) {
e.preventDefault ? e.preventDefault() : e.returnValue = false;
var form = document.getElementById('add-lang-form');
var formData = new FormData(form);
$.ajax({
url: 'PHP_FILE',
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
data: {
dados: formdata,
caller: 'addlang',
},
type: 'POST',
beforeSend: function() {
$("#login_btn").html('<i class="fa fa-2x fa-cog fa-spin"></i>');
$("#login_btn").attr("disabled", true);
},
success: function(output) {
if (output == "OK") {
alert("OK");
} else {
alert(output);
}
}
});
};
I tried creating the formData directly, everything and nothing works.
The $_POST['dados'] is not set. Any clue of whats going on?
you can't use a FormData object as the value of a parameter, it has to be the entire data: value. If you want to add additional parameters, use FormData.append().
function AddLang(e) {
//var data = $("#add-lang-form").serialize();
e.preventDefault ? e.preventDefault() : e.returnValue = false;
var form = document.getElementById('add-lang-form');
var formData = new FormData(form);
formData.append('caller', 'addlang');
$.ajax({
url: 'PHP_FILE',
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
data: formData,
type: 'POST',
beforeSend: function() {
$("#login_btn").html('<i class="fa fa-2x fa-cog fa-spin"></i>');
$("#login_btn").attr("disabled", true);
},
success: function(output) {
if (output == "OK") {
alert("OK");
} else {
alert(output);
}
}
});
};
Basically I am using html form for uploading image on server. Below is my code for form:
<div class="modal modal-fixed-footer" id="modal-image">
<div class="modal-content">
<h3>Upload Image</h3>
<form id="uploadimg" enctype="multipart/form-data">
<input type="hidden" name="entity" value="order">
<input type="hidden" name="orderId" value="<?php echo $orderId; ?>">
<input type="hidden" name="status" value="<?php echo $json->response->body->order->status; ?>" />
<input type="hidden" name="url" value="order-details.php?order=<?php echo $orderId; ?>&e=0">
<div class="form-inputs p-l-r-0">
<div class="row">
<div class="col s12">
<div class="file-field input-field" style="display:none">
<div class="btn accent-color">
<span>File</span>
<input type="file" id="fileToUpload" name="fileToUpload[]" multiple="multiple">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text" placeholder="Upload one or more images">
</div>
</div>
</div>
</div>
<div id="dvPreview" class="row"></div>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn-flat modal-action modal-close" id="uploadimg-submit">Submit</button>
<button class="btn-flat modal-action modal-close">Close</button>
</div>
Now when the #uploadimg-submit is clicked below jquery code is executed:
$('#uploadimg-submit').on('click', function(e) {
e.preventDefault();
$("form#uploadimg").submit();
});
and form submit function:
$("form#uploadimg").submit(function(e2) {
var smoothState = $('#main').smoothState().data('smoothState');
e2.preventDefault();
var formData = new FormData($(this)[0]);
// console.log(formData);
$.ajax({
url: 'processors/process-upload.php',
type: 'POST',
data: formData,
processData: false,
contentType: false,
beforeSend: function() {
ajaxindicatorstart();
},
success: function(rsp) {
if (rsp == '200') {
Materialize.toast('Image Uploaded Successfully', 2000, 'green');
smoothState.clear('/order-details.php');
smoothState.load('/order-details.php?order=' + $('#order_id').val());
} else {
Materialize.toast('Image Uploaded Failed', 2000, 'red');
smoothState.clear('/order-details.php');
smoothState.load('/order-details.php?order=' + $('#order_id').val());
}
},
error: function() {
Materialize.toast('Image Uploaded Failed', 2000, 'red');
smoothState.clear('/order-details.php');
smoothState.load('/order-details.php?order=' + $('#order_id').val());
}
});
return false;
});
The file process-upload.php takes less than a second to process the image which i debugged using microtime(true). But total time take by sending request and recieving response is nearly 11 secs, majority of which (about 9 secs) is taken in sending request. Below are timeline analytics from chrome dev tools.
I want to reduce this time else it will be unfeasible to wait so long for uploading image. Is there any way I can optimize it further?
My brain is exploding - can't figure out what the issue is with Safari. All browsers work just fine, but Safari simply doesn't read my JavaScript. Not even a simple ol' 'alert()'. Any clues?
============HTML===============
</div>
<div class="container top">
<h1 class="text">Weather Dashboard</h1>
<h3 class="text">Enter the city to get a 3-day forecast</h3>
<form id="cityForm" class="form-group">
<div class="container-fixed">
<div class="form-horizontal">
<div class="input-group inpWid">
<div class="input-group-addon">
<span class="glyphicon glyphicon-home"></span>
</div>
<input type="text" class="form-control" id="city"
name="city" placeholder="Enter the City">
</div>
<button type="submit" class="btn btn-primary btn-success">Weather Me!</button>
</div>
</div>
</form>
<div class="container-fixed" id="weatherBox">
</div>
</div>
============JQuery/JavaScript===============
$("#cityForm").submit(function(e) {
e.preventDefault();
alert("safari");
var url = "scraper.php"; // the script where you handle the form input.
var city1 = $("#city").val();
var city = city1.replace(/\s+/g, '');
$.ajax({
type: "POST",
url: url,
cache:false,
data: {city, city1},
success: function(data){
$("#weatherBox").html(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
============PHP===============
$city = $_POST["city"];
$city1 = $_POST["city1"];
$url="http://www.weather-forecast.com/locations/$city/forecasts/latest";
$content = file_get_contents($url);
preg_match('/3 Day Weather Forecast Summary:<\/b>(.*?).<\/span>/s', $content, $day1);
preg_match('/7 Day Weather Forecast Summary:<\/b>(.*?).<\/span>/s', $content, $day2);
preg_match('/10 Day Weather Forecast Summary:<\/b>(.*?).<\/span>/s', $content, $day3);
for ($i=1; $i<=3; $i++) {
${d.$i} = '<img src="sun.gif" alt="sun" height="42" width="42">';
$wCon = ${day.$i}[1];
preg_match("/dry/i", $wCon, ${weather.$i});
if (${weather.$i}[0]!="dry"){
${d.$i} = '<img src="rain.png" alt="rain" height="42" width="42">';
};
unset(${weather.$i}[0]);
};
============Website===============
http://alexanderii.net/cover/
you have syntax error:-
change data: {city, city1}, to data:{'city':city,'city1':city1}
try this code:-
$.ajax({
type: "POST",
url: url,
cache:false,
data:{'city':city,'city1':city1},
success: function(data){
$("#weatherBox").html(data); // show response from the php script.
}
});