I've got some problems regarding sending a form online or saving it locally. I have an Phonegap application which is just a simple form which get saved to a database, or if that fails, locally.
I have everything set up only this fucntion. Firstly I thought, I just do it with Boooleans, run the fucntion and if everything goed well return True. But that doesn't work because the code just gets executed before I have a value to compare, which means the value will be always false.
This is the code now:
if(uploadDataAndImage(formData))
{
//Its true, do my things
}
else
{
//Its false
}
This is the boolean fucntion:
function uploadDataAndImage(dataForm) {
var localURL = dataForm.cardurl;
console.log(localURL);
if(localURL == "")
{
$$.ajax({
type: "POST",
url: "upload.php",
crossDomain: true,
data: dataForm,
success:function(data)
{
console.log("Upload to server without card");
return true;
},
error: function()
{
console.log("Form couldn't upload to the server");
//alert("Couldnt upload to server, saving locally");
return false;
}
});
}
else{
//set upload options
var options = new FileUploadOptions();
options.chunkedMode = false;
console.log("Start upload picture");
var ft = new FileTransfer();
ft.upload(deLokaleURL, encodeURI("uploaderino.php"), win, fail, options);
function win(r) {
console.log("Code = " + r.responseCode);
console.log("R" + r.response);
console.log("Sent = " + r.bytesSent);
dataForm.cardurl = r.response;
var dataString = JSON.stringify(dataForm);
$$.ajax({
type: "POST",
url: "upload.php",
crossDomain: true,
data: dataForm,
success:function(data)
{
console.log("Upload to server with card");
return true;
},
error: function()
{
console.log("Form couldn't upload to the server, do nothing");
return false;
}
});
}
function fail(error) {
//alert("An error has occurred: Code = " + error.code);
console.log("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
showMessage("Image upload has failed, get a better internet connection and try again!" , function(){console.log("Upload van de form is mislukt!")});
return false;
}
}
}
But this obviously doesn't work. Now I've done some research and asked soem questions and I've found Promises. But I cannot seem to grasp how I can use this.
I thought something like this:
var deferred = $.Deferred();
deferred.resolve(uploadDataAndImage(formData));
deferred.done(function(value) {
//Upload went well so do my things
});
But that is not how it works, right/?
Use deferred inside the uploadDataAndImage to return a promise. You can then use then() and catch() to do something when the ajax call is finished.
function uploadDataAndImage() {
var deferred = $.Deferred();
$$.ajax({
type: "POST",
url: "upload.php",
crossDomain: true,
data: dataForm,
success:function(data) {
deferred.resolve();
}, error: function(e) {
deferred.reject(e);
}
});
return deferred.promise;
}
uploadDataAndImage(formData).then(function() {
//Its true, do my things
}).catch(function() {
//Its false
});
I'd just set it up to use a callBack function. Something like this maybe
uploadDataAndImage(formData, function(data){
console.log(data);
if(data){
//do something in here that needs doing as the ajax call was true
}
else
{
//Do something after the ajax returned an error...
}
})
function uploadDataAndImage(dataForm, callBack) {
var localURL = dataForm.cardurl;
console.log(localURL);
if(localURL == "")
{
$$.ajax({
type: "POST",
url: "upload.php",
crossDomain: true,
data: dataForm,
success:function(data)
{
console.log("Upload to server without card");
callBack(true);
},
error: function()
{
callBack(false);
}
});
}
else{
//set upload options
var options = new FileUploadOptions();
options.chunkedMode = false;
console.log("Start upload picture");
var ft = new FileTransfer();
ft.upload(deLokaleURL, encodeURI("uploaderino.php"), win, fail, options);
function win(r) {
console.log("Code = " + r.responseCode);
console.log("R" + r.response);
console.log("Sent = " + r.bytesSent);
dataForm.cardurl = r.response;
var dataString = JSON.stringify(dataForm);
$$.ajax({
type: "POST",
url: "upload.php",
crossDomain: true,
data: dataForm,
success:function(data)
{
callBack(true);
},
error: function()
{
callBack(false);
}
});
}
function fail(error) {
//alert("An error has occurred: Code = " + error.code);
console.log("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
showMessage("Image upload has failed, get a better internet connection and try again!" , function(){console.log("Upload van de form is mislukt!")});
return false;
}
}
}
You can play around with what you want the function to do, I'm not 100% sure what you're wanting :) But whatever you put in the function will execute after the ajax calls have been made.
You can use promises, something like this:
uploadDataAndImage(formData)
.done(function(){
// Its true, do my things
}).fail(function(){
//Its false
});
function uploadDataAndImage(dataForm) {
var deferred = $.Deferred();
var localURL = dataForm.cardurl;
console.log(localURL);
if (localURL == "") {
$$.ajax({
type: "POST",
url: "upload.php",
crossDomain: true,
data: dataForm,
success: function(data) {
console.log("Upload to server without card");
deferred.resolve();
},
error: function() {
console.log("Form couldn't upload to the server");
//alert("Couldnt upload to server, saving locally");
deferred.reject();
}
});
} else {
//set upload options
var options = new FileUploadOptions();
options.chunkedMode = false;
console.log("Start upload picture");
var ft = new FileTransfer();
ft.upload(deLokaleURL, encodeURI("uploaderino.php"), win, fail, options);
function win(r) {
console.log("Code = " + r.responseCode);
console.log("R" + r.response);
console.log("Sent = " + r.bytesSent);
dataForm.cardurl = r.response;
var dataString = JSON.stringify(dataForm);
$$.ajax({
type: "POST",
url: "upload.php",
crossDomain: true,
data: dataForm,
success: function(data) {
console.log("Upload to server with card");
deferred.resolve();
},
error: function() {
console.log("Form couldn't upload to the server, do nothing");
deferred.reject();
}
});
}
function fail(error) {
//alert("An error has occurred: Code = " + error.code);
console.log("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
showMessage("Image upload has failed, get a better internet connection and try again!", function() {
console.log("Upload van de form is mislukt!")
});
deferred.reject();
}
}
return deferred.promise();
}
Related
I'm trying to check if same email exist in server db, but ajax is returning code 0 even my server is opened.
I checked it by using URL in browser.
if (input == email.find(".form_input").val()) {
emailChecking = true;
$.ajax({
url: "https://localhost:8888/check?target=" + input,
async: true,
type: "GET",
dataType: "text",
success: (data) => {
console.log(data);
if (emailChecking == true) {
emailChecking = false;
inputField(email, error);
}
},
error: (request, status, errorLine) => {
if (emailChecking == true) {
emailChecking = false;
error = "cannot check email - code " + request.status;
inputField(email, error);
}
}
});
}
I have jQuery as client script and node JavaScript server as back-end.
I used to post the request to node server for getting data. Please find my AJAX call below.
My problem is even if my response is set to success it always comes in error function of the jquery.AJAX method.
And error object looks like
$.ajax({
url : 'http://127.0.0.1:3000/uploadcontent/fileUpload',
type : 'post',
data : formData,
enctype : 'multipart/form-data',
processData : false,
contentType : false,
error : function(error,jqXHR, exception) {
errorMessage(error);
console.log(JSON.stringify(error))
console.log(exception +" : "+error);
},
success : function(data) {
alert(data);
if (data.sucess){
successMessage(data.returnMessage);
} else {
alert('error');
if (data.returnObj != null) {
} else{
errorMessage(data.returnMessage);
}
}
}
})
Now, find below my node JavaScript route for the above request.
app.post('/fileupload', function(req, res) {
var fstream;
var fileName, bunchId, standard, userKey, subject, unit, chapter, topic;
req.pipe(req.busboy,function(err) {
if(err) {
console.log("ERROR: " + err.code + " (" + err.message + ")");
return;
}
});
req.busboy.on('file', function (fieldname, file, filename) {
console.log("Uploading: " + filename);
fstream = fs.createWriteStream(config.content_upload_path.pdf_path + filename + 'abc');
file.pipe(fstream,function(err) {
if(err) {
console.log('pipe error due to stream')
console.log("ERROR: " + err.code + " (" + err.message + ")");
return;
}
});
fstream.on('close', function () {
fileName = filename;
fileObject = file;
uploadFile(paramData, res)
res.redirect('back');
console.log('method complete')
});
fstream.on('error', function (err) {
console.log('stream on error event')
console.log(err)
generateWebServiceResponse(res, false, null, 200, err)
console.log(res);
res.send()
});
});}
generateWebServiceResponse method looks like this:
function generateWebServiceResponse(response, isSuccess, result, httpStatus,
returnMessage) {
response.json({
isSucess : isSuccess,
returnObj : result,
returnMessage : returnMessage,
resultCode : 0,
httpStatus : httpStatus
});}
Even in case of failure it should land in success function with isSuccess = false. But in each case it is landed in error case.
I am also not able to solve access origin error mentioned in the attached image.
It happened because of CORS. You must enable CORS for your route. The simplest way is using Node.js CORS middleware
Okay so I have a node js server running on my local machine and I'm trying to make an Ajax call to my server, the server is accepting the request and the request is executing successfully on the server side but on the client side I'm always getting the error response,
{"readyState":0,"responseText":"","status":0,"statusText":"error"}
My code to make Ajax request is as below,
$(document).ready(function() {
$("#button").click(function(e) {
e.preventDefault();
$.ajax({
crossDomain: true,
type: 'GET',
url: 'http://192.168.1.3:8080/insertintoplaylist?videoid=' + $("#videoid").val(),
async: true,
dataType: 'json',
success: function(res) {
alert("response"+res);
},
error: function(error) {
alert("error!" + JSON.stringify(error));
}
});
});
});
Here is the code snippet which will be executed when client makes a request to the path as mention in the url parameter of ajax call,
var req = youtube.videos.list({
id: video,
part: 'snippet,id'
},function(err,data,response){
if(err){
console.error('Error: ' + err);
}
if(data){
console.log(data.items);
var dataItem = data.items[0];
writeUserData(dataItem.id,dataItem.snippet.title,dataItem.snippet.thumbnails.medium.url,function(){
res.json({msg:'Saved'});
});
}
if(response){
console.log('Status code: ' + response.statusCode);
}
});
function writeUserData(videoId, title, thumbnail,cb) {
console.log("\nWriting data for video ");
firebase.database().ref('kidspoemTesting/' + videoId).set({
title: title,
thumbnail: thumbnail,
},function(err){
if(err){
console.log("Failed to save data"+err);
console.log("\nWriting data failed for video ");
}
else {
console.log("Data saved");
console.log("\nWriting data succeed for video ");
cb();
}
});
}
I wrote the following function that is supposed to send an AJAX POST request from the browser:
function addFormToDB(email, company, subject, text) {
var params = "email=" + email + "&company=" + company + "&subject=" + subject + "&text=" + text;
$.ajax({
url: 'http://127.0.0.1/submit',
type: 'POST',
data: '{"data":"' + params + '"}' ,
xhrFields: {
withCredentials: false
},
dataType: "jsonp",
contentType: 'text/plain',
success: function(data) {
alert("success");
},
error: function(result) {
alert("error");
}
});
}
In the server side (node.js + express) I have the following function that handles POST requests:
app.post('/submit', function(req, res) {
console.log("enter function");
var p = new Promise(function(resolve, reject) {
db.serialize(function() {
db.run("INSERT INTO users VALUES (?, ?, ?, ?)",
[req.query['email'], req.query['company'], req.query['subject'], req.query['text']],
function (err) {
if (err) {
console.error(err);
reject();
} else {
console.log("Transaction passed");
resolve();
}
});
});
});
p.then(function(){
res.status(200).send();
}).catch(function() {
res.status(400).send();
})
});
I don't know why but when POST request is sent, nothing happens and the program doesn't enter the function of the POST request. The console doesn't say anything.
This is how the 'network' window looks:
I understand that 404 error code means that there is a problem with the routing. However, when the client code is this (no JQuery) it works fine:
var params = "email=" + email + "&company=" + company + "&subject=" + subject + "&text=" + text;
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://127.0.0.1:3000/submit?" + params, true);
xhttp.onreadystatechange = function() {
console.log(xhttp.readyState + " " + xhttp.status);
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log("request " + params + " was sent to DB");
alert("Thank You!");
}
};
xhttp.send();
The path in both code snippets is the same: http://127.0.0.1/submit, so probably the problem is not with the path.
Do you know what is the problem?
Your issue here is the fact you are making aa JSONP call which is a GET request. You can not make a JSONP that is a POST. Looking at the request in the screenshot, you can see it is a GET.
dataType: "jsonp", <-- changes the POST to a GET
JSONP works by sticking a <script> tag on the page so it is a GET. So in the end the Ajax and the plain JavaScript are not the same. Plain JavaScript would be to append a script tag to the page.
What is it for?
var params = "email=" + email + "&company=" + company + "&subject=" + subject + "&text=" + text
...
data: '{"data":"' + params + '"}' ,
Just try it
data: { email: email, company: company, subject: subject, text: text }
in Node.js
req.param['email'] ... etc
Try this (need to remove jsonp and data):
function addFormToDB(email, company, subject, text) {
$.ajax({
url: 'http://127.0.0.1/submit',
type: 'POST',
data: {email: email, company: company, subject: subject} ,
xhrFields: {
withCredentials: false
},
success: function(data) {
alert("success");
},
error: function(result) {
alert("error");
}
});
}
For some reason, I cannot enter my success and error blocks when I am saving my model. Wether my response is successful "201" or error "404", my code will not hit the debugger lines. Does anyone know what could be going wrong?
SignInView.prototype.login = function(event) {
event.preventDefault();
return this.model.save(this.credentials(), {
type: 'POST',
url: 'http://localhost:3001/api/v1/users/sign_in'
}, {
success: (function(_this) {
return function(userSession, response) {
debugger;
return window.location.href = "/";
};
})(this),
error: (function(_this) {
return function(userSession, response) {
debugger;
var message;
message = $.parseJSON(response.responseText).error;
return alert(message);
};
})(this)
});
};
The save function only takes two parameters -- you are passing your success and error functions as a third param. Try the following:
SignInView.prototype.login = function(event) {
event.preventDefault();
return this.model.save(this.credentials(), {
type: 'POST',
url: 'http://localhost:3001/api/v1/users/sign_in',
success: (function(_this) {
return function(userSession, response) {
debugger;
return window.location.href = "/";
};
})(this),
error: (function(_this) {
return function(userSession, response) {
debugger;
var message;
message = $.parseJSON(response.responseText).error;
return alert(message);
};
})(this)
});
};