I am trying to make a post request to a url with the following code .
Passing object to http.send(params) function gives (400) bad request error.
I am not able to trace the issue here .
var http = new XMLHttpRequest()
var url = 'http://somerandomurl'
http.open('POST', url, true)
http.setRequestHeader('content-type', 'application/json')
http.setRequestHeader('accept', 'application/json')
http.onreadystatechange = function () {
if (http.readyState === 4 && http.status === 200) {
returndata = http.responseText
console.log(JSON.parse(returndata))
}
}
http.send(params)
Solution: http.send(JSON.stringify({'email': params.email, 'password': params.password})) it worked for me .
It seems to me that your issue is that you are trying to send a whole object instead of JSON. The correct way to do this would be to use http.send(JSON.stringify(params))
You should use one of three ways to do it
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#A_brief_introduction_to_the_submit_methods
Or either, you can take Axios.
You can use the new fetch API for this, makes it dead easy and less code
// Call the fetch function passing the url of the API as a parameter
fetch(url)
.then(function(response) {
// Your code for handling the data you get from the API
})
.catch(function() {
// This is where you run code if the server returns any errors
});
Also if your a newbie it will get things working quicker and help you solve your problem faster.
Related
First of all I have to say that I have NO EXPERIENCE in Ajax and I just need this one explanation in order for me to create a simple chrome extension.
There is not much I could find on internet even tho I believe this is very simple.
I need a part of code where I would "call" url from website and I need to adjust certain arguments in that url.
Request URL:http://URL_OF_THE_WEBSITE/v1/send?token=TOKEN_VALUE
Request Method:POST
Request Payload :
{amount: 1, user_id: 12345678}
amount: 1
user_id: 12345678
(this is something I get from Network panel- with url and token changed to real things - while calling url automatically from website, but I need to be able to call it manually too.)
So I have an idea of mixing AJAX(which I don't know) and JS in order for me to call this url.
I would use variables for both TOKEN_VALUE and amount&user_id, but I don't know how to even call that url and how to set "request payload" in order for site to do the thing I want it to do.
I would really appreciate if someone would be kind enough to help :)
Work I have done, but doesn't work:
var request=new XMLHttpRequest;
request.open("POST","https://URL_OF_THE_WEBSITE/v1/send?token=TOKEN_VALUE"),request.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"),request.Payload("user_id=12345678&amount=5");
I basically tried to remake an example I found online, but it didn't work out, therefore I need someone to actually explain to me how this works and how can I adjust arguments that I need.
function callAjax() {
// the XMLHttpRequest returns the ajax object that has several cool methods, so you store it in the request variable
// #data contains the $_POST[amount],$_POST[user_id],$_POST[whatever] since we are using POST method, if you're using PHP as a server side language
var request = new XMLHttpRequest(),
url = 'place_here_the_url_only',
data = 'amount=1&user_id=12345678&whatever=dataYouWantToSendToServerFromBrowser',
token = document.querySelector('meta[name="csrf-token"]').content;
// when the server is done and it came back with the data you can handle it here
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// do whatever you want!
console.log("The request and response was successful!");
}
};
// method post, your giving it the URL, true means asynchronous
request.open('POST', url, true);
// set the headers so that the server knows who is he talking to, I'm using laravel 5.5
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
// Token needed
request.setRequestHeader('X-CSRF-TOKEN', token);
// then you send the data and wait for the server to return the response
request.send(data);
}
Ajax: Asynchronous JavaScript And XML
It is a mean of communication between the browser and the server hosting the website, it cannot call any other server.
Asynchronous means the website continues to function normally, until the request is returned from the server and the:
if (this.readyState == 4 && this.status == 200) { }
gets triggered
I'm currently developing a intranet application for my company. Within my application i would like to fetch some variables with javascript and send them to a MySql database through php.
I know that javascript is a client-side and php is server-side so I'm not sure if it's even possible to transfer the variables through.
Goal is to get the current users computer name and store it in a SQL database whenever they are opening the intranet site.
<?php
<script type="javascript">
var network = new ActiveXObject('WScript.network');
<?php $pcName = "<script>document.write(network.computername)</script>";
</script>
?>
This part works perfectly. The computername is stored in the php variable $pcName and it shows fine on the intranet site when I try to echo the variable.
$sql = "INSERT INTO t1 (pcName) VALUES ('".$pcName."')";
But when I insert it into my sql table the value is "<script>document.write(network.computername)</script>".
Am I missing something? Or is it as I assumed that the variable is available on the clint, and the client only.
You will probably have to create and call an "API" of some sort. For example, you could have something like this on the client:
<script type="javascript">
var network = new ActiveXObject('WScript.network');
var pcName = network.computername;
fetch('storeComputer.php', {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
pcName: pcName
})
});
</script>
And then on PHP side:
// storeComputer.php
$json = json_decode(file_get_contents('php://input'));
$pcName = $json['pcName'];
// do what you want with $pcName..
There are many ways, but i use jquery inside javascript to send the parameter to php. Its works for me very well
try this
$('.add_item').click(function(){
var responsecontainer=$('#responsecontainer').val();
var ProductName=$('#ProductTable').val();
$.ajax({
url:"sample.php"
, method:"POST"
, data: {
ProductName: ProductName,
}
, success: function(result){
// do some thing here
}
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
}
use can use some other method too.
Yes, it's possible.
Javascript can launch any URL with parameters, notably including JSON encoded parameters; the URL can launch a CGI script; the CGI script can catch the JSON and interact with the MySQl; and then return the result to javascript, either asynchronously or synchronously. Here's an asynch URL launch:
// this is asynchronous - result comes back to callback later, while this returns immediately
// -----------------------------------------------------------------------=======------------
function callAjax(url, callback)
{
var xmlhttp;
// compatible with IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
callback(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
.
Here's a callback:
function cb_myCallback(theStuff)
{
// process theStuff here. If it's JSON data, you can unpack it trivially in Javascript,
// as I will describe later. For this example, it's just text. You're going to get
// back "hello, Ben"
console.log(theStuff);
}
.
So here's how I might use that to call a script that can access the database:
function pyRequest(upd_data,upd_callback)
{
var cd_url;
cd_url = '/cgi-bin/myPython.py?myData=' + encodeURIComponent(upd_data);
callAjax(cd_url,upd_callback);
}
pyRequest("Ben",cb_myCallback);
.
So here’s what happens. pyRequest() builds a URL that can call the Python (or whatever you like to use) script. callAjax() actually does the calling. This all returns immediately to the calling code. Later, when the script has completed whatever its task is, the callback, in the example cb_myCallback(), is sent whatever the script emitted.
Synchronous Approach
There may be times when you won’t want to use an asynchronous callback, because you can’t proceed until you have the data you asked for. In such cases, you need to use a synchronous request, which will not return (with the actual response) until the response has been received from the script. Note that in this function, I embed the URL to demonstrate a little variety in possible structuring of these types of usages:
// this is synchronous - result returns only when called script provides it
// ------------------------------------------------------------------------
function syncCallAjax(spdq_myData)
{
var remote = '__Unset__';
var request = new XMLHttpRequest();
var remote_url;
remote_url = '/cgi-bin/myPython.py?myData=' + encodeURIComponent(spdq_myData);
request.open('GET', remote_url, false); // false makes the request synchronous
request.send(null);
if (request.status === 200)
{
remote = request.responseText;
}
return(remote);
}
This question already has answers here:
JavaScript XMLHttpRequest using JsonP
(5 answers)
Closed 5 years ago.
I am trying to grab json data from reddit using vanilla javascript and I found something perplexing. I found this question here grabbing Reddit data via javascript
where there is a very solid solution making use of jQuery.
Here is the jsfiddle they shared. http://jsfiddle.net/DHKtW/353/ we can see the $.getJSON is working.
So I implement my own getJSON function like this:
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status === 200) {
callback(null, xhr.response);
} else {
callback(status, xhr.response);
}
};
xhr.send();
};
// let url = 'http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback';
// let url = 'https://www.reddit.com/r/CryptoCurrency/.json?jsonp=?';
let url = 'http://www.reddit.com/r/pics/.json?jsonp=?';
getJSON(url , function(err, data) {
if (err !== null) {
console.log('Something went wrong: ' + err);
} else {
// console.log('Your query count: ' + data.query.count);
console.log('Your query count: \n');
console.log(data.query);
}
});
You can see in the code I have a couple of test urls that I tried. the yahooapis.com worked fine, reddit didn't. I am thinking this has something to do with jsonp. Here is a jsfiddle I set up to demonstrate that my code doesn't work. https://jsfiddle.net/9ky480c8/ here it is throwing an error that the request must be sent over https, which wasn't the case in the other jsfiddle.
Anyone know how to handle this with pure javascript?
It looks like you can ignore the JSONP issue by just omitting that query parameter. For that Reddit API, https://www.reddit.com/r/CryptoCurrency/.json seems to work just fine on its own and returns pure, normal JSON.
If you want to use JSONP, check out JavaScript XMLHttpRequest using JsonP for a method of doing it with pure Javascript and XHR.
I think I ran into a problem of the same variable being used, I might have gotten lucky in some cases where they were separated by function scope. I recently replaced all of my jQuery code with plain JS and this broke a few things however the gained speed/lack of dependency(extra file to download) was good for me in this situation.
So I have the basic form of:
var http = new XMLHttpRequest(),
url = "php/my-script.php",
params = encodeURI('some-param='+value);
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function(data) {
//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
var result = JSON.parse(http.responseText);
if (result['status'] === "success") {
someFunction(result['some_key']);
}
}
}
http.send(params);
When I ran into the problem of the same http variable being used, I started to replace new ones with http1, http2, etc... seems like a bad idea. Especially having to replace all the http-method(?) calls afterwards like http2.responseText, etc... Should I make this into a function... then pass in the values to post and return the data out?
I guess I don't understand what happens when you call:
var http = new XMLHttpRequest();
Is that a one time use case, where after it has been called you need a new one for another post?
I will try the single-global-function approach. Everywhere I needed to do an AJAX call whether get or post, I always just used $.post/$.get on the spot, not sure if that's bad.
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"]