I want to submit a POST request while passing a url among other parameters.
I have the following script but it is not working.
var params = "param1="+param1_value+"&url="+url_value;
var xhr = new XMLHttpRequest();
xhr.open("POST", action_url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
console.log("Done");
}
}
xhr.send(params);
Assuming that the url_value is something like this:
https://www.domain.com/blah?param=&email=domain%40email%2Ecom&blah=1234
what would be wrong with this script?
Take a look at this question/answer - Should I URL-encode POST data?
Your sample value for url_value is using the HTML Entity Code. Because of the & symbol in the value, it is being sent as multiple values. You probably need to URL encode it so it looks like this
https%3A%2F%2Fwww.domain.com%2Fblah%3Fparam%3D%26email%3Ddomain%40email.com%26blah%3D1234
You may have a problem when trying to access another domain/website. The receiving side must have the Access-Control-Allow-Origin header in its return message.
You can probably find your solution in this answer.
You are missing quotation to the url string value,alert the parameter string as below
var params = "param1='"+param1_value+"'&url='"+url_value+"'";
Related
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);
I am saving the coordinate (generated by click on google map) in the variable ccc. Now I want to process this variable in Django. How to get its value like we get from HTML input element (for eg.
myX = request.POST.get("myInput"))
Here is the curtailed code:
<html>
<script>
google.maps.event.addListener(map, 'click', function(e) {
var ccc = e.latLng.lat(); //I want to retreive this variable
//ccc = 77.6746784
});
</script>
</html>
You can use ajax request to send data to the server like this
var xhr = new XMLHttpRequest()
var params = "ccc=" + ccc;
xhr.open("POST", YOUR_DJANGO_VIEW_URL, true);
//Send the proper header information along with the request
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {//Call a function when the state changes.
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send(params);
Obviously the only way to send values from the browser to your django server is to send an HTTP request (using POST because it's submitting data for processing). Whether you use a form and a plain post request (eventually submiting the form via javascript too), or you post using ajax (well, using a XMLHttpRequest object to be exact).
I wanted to know if there was a way I can receive information from API through JavaScript. I'm currently trying to use the information from API from www.openweathermap.org but I'm not sure how I can do it with JS. I currently tried
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.openweathermap.org/data/2.5/weather?
lat=38.892634199999996&lon=-77.0689154", false);
xhr.send();
console.log(xhr);
which responds and sends me information in JS Object format:
{ response: {"coord":{"lon":-77.04,"lat":38.9},"weather":[{"id":800,"main":"Clear",
"description":"sky is clear","icon":"01d"}],"base":"cmc stations","main":{
"temp":301.51,"pressure":1016,"humidity":51,"temp_min":299.15,"temp_max":304.15},
"wind":{"speed":2.6,"deg":360},"clouds":{"all":1},"dt":1436565479,
"sys":{"type":1,"id":1325,"message":0.008,"country":"US","sunrise":1436521925,
"sunset":1436574893},"id":4140963,"name":"Washington, D. C.","cod":200}\n',
responseText: '{"coord":{"lon":-77.04,"lat":38.9},"weather":[{"id":800,
"main":"Clear","description":"sky is clear","icon":"01d"}],"base":"cmc stations",
"main":{"temp":301.51,"pressure":1016,"humidity":51,"temp_min":299.15,
"temp_max":304.15},"wind":{"speed":2.6,"deg":360},"clouds":{"all":1},
"dt":1436565479,"sys":{"type":1,"id":1325,"message":0.008,"country":"US",
"sunrise":1436521925,"sunset":1436574893},"id":4140963,"name":"Washington, D. C.","cod":200} }
I tried console.log(xhr.response.coord) and console.log(xhr.responseText.coord) as an example and both comes out undefined. Do I need to do something else to print out the information?
I know you can use $.get(URL, function()) to receive the information via JQUERY but is there a way I can do it just JS?
You should parse the string as a JSON object. Like this:
var data = JSON.parse(xhr.response);
console.log(data.coord);
You are missing the response handler
var xhr = new XMLHttpRequest();
// when the async call finishes, we need to check what happened
xhr.onreadystatechange=function(){
// if it finished without errors
if (xhr.readyState==4 && xhr.status==200){
// we get the data
var data = JSON.parse(xhr.responseText);
// this should be your json
//console.log(data.response.coord);
document.getElementById('response').innerHTML = xhr.responseText;
}
};
// NOTE! for demo purposes I'm using another api query that does not require an api key, change this to your api url
xhr.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=London,uk", false);
xhr.send();
<div id="response"></div>
Your response is in JSON so you need to parse it first.
Use JSON.parse(xhr.response) to parse the response.
Like this:
JSON.parse(xhr.response)["coord"]["lat"]
JSON.parse(xhr.response)["coord"]["lon"]
I have a JavaScript code that is supposed to send some data to a php file on the server. The JavaScript code gives an alert that the post was successful, but no data is on the php file. No errors show up in the console. What is the problem here?
Here is the code:
var data = "It works";
var url = "data.php";
var http = new XMLHttpRequest();
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert("It worked");
}
}
http.send(data);
Here is the site for the code:
http://mikeyrichards.freeiz.com/run.html
EDIT: A clarification, I only want the data to show up like a text file on the PHP. For some reason, my server cannot open text files, so I have to use PHP
You need to send data in key value format something like this
var data = "lorem=ipsum&name=test";
Try changing to:
var data = 'data=It+works';
Then you can access it in the PHP script as $_POST['data'].
Don't forget to encode the space as + or %20. If you're generating the data dynamically, use encodeURIComponent to encode it properly:
var data = 'data=' + encodeURIComponent(value);
Hi I make an xmlHttpRequest like this:
var xhr = new XMLHttpRequest();
var params = 'gbook_text=' + encodeURIComponent('sdfsdf');
xhr.open("POST", '/gbook/save/7697256.html', true)
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
}
xhr.send(params);
And I need to parse some data from response which is just a webpage
I need to parse It via dom methods like getElementById().
I know that I can write something like:
xhr.responseXML.getElementById('author')
But it works only if server sets a header
Content-Type: text/xml
Otherwise responseXML is null
So what are my options?
P.S: only js without any libraries.
P.P.S: browser requirements: chrome, ff, ie8+
Edited: okay options, which one is better:
1)parse xhr.responsetext as a string
2)redirect to response page and parse it.How to do it, btw?
If i understand your question, you can only get your response back in text, yet you want to search for it as an HTML document, you can try creating a div and putting the html response as the innerHTML of the div.
var res = document.createElement( 'div' );
res.innerHTML = xhr.responseText;
res.querySelector("#ElementID")
Have you tried setting the responseType and/or using the overrideMimeType method?
xhr.responseType = 'document';
xhr.overrideMimeType('text/xml');