I am designing a web app where users can post content to a feed.
I usually send the post and the post data to the server via an XMLHttpRequest.
request = new XMLHttpRequest()
var user = 'current user'
var post = 'some text'
request.open("POST", "/sent_new_post?x=" + post + "&user=" + user)
request.setRequestHeader("X-CSRFToken", csrftoken);
request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
request. onload = () => { // do stuff when response comes back }
request.send()
On the server I then access the data with
x = request.GET['x']
But I have run into some problems using this method especially when the post text contains an '#'.
I was wondering if I can send the data using
request.send(data)
But I don't know how to access that data in the view function...
How can I access data in my view function that has been send to the server using request.send(data)????
I am not sure, because the question is not entirely clear to me.
If what you want to do is accessing the payload of the request you receive, then you need to know that
In an HttpRequest object, the GET and POST attributes are instances of django.http.QueryDict, a dictionary-like class customized to deal with multiple values for the same key. This is necessary because some HTML form elements, notably , pass multiple values for the same key1.
Therefore you can access the 'data' payload by writing something like this data= request.POST.get('data','').
If you want to send a # in a url parameter to the backend you have to encode it
"/sent_new_post?x=" + encodeURIComponent(post) + "&user=" + encodeURIComponent(user)
If you want to send the data in the post body you'll have to use request.POST to access the data, you will still have to encode the data you're sending.
request.send("x=" + encodeURIComponent(post) + "&user=" + encodeURIComponent(user));
Related
I have a script, which is reading a google sheet and returning
its content.I want to store all data to database.
var request = gapi.client.sheets.spreadsheets.values.get(params);
request.then(function(response) {
console.log(response.result.values[2][2]);
}, function(reason) {
console.error('error: ' + reason.result.error.message);
});
}
how to store it to mysql database or how to make recognize this return data to
PHP script
You'll need to do a PHP page to receive your data. To send your data, you should use an AJAX requests that will send your data to the php script. Let's have a look on XML HTTP Request with Javascript on Google, or you can read this : https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX
I'm currently trying to use an API and for the API, the developer console of that app asks the developer to submit a callback URL. Whenever the user of the app does something, it submits a GET request to the callback URL and I can retrieve data from that request. The current url I am using is https://appId:javascript-key=myJavascriptKey#api.parse.com/1/functions/receiveInfo. How can I handle the data, a.k.a the GET parameters, from the GET request? I found an answer on Parse.com that says how to retrieve data from a POST request, but all it says is that data = request.body. Do I do the same for GET requests and if so what do I do after that? Is request.body a json value?
Parse.Cloud.define("receiveInfo", function(request,response){
var params = request.body;//is this right to get the GET parameters they send? if so what do I do next?
});
The documentation has your solution at: https://parse.com/docs/cloud_code_guide#functions
For GET requests you have to use the request.params object which has all your request parameters for a GET are there. POSTS are sent in the request body, GET in the request parameters.
It looks like you are trying to get the params you can use something similar to:
Parse.Cloud.define("myMethod", function(request, response) {
if(request.params.myparam == "moo") {
response.success("Cow!");
}
else {
response.error("Unknown type of animal");
}
});
I am facing very strange issue here. I have a servlet running on my machine which renders my web page based on some input parameters.
Now, my screen capture with PhantomJS is not working if I try to send my data as a JSON object as a POST request type. For e.g. if I try:
Client side
var data = {"op": "get"};
page.open(address, 'POST', data, function (status) {
if (status !== 'success') {
console.log('[ERROR] :: Unable to fetch the address - ' + address + ", with data - " + data);
phantom.exit();
} else {
page.render(output);
}
console.log('processing...');
});
Server side
Now, on the server side, I am using Apache Velocity View templating so I have a single method which handles both get and post like :
public Template handleRequest(HttpServletRequest request, HttpServletResponse response,
Context context){
System.out.println(request.getParameter("op"));
//Always null
}
However, if I try sending my data from phantomjs as:
var data = "op=get&..."
It works
Also, at many places elsewhere in my code..I am doing Ajax POST requests to the same servlet and it works perfectly for all those request.
Would anybody explain why my servlet is not reading the JSON parameters passed from Phantomjs?
Servlets deal with simple request, so they only know how to parse (natively) HTTP parameters, either GET parameters from the URL, or POST parameters sent as application/x-www-form-urlencoded. Newer versions of the Servlet specification can also read multipart/form-data.
But there's nothing about JSON mentioned either in the Servlet or the HTTP specifications. So you must use a library that knows how to parse JSON and make the resulting object available in the Velocity context.
I've been having trouble with front-end back-end interactions. I'm relatively sure I'm sending the data but I cannot access the data afterwards. Most recently I have used this code template (from mozilla's help pages a link ) to send the data.
JavaScript:
function sendData(data) {
var XHR = new XMLHttpRequest();
var urlEncodedData = "";
// We turn the data object into a URL encoded string
for(name in data) {
urlEncodedData += name + "=" + data[name] + "&";
}
// We remove the last "&" character
urlEncodedData = urlEncodedData.slice(0, -1);
// We URLEncode the string
urlEncodedData = encodeURIComponent(urlEncodedData);
// encodeURIComponent encode a little to much things
// to properly handle HTTP POST requests.
urlEncodedData = urlEncodedData.replace('%20','+').replace('%3D','=');
// We define what will happen if the data are successfully sent
XHR.addEventListener('load', function(event) {
alert('Yeah! Data sent and response loaded.');
});
// We define what will happen in case of error
XHR.addEventListener('error', function(event) {
alert('Oups! Something goes wrong.');
});
// We setup our request
XHR.open('POST', 'http://ucommbieber.unl.edu/CORS/cors.php');
// We add the required HTTP header to handle a form data POST request
XHR.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
XHR.setRequestHeader('Content-Length', urlEncodedData.length);
// And finally, We send our data.
XHR.send(urlEncodedData);
}
HTML:
<button type="button" onclick="sendData({test:'ok'})">Click Me!</button>
My questions are: is there a better way of sending data (more suited to node)? and how can I access the data on the server side?
is there a better way of sending data?
This is rather subjective question, but here is an alternative: you can create form with hidden elements and send them to the server using FormData(). This allows you also comfortable files processing:
<form onsubmit="xhrsend(event,this)" method="POST" enctype="multipart/form-data" action="http://ucommbieber.unl.edu/CORS/cors.php">
<input type="hidden" name="myName" value="myValue"/>
<input type="file" name="myFile"/>
<input type="submit" value="Send"/>
...
</form>
use universal JS to XHR send any form
function xhrsend(ev,frm) {
ev.preventDefault(); // prevent submiting form
var XHR = new XMLHttpRequest();
XHR.addEventListener(...); // whatever
XHR.open('POST', frm.action, true);
XHR.send(new FormData(frm)); // send form data
this.reset(); // optional: reset form values
}
how can I access the data on the server side?
This question will guide you how to handle POST data on node.js server.
Note: if you play with node.js, I recommend to have a look at websockets - it can do more than XHR (like sending message from server to client).
I'm sending a POST from a chrome extension content script to a server I control. I setup the permissions in the manifest ok. Here is my XHR code. (I want to avoid jQuery for this). Its sending an empty responseText
var xhr = new XMLHttpRequest();
xhr.open("POST",'http://mysite.com/make',true);
xhr.onreadystatechange=function() {
if (xhr.readyState == 4) {
var res = JSON.parse(xhr.responseText);
console.log(res);
}
}
xhr.send({'textbox':data[0].user,'from':'extension'});
data[0].user is an object I got directly from the Twitter API
in my CI controller I have
$user = $this->input->get_post('textbox', TRUE);
$from = $this->input->get_post('from', TRUE);
$fullURL = 'http://www.google.com'; //example of a URL from code.
$json = $this->output->set_content_type('application/json');
$json->set_output(json_encode(array('URL' => $fullURL)));
The response text is empty
a jquery call on the other hand works fine
$.post("http://mysite.com/make", { 'textbox': data[0].user, 'from':'jquery' },
function(data) {
console.log(data);
});
Reason is simple, JQuery post method can accept JSON and then convert it to string and send to the server.
What you are trying to do is to directly send JSON here :
xhr.send({'textbox':data[0].user,'from':'extension'}) // Incorrect way
send method should either accept NULL or a string which is generally made up of QueryString Parameters like.
xhr.send("textbox="+ data[0].user + "&from=extension"); // Correct way
This will ensure that your data goes to the appropriate URL with textbox and from as post request parameters.
and queryString will be generated like textbox=username1234&from=extension in the packet's body unlike one goes in Get with the headers along side the URL.
jQuery's post method makes it simpler for you to format data you send using JSON and then internally it converts that to a queryString to send parameters.
You can't directly send Javascript object like that with an XHR object!
Also checkout this example:
http://beradrian.wordpress.com/2007/07/19/passing-post-parameters-with-ajax/