XHR in Chrome Extension with CI - javascript

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/

Related

Sending data to the server via XMLHttpRequest in Django

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

Post to and visit a URL in Javascript

I'm trying to:
Post a JSON object to a URL and visit it at the same time.
Set the content-type and accept headers
I'm working with an old source base (asp classic / vb). Ideally, if I can do this in javascript it would be wonderful!
Constructing the js call with headers and data is simple with XHR:
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
var data = JSON.stringify({JSON DATA});
xhr.send(data);
However this is an async call and I can't seem to find a way of making it actually visit the URL in the browser.
The alternative is to create an form and append it to a HTML entity before using javascript to submit it. This time is post the data to and visits to the URL.. however, I don't have control over the headers.
So back to my questions. Can I post to and visit a URL in Javascript?
Given that visiting an URL in the browser is a GET request, and you want to POST at the same time, NO you cannot.
Why do you need to post and visit?
You could post your data and in the callback (once the post request is done) load the the page.
No.
The closest you could come would be to:
Use Ajax to make the request
Use DOM to modify the current page with data from the response
Use the History API to update the URL in the address bar
Changing the server side code to expect regular form encoded data and then submitting a regular form would probably be the simplest approach to solving the problem.
You are using XHR, and if you want to manage it from javascript... Add onreadystatechange property to your xhr (this function will be fired when your server response), and in this function redirect using window.location.href
var xhr = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Here redirect, with params if you need to
window.location.href = "https://stackoverflow.com?name1=value1&name2=value2";
}
};
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
var data = JSON.stringify({JSON DATA});
xhr.send(data);

difference between youtube's request and mine

i want to make a script that makes every video's comment section look like the ones that still have the old kind.
for example, videos on this channel:https://www.youtube.com/user/TheMysteryofGF/videos
in Firebug, in the Net tab, i noticed the comment JSON file's URL it is requested from is different.
i tried to run a code on the youtube watch page which would request the file the same way, but it doesnt work, and in firebug it says it was forbidden.
the URL is the same, they are both POST, and i cant figure out what is different. i can even resend the original request in firebug and it works... so anyway, here is a code i tried on a video with "1vptNpkysBQ" video url.
var getJSON = function(url, successHandler, errorHandler) {
var xhr = typeof XMLHttpRequest != 'undefined'
? new XMLHttpRequest()
: new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('post', url, true);
xhr.onreadystatechange = function() {
var status;
var data;
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate
if (xhr.readyState == 4) { // `DONE`
status = xhr.status;
if (status == 200) {
data = JSON.parse(xhr.responseText);
successHandler && successHandler(data);
} else {
errorHandler && errorHandler(status);
}
}
};
xhr.send();
};
getJSON('https://www.youtube.com/watch_fragments_ajax?v=1vptNpkysBQ&tr=time&frags=comments&spf=load', function(data) {
alert('Your public IP address is: ' + data);
}, function(status) {
alert('Something went wrong.');
});
You are using Ajax to get data. Ajax has 1 restriction: You can only get data from your own server. When you try to get data from another server/domain, you get a "Access-Control-Allow-Origin" error.
Any time you put http:// (or https://) in the url, you get this error.
You'll have to do it the Youtube way.
That's why they made the javascript API. Here is (the principal of) how it works. You can link javascript files from other servers, with the < script > tag
So if you could find a javascript file that starts with
var my_videos = ['foo', 'bar', 'hello', 'world'];
then you can use var my_videos anywhere in your script. This can be used both for functions and for data. So the server puts this (dynamically generated) script somewhere, on a specific url. You, the client website can use it.
If you want to really understand it, you should try building your own API; you'll learn a lot.
Secondary thing: Use GET.
POST means the client adds data to the server (example: post a comment, upload a file, ...). GET means you send some kind of ID to the server, then the server returns its own data to the client.
So what you are doing here, is pure GET.

Sending localStorage data to PHP

I've done some research and even have a book that explains Ajax calls to php and sending data to and from browser and server. I found this to be pretty close to what I need since I am using local storage How can I pass saved localStorage web data to a php script?, this link seems pretty coherent but I am not sure what to do on the PHP side How to pass data from Javascript to PHP and vice versa?,
though I have a bigger problem, the amount of data I have in local storage is pretty large, there are several different arrays that are stored there and are JSON encoded, when I get the array I use JSON.parse and to set the array in storage I stringify it. How could this be done to send that kind of data over? Not all the data in localStorage is an array either, there are hundreds of variables in local storage that need to be saved.
EDIT:
Here is my code since it was brought to my attention that it is needed.
I am trying to get all the data from localstorage to be sent to the server to be saved in a database.
function postData(){
var storage = JSON.stringify(localStorage);
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200 && xhr.status < 300) {
document.getElementById('div1').innerHTML = xhr.responseText;
}
}
};
xhr.open('POST', 'Membership.php');
xhr.setRequestHeader("Content-Type: text/json", "application/x-www-form-urlencoded");
xhr.send("data=" + storage);
}
On the PHP side of things I have
if ($_POST){
$data = json_decode($_POST['data']);
echo "The data" .$data;
}
I don't know if this is correct, I can't find anything on how to pass all localstorage data, this is basically what I was trying to ask before but obviously failed to convey that.
Basically what you need to do is:
Retrieve all the data from localStorage
Stringify everything (Now you have JSON representation of all the data)
Prepare the AJAX request using jQuery or other_framework_of_choice and set the payload to the stringified data and send it:
Send Content-type: text/json ti send a hint to the service that you are sending JSON data (Optional, but recommended)
Process the data within the PHP side (I.e json_decodethe payload and process it using your own logic satisfying your needs.
NOTE:
You didn't provided any code, so I would just skip the coding part (I can't guess your codes, mate)
EDIT
You can refer to Send data from localStorage via AJAX to PHP and save it in an HTML file
just skip the saving part and replace with your desired processing

Need to post large amount of data using xmlHttprequest

I need to pass huge amount of data to server without page loading. I have this code:
var GlType = "<%=GlType %>";
var pageUrl = "SelectAccount.aspx?callback=true&AccountList=" +accountList +"&AnalysisDate="+analysisDate+"&GlType="+GlType;
if (window.XMLHttpRequest)
{
var xmlRequest = new XMLHttpRequest();
}
else
{
var xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlRequest.open("POST", pageUrl, true);
xmlRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlRequest.send(null);
I am have passed using query string its exceeded the maximum Length of query string. Help me on this..
Since you're already using the POST method, you can pass data in the body.
xmlRequest.send("Field1=abc&Field2=def");
You can retrieve the data on the server, e.g. in ASP.NET:
if (Page.Request.Form["Field1"] == "abc") ...
For GET method you can only use the query string for transferring data.
You're sending the request via post, but putting everything in the query string!
Instead, you should send the data as the body of the request (passed to the send method).

Categories