Send POST request from JavasScript to Sinatra endpoint - javascript

so I have a javascript file that saves a specific value in a variable send that I need to send to my ruby routes file through a POST request. I'm a little confused if I can do this since what I have does not seem to work. I'm using the MVC structure so my routes file is saved in my controllers folder.
In my JS file, I have the following:
var send = "test"`
$.ajax({
url : window.location.href + "senddata/",
type : ",
data : { send: send },
}).done(function(response) {
alert('1');
}).fail(function (error) {
alert('2');
});
In my Ruby file, I'm not sure what to do to be able to receive this data? I know I need to do #variable = params[:send] but not sure from there. I'm using Sinatra.
My ruby code is as follows:
post '/senddata/' do
flash[:success] = "Reached"
end

Related

fetch mysql data into javascript variable

var events = [
{"id":"1","title":"pending","start":"","end":"2020-04-27 10:25:34","url":"","allDay":"1"},
{"id":"2","title":"22","start":"2013-12-15 10:25:47","end":"2013-12-16 10:25:39","url":"","allDay":"1"},
{"id":"3","title":"33","start":"2013-12-26 10:25:50","end":"2013-12-27 10:25:42","url":"","allDay":"false"},
{"id":"4","title":"2-12 ","start":"2020-04-20 10:26:28","end":"2020-04-20 10:26:28","url":"","allDay":"false"},
{"id":"6","title":"test nay","start":"2013-12-09 00:00:00","end":"2013-12-11 00:00:00","url":"event","allDay":"false"}
]
i want to Retrieve data in my database into this JavaScript variable please anyone simply explain how do to do that ?
You have to use any of the backend technologies (Java/Python/php/Node JS etc) to save the json array to DB. This is because javascript can not directly handle or connect to Database.
From javascript side, you can use jQuery ajax to send the data to your backend api as follow.
$.ajax({
type: "post",
url: "", //your backend API endpoint
data: {data: events},
success: function(responseData){
//If backend api runs successfully, control comes to this method with responseData as return from api
},
error: function(responseData){
// If api call does not run properly, control comes in this method.
}
});
And your backend API got the data, connects to the DB and run the SQL to store the data. So based on backend technology, you have to develop the code.
On the server side, create a get or post route which sends data in JSON format.
On the client side, use jQuery/fetch/axios to grab that data. It's easy. Try this, https://github.com/axios/axios

How to Access To A Zip File on Server Using JQuery Ajax - No Need to Download

Can you please let me know how I can get a ZIP file stored on same server using the jquery Ajax? Please be informed that I do not want to download the file
I need to pass the result , if success? to an API snippet like this, (this is using a Form to pass a zip file from client to the request Here is The Working Demo
request({
url: portalUrl + '/sharing/rest/content/features/generate',
content: myContent,
form: dom.byId('uploadForm'),
handleAs: 'json',
load: lang.hitch(this, function (response) {
if (response.error) {
errorHandler(response.error);
return;
}
var layerName = response.featureCollection.layers[0].layerDefinition.name;
addShapefileToMap(response.featureCollection);
}),
error: lang.hitch(this, errorHandler)
});
but I need to pass the zip file from server witout using a form and here is what I would like to do
var data = "www.mydomain.com/GIS/App.ZIP";
request({
....,
form: data,
....
});
Update
As menitoned API offers the Formdata option as well but how I can pass second parameter of type inside the append method?
var theFile = "http://localhost/Portal/APP.ZIP";
var myFormData = new FormData();
myFormData.append(theFile, ? );
Javascript cannot access the local filesystem without user intervention for security reasons. A user must take an action to load a file. Otherwise, it would be very easy for malicious web pages to traverse your file system.
You can use javascript via AJAX to trigger a server side script which can access the server file system and return results to javascript though.

Example on Making rest call to Python server using angular js client

Can anybody give an example on using rest in getting and posting data from/to python server using Angularjs .
Please provide an example for both client(angularjs) and server(python) ..
where my sample client-side code is
var student_id = 12
$http({
method:"POST" // or get
url: //url to the python file
data: //this is what confusing me .. how to send that student id
}).success(function(data){
console.log(data);
})
and in python i want to run a function which prints student id
def print_info(id): ## here id is the student id that shall be recieved
print "student id is %s" %id
here i want the js client to send that student_id value to python server where it should receive it and send that value of print_info function to the client..
Thanks in advance..
You can use it like this:
$http.post('<your_url>', data).success(function(data) {
//handle the data returned
}, function(error) {
//handle if an error is thrown
})
And the format of your data can be a json like this:
data = {
"student_id": value
}

PUT and POST Request of .save() of Backbonejs model

How to be confirmed whether a backbonejs .save() is sending PUT request ?? I checked my server side, which is working good, there is no problem in server side. But my .save() is not working.
Here is my model of backbone
define(['underscore','backbone'],function(_,Backbone)
{
var my_model = Backbone.Model.extend(
{
urlRoot: "http://localhost/back/server_file.php/number"
});
return my_model;
});
Here is how I am using .save()
var my_data = {
id: data.id,
code: data.code
};
var My_model = new my_model();
My_model.save(my_data,
{
success: function(response)
{
alert('Yes');
},
error: function(response)
{
alert('No');
}
});
I think my .save() is sending POST request to server.
UPDATE
I think I could find out my problem. I am describing that here.
What I would like to do
I would like to send 2 parameters from backbonejs model to server side script (I am using PHP SLIM Framework). Based on those 2 parameters server side script update a record's(2 field of this record match with those 2 parameters ) another field with a static parameter at database.
What backbonejs provide (As I think )
Backbonejs has a model with id as JSON format. Backbonejs sends PUT request to server side script. Server side script just dump (update) the data(which was as JSON format,like a bundle) to the database with matching id. Serer side script would not like to look inside the data.
I am getting (from network tab of firebug) my PUT request URL is like http://localhost/back/server_file.php/number/1 (This is the id) . On the other hand I would like to get URL is like http://localhost/back/server_file.php/number/1 (id the first parameter)/456 (Second parameter).
If I am right, anyone could say how can I implement my plan??
This should work,
My_model.set(my_data);
My_model.save(null, {
wait : true,
url : "http://localhost/back/server_file.php/number/1/456",
success : function(response){
},
error : function(e){
}
});
You can debug the request being sent in network tab of Chrome Developer Tools or you can use a network tool like Fiddler to see all requests.
Refer the attached on where to see the request method being used.

In javascript how do you open a file from the server?

Im working in an application that uses java + spring on the server side aswell as extdirectspring. On the client side it uses extjs/javascript.
I want to poke a method on the serverside and retrieve a file from the database. If the file doesn't exist then I'd like to display an error in some way.
The attempt to retrieve the file and the check it exists need to happen in the same call - the file could be deleted in between calls.
The way I can see people have done it in the current application is using spring controllers + request mappings and a window.open("someUrl/filename.blah"); with the server returning the file from the mapped method.
This doesnt seem to let you handle the case where the file doesn't exist though.
Ideally I'd just like to send some json back from the server which has the file data (possibly null) and sucess/failure. When I get the response I can then either show some information about the failure or open the file. Unfortunately I can't observe the current failure mode because something somewhere is caching the files - if I delete them from the database then they appear to still exist and you can still download them!
By 'open' I mean show the standard 'what do you want to do with this file open/save' dialog. I'm not trying to parse the file or do anything with it - I just want to serve it up to the browser/user.
Is there a way to do that without using a url and window.open? Eg some method that takes a blob of data and a file name or similar?
Update
The transfer of the data/json isn't the problem I'm trying to solve.
As I'm using extdirect I'll probably just do it like this:
public class SomeClass
{
#ExtDirectMethod
public AFile getFile(Long id) throws Exception
{
//do stuff
}
}
Then on the clientside you just do:
someClass.getFile(id, function(file){
if(file.found){
SomeHowGiveThisToTheUser(file.name,file.data); ????
return;
}
ReportCouldntFind(file.name);
});
The bit I dont know how to do is the give the file to the user.
Further update
I dont think it's possible to do this without blob urls or data uri's. Both of these are mentioned in this post. I haven't tried them out as we are having to support a browser that is too old for both techniques.
You are wanting to do some standard Ajax (Assuming you have jQuery available).
Something like:
$.getJSON( url, function( data ) {
if (data.success){
} else {
}
});
And on the server side, add code to return the expected JSON.
In extJS:
Ext.Ajax.request({
url : url,
method: 'GET',
headers: { 'Content-Type': 'application/json' },
params : params,
success: function (response) {
var jsonResp = Ext.util.JSON.decode(response.responseText);
if (response.success){
// do success stuff, like using response.fileData
} else {
// do fail stuff
}
failure: function (response) {
var jsonResp = Ext.util.JSON.decode(response.responseText);
// etc.
});
On the server in a Java servlet you could something like this (assumes apache commons file util):
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
InputStream in = new URL( "http://remote.file.url" ).openStream();
IOUtils.copy(in, response.getOutputStream());
}
Probably a more spring specific way to do it, but that gives you an idea.
For your case, you want to wrap the file contents in a JSON object that includes the success proeprty. For that, use the Java JSON jar: http://json.org/java/
Update: Finally understand what you are asking.
It finally occurred to me that you are asking how to handle the actual download.
There's a couple ways these days.
Take a look at this SO answer, this is using an iFrame: Download File Using Javascript/jQuery
There are also several fancy downloader components, including several for jQuery.
So you would do a two part process: check for the file availability using a standard ajax call, and then if response.success, use the downloader to serve the file to the user.

Categories

Resources