I want to know how can I send the image data to the server (Django app) using javascript ajax function.
Following is my code.
// Get filename of image
jsondata = JSON.parse(data);
image_file_name = jsondata.fileurl;
// document.getElementById('previewimage').src = image_file;
// I can show the image.
b64_image = btoa(unescape(encodeURIComponent(image_file)));
var credentials = {
filename: image_file_name,
image: b64_image,
};
// Send ajax request to the server
$.ajax({
url: HOST_NAME + "user/api/file_uploader/",
type: 'GET',
dataType: 'json',
data: credentials,
timeout: 10000,
})
.done(function (data) {
// Get the result
jsondata = JSON.parse(data);
alert("File upload completed...");
})
// If false...
.fail(function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Upload error");
})
You have to use FromData for posting files using ajax .
var form = $('form')[0];
var formData = new FormData(form);
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
// success code .
}
});
You just need to make one change in your code.
// Send ajax request to the server
$.ajax({
url: HOST_NAME + "user/api/file_uploader/",
type: 'POST', // changed from GET to POST
dataType: 'json',
data: credentials,
timeout: 10000,
})
.done(function (data) {
// Get the result
})
.fail(function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Upload error");
})
as GET is use to read and post is used to create.
you can read more about request methods.
Related
As the title says, I wanna check if this ajax method has been submitted or not and show the result in a condition.
Here is the Ajax POST code;
$.ajax({
url: "addorderInfo.php", // Url to which the request is sent
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false,
success: handleResult
});
And here is the condition I put but it is not working.
function handleResult(data){
if(data == 'error'){
window.location.href ='404.php';
}
else{
$( "#clearcart" ).click();
window.location.href = "ordercomplited.php";
}
}
try this
$.ajax({
url: "addorderInfo.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function (data) {
alert(data)
},
error: function (error) {
alert(error.responseText) // if your request doesn't work
}
});
There isn't sufficient code to know why is not working.
IMHO the ajax call is not handling the error. Try to edit your code as follow:
$.ajax({
url: "addorderInfo.php", // Url to which the request is sent
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false,
success: function(data) {
handleResult(data);
}
error: function(data) {
handleError(data);
}
});
I'm trying to insert data into MongoDB using Mongoose, i created a form and sending data using two ajax post to the node, but Mongoose insert two document for each ajax call, I want to send my data to data as a single document.
This my server:
app.post("/cp" , upload , function(req , res){
console.log('file uploaded succcessfully');
var title = JSON.stringify(req.body.titles);
var file = req.file;
const courses = new Courses({
// courseTitle:c_title,
// courseSubtitle:c_subtitle,
// courseAuthor : c_creator,
// coursePrice : c_price,
courseVideo :file ,
courseTitles :title ,
// courseSpecs : c_specs,
courseValidation : 0
});
courses.save();
});
Mongoose insert a document with title and without file and a document with file and without title,
Ajax:
if(e.submitter.id == "submitpostCp"){
var data = {};
data.titles = titlesLis;
data.specs = specsLis;
data.submit = "submitAll";
var fileup = new FormData($('#form')[0]);
$.when(
$.ajax({
type: 'post',
url: '/cp',
data: JSON.stringify(data),
contentType: 'application/json',
xhrFields: {
withCredentials: false
},
headers: {
},
success: function (data) {
console.log('Success');
console.log(data);
},
error: function () {
console.log('We are sorry but our servers are having an issue right now');
}
})
).then(function() {
$.ajax({
url:'/cp',
type: 'POST',
contentType: false,
processData: false,
cache: false,
data: fileup,
success: function(res){
// alert(res);
},
error: function(){
alert('Error: In sending the request!');
}
})
});
}
In this case you should use findOneAndUpdate method with options {upsert: true}: https://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate
First, here is my code :
routes.php
$router->resource('vips','formController');
formController.php (im only posting the concerned function)
public function store(CreateVipRequest $request, Vip $vip, Pool $pool, Url $url)
{
$new_vip = $vip->create($request->except(['srv_hostname', 'srv_ip', 'srv_port','url']));
$pool->fill($request->only(['srv_hostname', 'srv_ip', 'srv_port']));
$url->fill($request->only(['url']));
/* Some more inserts on the database...*/
return redirect()->route('vips.show', [DB::table('vips')->max('id')]);
}
My code submits the form, and after some json requests to a distant Api (and some databases insertions) it redirects to the show view.
Now I want to add a second button that submits the form via Ajax.
Question : Is there a way to use the same function store ? I need it to be able to process both an ajax submit and a normal submit.
Submit form using ajax
$("#form-name").submit(function(ev){
ev.preventDefault();
var formURL = $(this).attr("action");
var postData = $(this).serializeArray();
$.ajax({
url: formURL,
type: 'POST',
data: postData,
success: function(data, textStatus, jqXHR){
location.reload();
},
error: function(jqXHR, textStatus, errorThrown){
var errResponse = JSON.parse(jqXHR.responseText);
},
});
});
Yes, you can.
In your javascript you can do something like this (assuming you're using jquery):
// if you're using a form
var data = $('form').serialize();
// if data comes from elsewhere
var data = {foo: 'bar', ...};
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
success: function (data) {
// Do something if everything went fine
},
error: function (jqXHR, textStatus, errorThrown) {
// Do something if something went wrong
},
});
Your controller will catch the data coming from the request as you are already doing.
I'm trying to do GET that retrieves data from a URL and then a POST to a RESTful api. The get call seems to work okay but the server sees nothing in the file parameter. I have verified that the GET call is return pdf stream data and that it is placing it in the FormData arg.
Here is the complete call
function upload(key, url){
var file;
/* get data from url */
$.ajax({
url: url,
type: 'GET',
async: false,
cache: false,
dataType : 'text',
contentType : 'application/pdf',
success: function( data ) {
file = data;
},
error: function(xhr, status, error) {
console.log("error logging: "+ error);
}
});
/* send data to api */
var data = new FormData();
data.append("key", key);
data.append("file", file); //<-- this has pdf stream data
$.ajax({
url: ROOT_URL + "/api/account/upload",
type: 'POST',
cache: false,
async: false,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
data: data,
success: function( data ) {
console.log("Uploaded!");
},
error: function(xhr, status, error) {
console.log("error logging: "+ error);
},
dataType: "json"
});
};
Here is the server side (grails + spring + jaxrs)
#POST
#Path('upload')
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces('application/json')
String upload(#Context HttpServletRequest request){
GrailsWebRequest w = WebUtils.retrieveGrailsWebRequest()
MultipartFile multipartFile = w.getRequest().getFile('file');
println("request:" + request)
println("multipartFile:" + multipartFile)
println("parameterMap:" + w.getRequest().getParameterMap() )
return ['okay':'uploaded'] as JSON
}
Which currently prints out:
request:org.grails.jaxrs.web.RequestWrapper#448593df
multipartFile:null
parameterMap:[file:[], key:[c07fc0974ebb4f3a8fc21e3d002152d4]]
Looks like when the POST call is happening, the variable file doesn't have a value yet. Since you are wanting everything after GET call to occur after the server has returned data, you should move that code into a separate function that is called upon success.
I'm trying to send some FormData via a simple jquery ajax GET/Post but for some reason my formData is not getting set right. I end up with ?[object%20FormData] as my payload.
I'm a bit new to this FormData stuff, but I was able to use it successfully with file uploads no problem using this same technique... Here's what I'm doing with my specified values I want to send:
I should note: I'm not using any form element to grab these values from.
var data = new FormData();
data.append("date", curDate);
data.append("serviceID", sID);
data.append("attSummID", asID);
data.append("totalCount", 0);
data.append("visitorCount",0);
data.append("reset",false);
$.ajax({
url: '/4DACTION/WEB_ServiceCounts/',
processData: false,
contentType: false,
data: data,
dataType: 'json',
type: 'GET',
success: function(response){
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown){
alert('ERRORS: ' + textStatus);
}
});
Any tips?