JQuery Ajax request doesn't reach the server - javascript

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

Related

sending json object to Django framework returns a 500 code error

I am sending an object using AJAX to a Django view. The data I am sending is mouse movement which is sent every 10 seconds to the server to be saved. Now, I have no problem reading my data from the client and server sides. The data gets saved in the database, but I get a 500 error message every time the function sends to the server gets executed. I tried to use fetch and got this error message:
POST error: SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
I searched about this error, and my understanding is that the problem is with the data type, but I am unsure how I can trace the problem and fix it. Could someone help me troubleshoot this issue?
here is my js function:
var target_id = '';
var eventsLog = {"mouse": []};
function logMouse(event){
target_id = event.target.id;
currDate = new Date()
start_time = currDate.getHours() + ':' + currDate.getMinutes() + ':' + currDate.getSeconds() + ':' + currDate.getMilliseconds();
var insert = [start_time, target_id];
(eventsLog.mouse).push(insert);
}
var timesPerSecond = 5;
var wait = false;
$(document).on('mousemove', function (event) {
if (!wait) {
logMouse(event);
wait = true;
setTimeout(function () {
wait = false;
}, 1000 / timesPerSecond);
}
});
const post_url = server_url;
function sendMovement() {
/* fetch(post_url, {
method: 'POST',
body: JSON.stringify(eventsLog),
credentials: 'include',
headers: {'Content-Type': 'application/json'}
}).then(res => res.json()).then(response => {
console.log('POST response:', response);
}).catch(error => {
console.log('POST error:', error);
});*/
$.ajax({
type: "POST",
url: server_url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(eventsLog),
dataType: "json",
success: function () {
},
error: function (req, textStatus, errorThrown){
console.log('Ooops, something happened: ' + textStatus + ' ' +errorThrown)
}
});
and this is my Django view:
movement = json.loads(request.body.decode('utf-8'))
and I checked the data type received in Django and it is a dictionary.
Retrieve csrftoken from cookies and attach it on the request header. Use setInterval() to send the request every ten seconds. Of course you can implement with Fetch API, but since you were using jQuery on your movement function, I also used it to send an AJAX.
get_mouse_movement.html
(just the script part)
<script>
var target_id = '';
var eventsLog = {"mouse": []};
var timesPerSecond = 5;
var wait = false;
function getCookie(name) {
...
}
function logMouse(event){
target_id = event.target.id;
currDate = new Date()
start_time = currDate.getHours() + ':'
+ currDate.getMinutes() + ':'
+ currDate.getSeconds() + ':'
+ currDate.getMilliseconds();
console.log([start_time, target_id])
eventsLog.mouse.push([start_time, target_id]);
};
$(document).on('mousemove', function (event) {
if (!wait) {
logMouse(event);
wait = true;
setTimeout(function () {
wait = false;
}, 1000 / timesPerSecond);
}
});
function sendLog() {
$.ajax({
type: "POST",
url: '/your/url/',
headers: {'X-CSRFToken': getCookie('csrftoken'), 'Content-Type': 'application/json'},
data: JSON.stringify(eventsLog),
success: function(data) {
console.log(data.message);
eventsLog.mouse = [];
},
});
};
setInterval(function(){
sendLog();
}, 10000);
</script>
views.py
import json
from django.http import JsonResponse
def mouse_movement(request):
if request.method == 'POST':
data = json.loads(request.body)
print(data)
return JsonResponse({'message': 'log is saved'})
return render(request, 'get_mouse_movement.html')
.loads() accepts, str, bytes or bytearray. You do not need to decode it.

Why am I getting Ajax error {"readyState":0,"responseText":"","status":0,"statusText":"error"}

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

Promises and uploading data

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

Redirecting after all functions finished

I am using the Parse hosting and Cloud Code functions.
I have a button that runs a function and then redirects to the same page to refresh it after the function has been called. The cloud function that is being called by the button then calls a number of different functions from there, including a httpRequest. From what I can see, the page is refreshing after the first function has been called, not the subsequent functions and httpRequests being called later. The data on the loaded page is still displaying old data, and has to be refreshed manually to see the updated data.
Here is the code the button is triggering:
// User Control Panel -- Logic
app.post('/panel', function(req, res) {
var currentUser = Parse.User.current();
if (currentUser) {
currentUser.fetch().then(function(fetchedUser){
var username = fetchedUser.getUsername();
if (fetchedUser.get("timeRemaining") < 10) {
res.redirect("/panel");
} else if (fetchedUser.get("isRunning") == false){
Parse.Cloud.run("dockerManager", {username: username}) // Ignoring the rest of the code, this is where the cloud function is called.
res.redirect("/panel");
} else {
res.redirect("/panel");
}
}, function(error){
});
} else {
res.redirect('/panel');
}
});
This is the cloud function that is running:
Parse.Cloud.define("dockerManager", function(request, response) {
var username = request.params.username;
var override = request.params.override;
var containerID = request.params.containerID;
//other irrelevant code here
} else {
Parse.Cloud.useMasterKey();
var query = new Parse.Query(Parse.User);
query.equalTo("username", username);
query.first(function(user) {
if (user.get("dockerID") == undefined) {
Parse.Cloud.run("createDockerContainer", {username: username});
response.success("[Docker Manager] Created Docker Container for username: " + username + " with Docker ID: " + user.get("dockerID"));
} else if (user.get("isRunning") == true) {
Parse.Cloud.run("stopDockerContainer", {username: username});
response.success("[Docker Manager] Stopped Docker Container for username: " + username + " with Docker ID: " + user.get("dockerID"));
} else if (user.get("isRunning") == false) {
if (user.get("timeRemaining") >= 10){
Parse.Cloud.run("startDockerContainer", {username: username});
response.success("[Docker Manager] Started Docker Container for username: " + username + " with Docker ID: " + user.get("dockerID"));
} else {
response.error("noTime");
}
}
});
}
});
Each of the functions this is calling send a httpReqest to another server, as shown below:
Parse.Cloud.define("stopDockerContainer", function(request, response) {
var username = request.params.username;
//irrelevant code
containerID = user.get("dockerID");
Parse.Cloud.httpRequest({
method: "POST",
url: "http://[redacted address]/containers/" + containerID + "/stop",
headers: {
"Content-Type": "application/json"
},
success: function(httpResponse) {
console.log("[Docker Stopper] Stopped Docker container for user: " + username + " with ID: " + containerID);
user.set("isRunning", false);
user.save();
response.success(true);
},
error: function(httpResponse) {
console.log("[Docker Stopper][CRITICAL] Error stopping docker container for username:" + username);
console.log("Request failed with response code " + httpResponse.status);
response.error(false);
}
});
});
});
Any ideas?

Create file on SkyDrive

I'm trying to create a new file on SkyDrive using JavaScript.
The closest thing I have so far is to create a file, but without any content.
function upload() {
WL.api({
path: "me/skydrive/files/testfile8.txt",
method: "PUT",
body: "Some file content"
}, function (response) {onError(response) });
function onError(response) {
$("#status").html(response.error)
}
}
Does anybody know how to create a new file on SkyDrive and pass a string as the file contents.
I have also tried using Ajax
$.ajax({
type : "PUT",
url: "https://apis.live.net/v5.0/me/skydrive/files/HelloWorld.txt?access_token=" + ACCESS_TOKEN,
data: "SOMEDATA",
processData: false,
success: function() { alert('Success!' );},
error: function(a,b,c) { alert('Error!' + a + b + c); }
});
This just returns a internal server error and leaves me pretty helpless :)
Anybody?
Sorry to reply to an old thread.
How about the following code?
It creates a file called 'hello.txt' that contains the string 'Hello, world!' in your SkyDrive folder.
var CLIENT_ID = '!!!!!!!!CLIENT ID!!!!!!!!';
var REDIRECT_URI = '!!!!!!!REDIRECT URI!!!!!!!';
var filename = 'hello.txt';
var content = 'Hello, world!';
var access_token = '';
WL.init({
client_id: CLIENT_ID,
redirect_uri: REDIRECT_URI
}).then(function (response) {
return WL.login({scope: ['wl.signin', 'wl.skydrive', 'wl.skydrive_update']});
}).then(function (response) {
access_token = response.session.access_token;
return WL.api({path: 'me/skydrive'});
}).then(function (response) {
var url = response.upload_location + filename + '?access_token=' + access_token;
var xhr = new XMLHttpRequest();
xhr.open('PUT', url);
xhr.onload = function () {
alert('success:', xhr.responseText);
};
xhr.onerror = function (error) {
alert('XHR error:', xhr.responseText);
};
xhr.send(new Blob([content]));
}, function (error) {
alert('error:', error);
});
BTW, This thread may also help you.

Categories

Resources