How to pass an object from client to server Nodejs - javascript

How do I pass a large object from my client to my node.js server, the object is stored in a variable in my script tags.

You need to run an ajax request and I would probably use JSON for it. This is an example using jQuery (the template engine is irrelevant, this is just JavaScript):
var data = {'bob':'foo','paul':'dog'};
$.ajax({
url: url,
type: 'POST',
contentType:'application/json',
data: JSON.stringify(data),
dataType:'json'
});

Just like you would any other client/server. Since clients and servers are detached, the server-side technology is irrelevant (though it does depend what type of endpoints).
Assuming you are using HTTP endpoints, you would simply use AJAX. You'd take your data, turn it into JSON, and then send it along.
With vanilla JavaScript on modern browsers, the easiest approach is with fetch(), which looks like this:
fetch('url-to-endpoint', {
method: "POST",
body: dataVariable
}).then(response => console.log(response.json()));
That's a basic POST. You can read up on all the ins and outs on MDN if you want to do something fancier.

Related

Adding jquery AJAX to send string into python script

How can i send a simple string, called accessToken (from Facebook API), to my python script? Is my way of thinking correct?
$.ajax({
traditional: true,
type: "POST",
url: my server ip:port?,
data: accessToken,
success: ok,
dataType: "String"
});
Lets say that python script will work on my local PC, should i then just tell my script to listen to POST requests on a given port? Does the string need any additional processing? I am not sure about whether this is correct, because it is my first time setting any ajax calls, or serverside python scripts, therefore i have, for now, no way to check whether this works.

Why JSON Object Serialization is needed or important sending in ajax call to the server?

I have seen at several places developers are using JSON.stringify(data) while making an Ajax call to the server for the serialization of post data in JSON string, but why it is needed ?
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
You have to encode the data using some method in order to send it over HTTP.
JSON is a standard format that supports common data structures like arrays. This lets you describe most kinds of data that you would want to send.
Several modern frameworks are capable to directly bind JSON data structures to their model businesses, this allows for a incredibly fast and easy relationship between client and server data models.
This way you can work feely on your client side with js objects, on the moment that you send data to the server via AJAX, you just stringify these objects to allow the server end to understand them, and in an automatic way your server will be able to translate that info to your server data classes, without further interaction needed (of course, you will need defined classes that are compatible with your client model data structures).

Jquery AJAX request with hash deep in URL

I am working on embedding Sisense into my site and I would like to explore embedding via AJAX rather than the dated Iframe (since I'll have to use a hosted JS file to bind to events, only accessible via a GUI).
I have the following AJAX call (url masked with fake IP):
$.ajax({
url: 'http://99.9.9.123/app/main#/dashboards/4251cc98nc83/widgets/n128cm836chna1?embed=true&r=false',
type: 'GET',
dataType: 'html',
data: {},
success: function(result){
$("#container").html(result);
}
});
When I make this call, the request URL looks like it has been truncated to the location of the hash:
(Ignore the Access-Control-Allow-Origin error. I will be changing that in my environment)
Any idea what is going on here and why I cannot access the full URL via AJAX? I have no access to changing the URL.
This is an issue with $.ajax in jQuery < 3. Indeed everything after # is stripped out from URL. It was fixed in jQuery version 3:
https://github.com/jquery/jquery/pull/2721
With hints from the comment provided, I'm seeing that the hash is never passed to the server:
Can I read the hash portion of the URL on my server-side application (PHP, Ruby, Python, etc.)?
My thought was to decode the hash, hit it via AJAX, and decode it on the server.
Another solution I'm thinking of is to create an endpoint on the server that I can call and pass parameters that correspond to the appropriate dashboard/widget ids. Haven't implemented yet; just a thought.

Javascript Dynamically Communicate with PHP

I'm creating a system where a Javascript script extracts data from a Sage extract, and stores it in a Javascript object (JSON I guess). I need to then upload the data to an SQL database via PHP.
I had thought of using an Iframe, by changing the src to the PHP pages URL, then pass GET variables to the page via the url. I was wondering if I could actually use tags to do this too? By creating new images and setting the src to the PHP pages URL (again, passing GET variables to it), then the PHP page could do the rest? I know the image wouldn't display anything, it doesn't need to. I just need a way to pass data to the PHP page.
Best practices?
The modern way of using JavaScript to communicate with a server is XMLHttpRequest. By default it is asynchronous and does give you the option to change this, though synchronous requests may be considered bad practice.
Here is a basic example
function sendObject(object, uri, callback) {
var xhr = new XMLHttpRequest(),
data = new FormData();
data.append('object', JSON.stringify(object));
if (callback) xhr.addEventListener('load', callback);
xhr.open('POST', uri);
xhr.send(data);
}
// ex. usage
sendObject(
{foo: "bar"},
"/somepage.php",
function () {console.log('completed with code:', this.status)}
);
Using a FormData saves you a little time, too. If you can't expect it to be available, simply do
postData = encodeURIComponent(key) + '=' + encodeURIComponent(value) + '&' + etc;
As the two other answer have said, for an HTML page with Javascript to communicate with the server, a PHP page, you would need to use XMLHttpRequest, aka AJAX. Paul S.'s answer is the best answer with respect to how to directly use XMLHttpRequest with Javascript.
However, one thing to keep in mind is that if you have to support older browsers, especially Internet Explorer version 9 or below, you'll run into quirks and it's advised to use a library for this. For the all purpose library, which includes not only AJAX methods but also form data handling and manipulating the DOM before, during, and after your request, your best bet is to use jQuery. For example, for an AJAX request to send data from a form:
$.ajax({
url: 'http://www.example.com/data.php',
data: $(form).serialize(),
dataType: 'JSON', // JSON will be returned if possible
type: 'POST'
}).then(function(data) {
...
});
jQuery is great, but it is also a big library and if you only really want or need AJAX requests, it's better to find a smaller library or use a function that's known to work cross browser. It's also important to note that jQuery has strange handling of promises, which is the way a function would say it will return a value but not right away. These promises are necessary if you chain AJAX functions together without making your code contain many nested functions. Two of the most well known promise libraries are rsvp.js and q.

Javascript/python design assistance

I'm running an external website that harvests data from an iframe on our internal company intranet. This part is written in Javascript and is working. However, now I need access to the data the js is harvesting to process it further in python. It is not an option to process in Javascript as well as that is technically not possible.
I would appreciate some pointers on where to go from here? How do I get the javascript data into my python scripts?
You will need to use an AJAX call to pass the javascript data to your server on the backend for python to process, The best way to do this is to encode your data in a JSON Object and pass it in an AJAX call:
json_obj = {your:[data]};
$.ajax{
url: [url of webservice/action],
type: "POST",
data: json_obj,
dataType: "json",
success: function(result) {
//Write your code here
}
}
//Note that this does run asynchronously, so the code that follows this will not wait for the ajax call to finish
Python has a nifty module, json, that you can use to decode JSON objects into Python Objects using:
import json
data_obj = json.loads(json_data_string)
This will put the json string you assembled in your javascript then passed to python with AJAX into a Python structure (dictionary or list, depending on how your object was built) for easy python processing.
You can then pass a JSON string back by using the dumps() function:
data_str = json.dumps(data_obj)
Sources:
Python JSON module documentation
AJAX Examples

Categories

Resources