Submit FORM data then return response [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have the following code which sends post data to my form and alerts the expected result, however I'm finding it hard to save this as a variable I can use outside the function, can anyone offer any help?
<script>
var http = new XMLHttpRequest();
var url = "form.php";
var params = "name=test";
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() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.(params);
</script>

Just declare a variable and set it when the request responsed by server;
var http = new XMLHttpRequest();
var url = "form.php";
var params = "name=test";
var response;
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() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
response = http.responseText;
}
}
http.(params);

Related

Perform $.getJSON without using JQuery [duplicate]

This question already has answers here:
How can I make an AJAX call without jQuery?
(24 answers)
Closed 6 years ago.
How do I get country code using javascript only, I am not allowed to use jQuery.
I have seen some sites like http://ipinfo.io , but all examples uses JQuery getJson, can I implement the same method :
var country_code = null;
$.getJSON('http://ipinfo.io/' + userip, function(data){
country_code = data.country;
alert(country_code);
});
I tried the following, but it returns a page instead:
var request = new XMLHttpRequest();
request.onload = function(elements) { console.log(elements); };
request.open("get", "http://ipinfo.io", true);
request.send();
Working example:
var someIp = '8.8.8.8';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
};
xmlhttp.open("GET", "//ipinfo.io/"+someIp+"/json", true);
xmlhttp.send();
<div id="myDiv">
pending
</div>
The ipinfo.io service returns JSON format only when proper header requesting JSON is attached. But it can be specified easily also with the /json directly in the requesting url.

How to post JSON from javascript to php [duplicate]

This question already has answers here:
send json object from javascript to php
(3 answers)
Closed 6 years ago.
I encoded an array into JSON in javascript:
var data = JSON.stringify(cVal);
And here is my ajaxrequest object:
function ajaxRequest(url, method, data, asynch, responseHandler){
var request = new XMLHttpRequest();
request.open(method, url, asynch);
if (method == "POST")
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
request.onreadystatechange = function(){
if (request.readyState == 4) {
if (request.status == 200) {
responseHandler(request.responseText);
}
}
};
request.send(data);
}
and I send the json to php with this ajaxrequset:
ajaxRequest("setOrder.php","POST", data , true , dosetOrder);
in php side:
$array=$_POST['data'];
but system says that the data in a undefined index in php
Create an object and stringify to json
var data = {};
data["username"] = username;
data["password"] = password;
var jsonData = JSON.stringify(data);
Send it to your endpoint
function ajaxRequest(url, method, data, asynch, responseHandler){
var request = new XMLHttpRequest();
request.open(method, url, asynch);
if (method == "POST")
request.setRequestHeader("Content-Type","application/json");
request.onreadystatechange = function(){
if (request.readyState == 4) {
if (request.status == 200) {
responseHandler(request.responseText);
}
}
request.send(data);
}
decode it at your endpoint
plain PHP
$body = json_decode(file_get_contents("php://input"), true);
echo $body["username"];
Slim Framework PHP
//example with Slim PHP framework
$body = json_decode($app->request->getBody(), true);
echo $body["username"];

How to send JSON response from python server to the javascript using ajax call

elif self.path == "/recQuery":
r = requests.get('http://example.com') # This returns some json from a request to another server.
print r.json()
self.wfile.write(r.json())
.
var http = new XMLHttpRequest();
var url = SERVER + "/recQuery";
var params = JSON.stringify({
query: search_query
});
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
console.log(http.responseText);
How can i send data from python server to javascript using ajax call. The one i am using does not return anything in the console. Can you please tell me what i am doing wrong here. I need send the response of what i get from requests.get method to the ajax call. The json should be returned to the ajax call in response. Problem is with the self.wfile.write method, When i use this i dont get anything on javascript side.
var http = new XMLHttpRequest();
var url = SERVER + "/recQuery";
var params = JSON.stringify({
query: search_query
});
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {
console.log(http.responseText);
}
};
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
I was not fetching the response onreadystatechange. So this works for me. Thanks !

Taxee API (http://www.taxee.io/) - JavaScript - How To: POST Request and Pass Parameters

Thanks for helping out with my question. I've been trying to get the federal, state, and FICA tax from a POST Request on this Taxee API (https://market.mashape.com/stylinandy/taxee), but haven't been able to get it working. I was able to access certain data (simply to figure out how this API works) using one of the two GET requests available for this API:
var state = 'CA';
var year = 2014;
var url = ' https://taxee.io/api/v1/state/'+year+'/'+state;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.onload = function() {
var result = JSON.parse(this.responseText);
console.log(result.single.income_tax_brackets);
xmlhttp.abort();
}
xmlhttp.send();
But the data I really need is in the POST request. I would like to know how to access a POST request for this, and more specifically, pass the parameters as noted on the link above. Thanks for any help you can provide, it's always greatly appreciated.
Figured out how to do it actually. The problem was the way that parameters are passed differently in POST requests. Hopefully this helps someone else out there:
var url = 'https://taxee.io/api/v1/calculate/2014';
var params = "filing_status=married&pay_rate=100000&state=CA";
var http = new XMLHttpRequest();
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);

Raw javascript eq of ajax post is not working correctly [duplicate]

This question already has answers here:
Send POST data using XMLHttpRequest
(13 answers)
Closed 7 years ago.
I am trying to make some ajax post raw js script and I am using one of the questions asked here in stackoverflow but I encountered a problem.
var r = new XMLHttpRequest();
r.open("POST", "###URL###", true);
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
console.log(r.responseText);
};
console.log(price);
r.send("prize=" + prize);
return false;
When I check in chrome network the payload is sent correctly prize=632 but the result of the php script with $_POST['prize'] is empty. Where can the problem be?
Best regards!
You are missing the headers:
var data = "prize=" + prize;
var r = new XMLHttpRequest();
r.open("POST", "###URL###", true);
// Send the expected headers information along with the request
r.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
r.setRequestHeader("Content-length", data.length);
r.setRequestHeader("Connection", "close");
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
console.log(r.responseText);
};
console.log(price);
r.send(data);
return false;

Categories

Resources