send an http request without XHR in an event handler - javascript

How to send an http request with either post/get method using javascript as an eventhandler? Thanks! Paul

Okay, you don't want to use Ajax.
You can use an event handler to submit a form!
<a href='#' onclick='cow_submit("zoodle")'>send</a>
<form method='post' id='formie' action='find_some_action.php'>
<input type='hidden' id='snoutvar' name='snoutvar' value='snout'>
</form>
<script>
function cow_submit(a_var_to_set){
var plip=document.getElementById('formie');
var snout=document.getElementById('snoutvar');
snout.value=a_var_to_set;
plip.submit();
}
See https://developer.mozilla.org/en/DOM/form

use XmlHttpRequest
sample code:
var client = new XMLHttpRequest();
client.onreadystatechange = handler;
client.open("GET", "test.xml");
client.send();
function handler()
{
// your handler
}

You can use XMLHttpRequest for sending request from javascript
Sending GET request
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("GET", url+"?"+params, true);
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(null);
Sending POST request
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
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);
And don't forget to encode parameters using encodeURIComponent for param value encoding in case of user input
e.g.
params="paramName="+encodeURIComponent(paramValue);

The standard class for doing this is XmlHttpRequest, but it's not universally supported. On some browsers you have to use ActiveXObject("Microsoft.XMLHTTP") instead.
Look into the jQuery system which provides HTTP download (AJAX style) methods regardless of the underlying browser APIs (hence avoiding a lot of the code shown in Tzury's answer).
The jQuery AJAX documentation is at http://docs.jquery.com/Ajax

You should try to add atring in a hidden field and then call the form.submit() to submit your form into the page define in action.
<script type="text/javascript">
function doTestFormSubmit(yourString) {
document.getElementById("myString").value=myString;
document.getElementById("testForm").submit();
}
</script>
<form name="testForm" id="testForm" action="yourDesiredPage.php" method="post">
<input type="hidden" name="myString" id="myString" value=""/>
</form>

Ajax Tutorial (http://code.google.com/edu/ajax/tutorials/ajax-tutorial.html)
var obj;
function ProcessXML(url) {
// native object
if (window.XMLHttpRequest) {
// obtain new object
obj = new XMLHttpRequest();
// set the callback function
obj.onreadystatechange = processChange;
// we will do a GET with the url; "true" for asynch
obj.open("GET", url, true);
// null for GET with native object
obj.send(null);
// IE/Windows ActiveX object
} else if (window.ActiveXObject) {
obj = new ActiveXObject("Microsoft.XMLHTTP");
if (obj) {
obj.onreadystatechange = processChange;
obj.open("GET", url, true);
// don't send null for ActiveX
obj.send();
}
} else {
alert("Your browser does not support AJAX");
}
}
function processChange() {
// 4 means the response has been returned and ready to be processed
if (obj.readyState == 4) {
// 200 means "OK"
if (obj.status == 200) {
// process whatever has been sent back here:
// anything else means a problem
} else {
alert("There was a problem in the returned data:\n");
}
}
}

Related

AJAX XHR request onReadyStateChange events order and number of times clarification

I'm learning and trying to write a simple stock quote tool using Python-Flask and Javascript.
I specifically want to learn plain Javascript. My code is working, but what I don't understand is when I'm watching the developer console, I get 3 error messages printed before I get the successful console.log(response).
Is it simply that the code loops 3 times before the response comes back, so it logged 'ERROR' each of those times before finally returning the 200 status? Would someone explain it to me or point me to a good article/post?
My event listener:
document.getElementById("btn_quote").addEventListener("click", getQuote);
The ajax call:
function getQuote(e){
e.preventDefault();
var ticker = document.getElementById("ticker").value
var shares = document.getElementById("shares").value
var url = "/quote/"+ticker+"/"+shares
// Fetch the latest data.
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
var response = JSON.parse(request.response);
console.log(response);
}
} else {
// TODO, handle error when no data is available.
console.log('ERROR');
return false;
}
};
request.open('GET', url);
request.send();
}
It's not returning separate HTTP status codes, its returning different ready states.
Change your console.log("ERROR");. To console.log(request.readyState);.
Then you will see what it is reporting and why.
i think you should be checking your readyState values with the actual values of the response. For you reference, following are the possible values of readyState:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
So you could basically check it to be 4 in your case:
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4) {
//response statements
} else {
//error statements
}
};
Basically, ajax calls will get notified for the following events which is called as readyStateChange event.
For most cases, you used to get 4 ready state changes based on the speed of the connection (rare cases only only one if it's very quick) and you should check whether it is 4 which means the response is completed now.
To check whether the request is suceess or not, you should check the request.status === 200 which means success and can check for other http status code for errors like 404, 500 etc.
document.getElementById("btn_quote").addEventListener("click", getQuote);
document.getElementById("btn_quote_error").addEventListener("click", getQuoteError);
function getQuote(e){
e.preventDefault();
var ticker = document.getElementById("ticker").value;
var shares = document.getElementById("shares").value;
//var url = "/quote/" + ticker + "/" + shares;
var url = 'http://stackoverflow.com/';
// Fetch the latest data.
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
console.log(request.readyState);
if (request.readyState === XMLHttpRequest.DONE) {
console.log(request.status);
if (request.status === 200) {
//var response = JSON.parse(request.response);
//console.log(response);
}
}
//else {
// TODO, handle error when no data is available.
//console.log('ERROR');
//return false;
//}
};
request.open('GET', url, true);
request.send();
}
function getQuoteError(e){
e.preventDefault();
var ticker = document.getElementById("ticker").value;
var shares = document.getElementById("shares").value;
//var url = "/quote/" + ticker + "/" + shares;
var url = 'http://stackoverflow404.com/';
// Fetch the latest data.
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
console.log(request.readyState);
if (request.readyState === XMLHttpRequest.DONE) {
console.log(request.status);
if (request.status === 200) {
//var response = JSON.parse(request.response);
//console.log(response);
}
}
//else {
// TODO, handle error when no data is available.
//console.log('ERROR');
//return false;
//}
};
request.open('GET', url, true);
request.send();
}
<input type="text" id="ticker"/>
<input type="text" id="shares"/>
<input type="button" id="btn_quote" value="Get Quote" />
<input type="button" id="btn_quote_error" value="Get Quote Error" />

Submit Fields In Table Row Using XMLHttpRequest

I would like to create a object using the row fields(id,title,body) and send using XMLHttpRequest.
See my javascript below.
function callAjax(url, callback) {
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callback(xmlhttp.responseText);
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send();
xmlhttp.send(); //send row (including id(hidden), title(text), body(text)
}
function updated(text) {
alert(111111111);
}
function deleted(text) {
alert(111111111);
}
https://jsfiddle.net/9j7ch3ct
I would usually use $(this).closest('tr').find('#id'), but I don't have the jQuery option unfortunately.
Thanks.
send the post data like this xmlhttp.send(data); data is a string like this id=val1&title=val2....
for getting trs use document.getElementsByTagName loop the array and frame the data send it with send(data) function

Sending Http POST Request through Rest API in Javascript

I am trying to send an Http post request to parse.com server through Rest API keys. Not sure if I am doing it right as below. The following is my whole script and makes a button which should trigger the post request in a simple HTML page.
<input id="clickMe" type="button" value="clickme" onclick="doFunction();" />
<script>
xmlhttp = new XMLHttpRequest();
var url = "https://api.parse.com/1/classes/english";
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.setRequestHeader("X-Parse-Application-Id", "VnxVYV8ndyp6hE7FlPxBdXdhxTCmxX1111111");
xmlhttp.setRequestHeader("X-Parse-REST-API-Key","6QzJ0FRSPIhXbEziFFPs7JvH1l11111111");
xmlhttp.onreadystatechange = function () { //Call a function when the state changes.
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
var parameters = {
"ephrase": "english",
"pphrase": "farsi",
"nvote": 0,
"yvote": 0
};
// Neither was accepted when I set with parameters="username=myname"+"&password=mypass" as the server may not accept that
function doFunction() {
xmlhttp.send(parameters);
}
</script>
xmlhttp.send(parameters);
^^^^^^^^^^
That needs to be a string, but it is an object, so will be converted to the string: "[object Object]".
You need to convert the data to the proper encoding first.
You've said:
xmlhttp.setRequestHeader("Content-type", "application/json");
so you can use JSON.stringify(parameters) for that.

Posting plain text on php using JavaScript

I need to use "POST" consisting of value and a variable structure using JavaScript. The plain text should be sent to a PHP page where it will be displayed. How should I get about this?
From what I understand according to my requirement. It needs to be something like a FROM submission, but run only using JavaScript.
document.body.innerHTML += '<form id="content" action="http://10.10.10.10/index.php" method="post"><input type="hidden" name="info" value="'+plainText+'"></form>';
document.getElementById("content").submit();
I tried this code as well.Do you have an Idea on how to display the text sent here on a PHP page?
var request = new XMLHttpRequest();
request.open("POST", "10.10.10.10/index.php", true);
request.onreadystatechange = function () {
if(request.readyState === 4){
if(request.status === 200 || request.status == 0){
request.setRequestHeader("Content-type","text/plain;charset=UTF-8");
request.setRequestHeader("Content-length", plainText.length);
request.send(plainText);
}
}
}
request.send(null);
You need to use ajax, if you need plain javascript then you should do something like this:
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
var DONE = this.DONE || 4;
if (this.readyState === DONE){
alert(xhr.responseText);
}
};
request.open('POST', 'script.php', true);
request.send("<YOUR TEXT>");
if you use jQuery then simple:
$.post('script.php', '<YOUR TEXT>', function(response) { });
and then you can read it in php using:
file_get_contents('php://input');
or (deprecated):
$GLOBALS['HTTP_RAW_POST_DATA'];

Send Custom HTTP Body with AJAX POST request

How do I send a custom HTTP body with my POST AJAX request in plain Javascript (not JQuery)? I am actually trying to send a JSON file in the body. I can set the custom header fields but can't find how to set HTTP body.
below is the code
function calculateorder() {
document.getElementById("finalize").style.display = "inline";
url1 = "https://ethor-prod.apigee.net/v1/stores/";
url2 = "/orders/calculate?apikey=wSgbv9PE8aJhDOI17vvTUX1NlAceUXG7";
url = url1 + store_id + url2;
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify(calculate));
}
When I used the same headers and JSON file with Rested (a OSX HTTP client) It works perfectly
Add parameter in XmlHttpRequest Obeject's .send() method
Like this:
xhr.send('username=me');
Send JSON Format Data myData Like this:
xhr.send(JSON.stringify(myData));

Categories

Resources