Maintaining authentication using API and xhr - javascript

I'm getting to grips with using an API to display the data on a page refresh. SO the first part is to authenticate using form based authentication. So I have this:
<html>
<head>
<script type="text/javascript">
function CallWebAPI()
{
var request = new XMLHttpRequest(), data = 'username=admin&password=admin';
request.open('POST', 'https://localIP:8443/api/users/_login', true)
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
request.setRequestHeader("Accept", "application/xml")
request.onreadystatechange = function()
{
// D some business logics here if you receive return
//if(request.readyState === 4 && request.status === 200) {
console.log(request.responseText);
//}
}
request.send(data);
}
</script>
</head>
<body>
<div>
<div id="response">
</div>
<input type="button" class="btn btn-primary" value="Call Web API" onclick="javascript:CallWebAPI();" />
</body>
</html>
So from the above, in the console browser I return a proper authentication message as thus:
SUCCESS
So I want to run another function to retrieve data now I'm logged in but it seems to reset back to 'unauthorised. All I did was create another function exactly the same except it was a GET rather than POST and added another button to test it. But it just kept returning 401: unauthorised. Am I doing it in the incorrect order or something?
I insert a second function like this:
function getChannelStats()
{
var stats = new XMLHttpRequest();
stats.open('GET', 'https://localIP:8443/api/channels/statistics?channelId=f237ae66-6c5b-4ffa-9396-0721eb575184', true)
stats.setRequestHeader("Accept", "application/xml")
stats.onreadystatechange = function()
{
// D some business logics here if you receive return
//if(request.readyState === 4 && request.status === 200) {
console.log(stats.responseText);
//}
}
stats.send();
}
request.send(data);
}
And add another button that class that function to get the responseText. I'm expecting an xml message with various numbers in it. But when I try to run it, it asks for me to authenticate - like it's not retaining it?

Related

How to send an API get request using JavaScript with HTML variables

I am trying to make a GET request to a web API using what is inputted in a textbox. So far I have the input value established but can't seem to figure out to send the request.
const inputdata = document.getElementById('request');
const requestdata = inputdata.value;
console.log(requestdata);
This function correctly but I can't seem to figure out the rest.
I am trying to do the following:
https://api.example.com/request?=${requestdata}
or
https://api.example.com/request/${requestdata}/test
Keep in mind that this is a static HTML site with no Node
Something like this should work to make an asynchronous GET request:
function httpGetAsync(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true);
xmlHttp.send(null);
}
const inputdata = document.getElementById('request');
const requestdata = inputdata.value;
httpGetAsync("https://api.example.com/request?=${" + requestdata + "}");
<input type="text" id="request" value="test">
If you check the developer tools > network tab you should see the GET request to the API endpoint.

AJAX and PHP sending "HTTP get request" to the same page

My application gathers some client related information via JavaScript and submits it via AJAX to a php page.
See the code below:
index.php
<html>
<head>
<script>
function postClientData(){
var client_data = new Array(screen.availHeight, screen.availWidth);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if(this.responseText == client_data[0]){
document.getElementById("message").innerHTML = "Client data successfully submitted!";
}
}
};
var parameters = "ajax.php?screen_height=" + client_data[0] + "&screen_width=" + client_data[1];
xmlhttp.open("GET", parameters, true);
xmlhttp.send();
}
</script>
</head>
<body onload="postClientData()">
<span id="message"></span></p>
</body>
</html>
ajax.php
<?php
echo $_REQUEST["screen_height"];
//Does something else...
?>
I was wondering if I could merge the ajax.php content to my index.php and eliminate ajax.php. When I try adding the code, I probably get into a endless loop since I don't get my "success" message.
How can I solve this issue?
Correct, IMO I would definitely keep this specific logic separated in the ajax.php file.
If you do really want to merge, add it to the top of index.php (before printing data):
if (isset($_GET['screen_height'])) && isset($_GET['screen_width']) {
// Execute specific logic and exit to prevent sending the HTML.
exit;
}

Laravel 4 javascript ajax request

I performed and Ajax request when a button is being clicked, to make a get request and update a div,but my page doesn't seem to update at all.but using the debugging tools i realised that:
it gives error: Cannot set property 'innerHTML' of null
But when i save my xmlhttp.responseText to a variable and i alert it alert this:
<div>
This is a new Ajax Message !! Thanks
</div>
which is the content of msg.blage.php that am requesting for.Though am new to using ajax and laravel.
Below here is the code:
register.blade.php
<button id="btn" onclick="makerequest('{{route('msg')}}','succesMessage')">Update!!</button>
<div id="successMessage"></div>
msg.blade.php
<div>
This is a new Ajax Message !! Thanks
</div>
script.js
function makerequest(serverPage, objID) {
var obj = document.getElementById(objID);
xmlhttp.open("GET", serverPage);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var data = xmlhttp.responseText;
alert(data);
obj.innerHTML=data;
}
}
xmlhttp.send(null);
}
routes.js
Route::get('/msg',['as' => 'msg', 'uses' => 'HomeController#msg']);
HomeContoller.php
public function msg()
{
return View::make('msg');
}
The error shows on line "sortable.js:14";
and that i think is the second each()
<button id="btn" onclick="makerequest('{{route('msg')}}','succesMessage')">Update!!</button>
<div id="successMessage"></div>
You have a typo in the first line, succesMessage instead of successMessage. It's trying and failing to find an element with the ID succesMessage as a result.

I can't send PHP variables to JavaScript

I'm trying to send parametres from a .php file to my Javascript but I can't even manage to send a String.
Javascript fragment:
var params = "action=getAlbums";
var request = new XMLHttpRequest();
request.open("POST", PHP CODE URL, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.send(params);
request.onreadystatechange = function() {
var phpmessage = request.responseText;
alert(phpmessage);
};
PHP fragment:
$deviceFunction = $_POST["action"];
if ($deviceFunction == "") $deviceFunction = $_GET["action"];
// Go to a function depending the action required
switch ($deviceFunction)
{
case "getAlbums":
getAlbumsFromDB();
break;
}
function getAlbumsFromDB()
{
echo "test message!";
}
The alert containing phpmessage pops up but it's empty (it actually appears twice). If I do this the alert won't even work:
request.onreadystatechange = function() {
if(request.status == 200) {
var phpmessage = request.responseText;
alert(phpmessage);
}
};
The readystatenchange event will be called each time the state changes. There are 5 states, see here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#readyState
Rewrite your JS:
request.onreadystatechange = function () {
if (request.readyState == 4) {
console.log('AJAX finished, got ' + request.status + ' status code');
console.log('Response text is: ' + request.responseText);
}
}
In your code, you only check for the returned status code. The code above will check for the ready state and then output the status code for debbuging.
I know that this answer is more a comment than an answer to the actual question, but I felt writing an answer in order to include nicely formatted code.
I faced a similar problem working with Django. What I did:
I used a template language to generate the javascript variables I needed.
I'm not a PHP programmer but I'm going to give you the idea, let me now if works. The following isn't php code, is just for ilustrate.
<?php
<script type="text/javascript" ... >
SOME_VARIABLE = "{0}".format(php_function()) // php_function resolve the value you need
</script>
?>
The I use SOME_VARIABLE in my scripts.
Please specify your onreadystatechange event handler before calling open and send methods.
You also should make your choice between GET and POST method for your request.
If you want to popup your message only when your request object status is OK (=200) and readyState is finished whith the response ready (=4), you can write :
request.onreadystatechange = function() {
if (request.readyState==4 && request.status==200) {
var phpMessage = request.responseText;
alert(phpMessage);
}
};

XMLHttpRequest connection check

I am trying to write a streamlined version of a XMLHttpRequest demo script shown here:
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first
I'm only going to use this on iPad, so I don't have to check for older versions of IE, and so on. On button click, I want to check if the connection exists. Here's my entire html page, including JavaScript snippet:
<html>
<head>
<script>
var myURL = "http://www.google.com";
function testConnection(url) {
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert("Connected!");
} else {
alert("Not connected!");
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
</script>
</head>
<body>
<button type="button" onclick="testConnection(myURL)">Test Connection</button>
</body>
</html>
For some weird reason, even though I'm online, when I click the button, I get repeated "Not connected" alerts, and only after a while I get the "Connected" alert, followed by no alerts.
Looks like I messed up, but I can't see where. What should I change to make it work?
If you can use xhr2, you can learn stuff from this tutorial and rewrite your code to something like this:
function testConnection(url) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() { alert("Connected!"); }
xmlhttp.onerror = function() { alert("Not Connected"); }
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
If you send request to another domain, you may get error even if it exists, if the target server has Same-Domain-Policy restriction (default). If the target server is on another domain, it must send header
Access-Control-Allow-Origin: *

Categories

Resources