I'm just doing some tests in my browser to figure out what's going on - everything seems to be working correctly up until this line:
responseJson = JSON.parse(localReq.responseText);
When I evaluate this part: JSON.parse(localReq.responseText); I get the appropriate value. But when I evaluate "responseJson" it gives me an uncaught referenceerror and I can't figure out why.
function login()
{
userName = document.getElementById("_name").value;
password = document.getElementById("_password").value;
data = "userName=" + userName + "&" + "password=" + password;
localReq = new XMLHttpRequest();
localReq.open("POST", "http://universe.tc.uvu.edu/cs2550/assignments/PasswordCheck/check.php", true);
localReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
localReq.send(data);
response = document.getElementById("_login");
if (localReq.status == 200)
{
responseJson = JSON.parse(localReq.responseText);
}
}
You need to use an event listener on your AJAX request to handle the response from the server asynchronously via a callback. By not doing this you are checking for a response code of 200 before the server has responded.
function login(){
userName = "username";
password = "password";
data = "userName=" + userName + "&" + "password=" + password;
localReq = new XMLHttpRequest();
// use an event handler here
localReq.addEventListener("load", function(evt){
if (localReq.status == 200) {
responseJson = JSON.parse(localReq.responseText);
alert("Success: " + localReq.responseText);
} else {
alert("Not Success!= :(");
console.log(localReq);
}
});
localReq.open("POST", "http://universe.tc.uvu.edu/cs2550/assignments/PasswordCheck/check.php", true);
localReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
localReq.send(data);
}
See this jsFiddle: http://jsfiddle.net/wwsj3r4q/
Related
I'm trying to use XMLHttpRequest to get image from a sharepoint library. But failed at the point of converting a weird string like
����JFIFS���E������..
back to image.
I managed to get a URL of my sharepoint files that when i put it in the browser, it will automatically download the image. I have also obtained the accessToken to gain permission to the files.
I tried to use base64 encoder from external script to convert the responseText and failed to display as image. Btw, the window.atob() or window.btoa() doesn't seems to do anything for my responseText.
I am not sure what kind of format i received from the responseText to be dealt with. Because i tried manually converting the image to base64 for testing, which begin like this
/9j/4AAQSkZJRgABAQAAAQABAAD/2wB..
. However, the string i got from using the the base64encoder i found online start like this
/f39/QAQSkZJRgABAQAAAQABAAD9/QBDAAs..
<div><img id="imgplaceholder" alt="place here"/></div>
<script>
var url =...;
var accessToken = ...;
var xhr = new XMLHttpRequest();
xhr.open("GET",url,true);
xhr.setRequestHeader("Accept","application/json; odata=verbose");
xhr.setRequestHeader("Authorization", "Bearer " + accessToken);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
var data = xhr.responseText;
//or var data = base64Encode(data);
document.getElementById("imgplaceholder").src = "data:image/jpeg;base64," + data;
}else{
alert(xhr.status + ":\n " + xhr.responseText);
}
}
</script>
I expect the image to be displayed in the , but nothing happens. I have tried using ajax too, but noting works. Please can someone help me?
I was following this https://sharepoint.stackexchange.com/questions/231251/fetch-and-display-image-from-sharepoint-list-javascript
Hope below script would be helpful for you.
<script type="text/javascript">
function Uint8ToBase64(u8Arr) {
var CHUNK_SIZE = 0x8000; //arbitrary number
var index = 0;
var length = u8Arr.length;
var result = '';
var slice;
while (index < length) {
slice = u8Arr.subarray(index, Math.min(index + CHUNK_SIZE, length));
result += String.fromCharCode.apply(null, slice);
index += CHUNK_SIZE;
}
return btoa(result);
}
$(function () {
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/GetFileByServerRelativeUrl('" + _spPageContextInfo.siteServerRelativeUrl + "/MyDoc/panda.jpg')/openbinarystream";
var xhr = new window.XMLHttpRequest();
xhr.open("GET", url, true);
//Now set response type
xhr.responseType = 'arraybuffer';
xhr.addEventListener('load', function () {
if (xhr.status === 200) {
var sampleBytes = new Uint8Array(xhr.response);
var imageBase64 = Uint8ToBase64(sampleBytes);
document.getElementById("imgplaceholder").src = "data:image/jpeg;base64," + imageBase64;
}
})
xhr.send();
})
</script>
<div><img id="imgplaceholder" alt="place here" /></div>
My first post here.
I'm using droidscript and I have to include an header that contains a specific user and a password in order to retrieve a token. I'm having trouble because I don't know where to include those headers.
That's the code I'm using:
function btn_OnTouch(){
var url = "myurl";
SendRequest(url);
}
//Send an http get request.
function SendRequest(url){
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
HandleReply(httpRequest);
};
httpRequest.open("GET", url, true);
httpRequest.send(null);
app.ShowProgress("Loading...");
}
//Handle the servers reply (a json object).
function HandleReply(httpRequest){
if (httpRequest.readyState == 4){
//If we got a valid response.
if (httpRequest.status == 200){
txt.SetText("Response: " + httpRequest.status + httpRequest.responseText);
}
//An error occurred
else
txt.SetText("Error: " + httpRequest.status + httpRequest.responseText);
}
app.HideProgress();
}
The told me I should probably include the headers like this, but I don't know where to put them in my code.
httpRequest.setRequestHeader(“username”, “myuser”);
httpRequest.setRequestHeader(“password”, “mypass”);
You need to do it just after calling the open method like this:-
httpRequest.open("GET", url, true);
httpRequest.setRequestHeader("username", "myuser");
httpRequest.setRequestHeader("password", "mypass");
httpRequest.send(null);
I am trying to use Ajax to validate a username and password stored in a php document on a server. The usernames and passwords are pre stored in the document.
On my HTML page is a field for the username, and a field for the password. Then, when they click the Log-In button it calls the following function:
function checkLogin() {
var user = document.getElementById("username").value;
var password = document.getElementById("password").value;
var data = "userName=" + user + "&password=" + password;
var request = new XMLHttpRequest();
request.open("POST", "check.php", false);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.send(data);
if (request.status === 200) {
window.open("test.html");
} else {
var messageSpan = document.getElementById("response");
var responseJson = JSON.parse(request.responseText);
messageSpan.innerHTML = "Your password of " + responseJson["password"] + " was not corerct. Please try again.";
}
}
The problem I'm having is that it never gets to the else if the username/password are incorrect. Even if there's nothing in the fields, it opens the new page. What am I doing wrong for it to think that all data is correct?
NOTE: The above code is for testing purposes only, and won't actually be used when publishing the web page. I just want to see what's happening and get it to work before moving on. Thanks.
Most likely your check.php echos out true or false on response in some cases you echo out user ID on success. Anyways, your response code is 200 for successful server communication. Examine request.responseText in case of getting 200.
if (request.readyState == 4 && request.status === 200) {
var responseJson = JSON.parse(request.responseText);
if (responseJson['success'] == 1){
window.open("test.html");
} else {
var messageSpan = document.getElementById("response");
messageSpan.innerHTML = "Your username and password combination was incorrect.";
}} else {
//For debugging purpose add an alert message here. alert(request.status);
messageSpan.innerHTML = "A server connection error occurred!"; }
It's noticeable that you are sending back json response. So you may add a node called success whith value of true or false to examine logged in success. It's not a good practice to show password in response message though.
Well the problem is you are getting status 200 from your check.php every time.
In your check.php you need to do some thing like
// let validate() be function that validates your username/password
// and returns true/false on validation
if(validate()){
http_response_code(200);
} else {
http_response_code(401);
}
hope it helps
simply you can use ajax like this,
<script>
function checkLogin() {
var user = document.getElementById("username").value;
var password = document.getElementById("password").value;
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
//progress
xhr.upload.addEventListener("progress", function(e) {
//progress value e
}, false);
return xhr;
},
type: "POST",
url: "check.php",
data: {'userName' : user , 'password' : password},
dataType:json,
success: function(msg) {
//when success //200 ok
if(msg.status=="done"){
window.open("test.html");
}else{
var messageSpan = document.getElementById("response");
messageSpan.innerHTML = "Your password of " + msg.password+ " was incorrect.";
}
},
error: function(jqXHR, textStatus, errorThrown) {
//when error
}
});
}
</script>
your php server side like this,
//$status="fail" or "done"
//success must be always success
$respond=array("success"=>"success","status"=>$status,"password"=>$password);
echo json_encode($respond);
exit;
I think this useful for you !
I can't seem to receive Javascript's HTTPRequest. I get this HTTP/1.1 200 OK
but I cannot seem to get the URL that I sent over. I just want the link that I am sending over on my webpage.
Here is my javascript:
jQuery(function($) {$("button").click(function(){
console.log(this.id);
document.getElementById("direction").innerHTML = this.id + " is pressed.";
newurl = 'index.php?btn='+ this.id+"?key="+user.key;
sendHttpRequest(newurl);
});
});
function sendHttpRequest(update){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
}
}
xhttp.open("GET",update,true);
xhttp.send(null);
console.log(update);
}
ESP8266 in void loop:
WiFiClient client;
String url = "/index.php?";
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
Serial.println("Request Sent");
String request = client.readStringUntil('\r');
Serial.println("headers received");
Serial.println(request);
You're only reading the first line of the response from the index.php script on the ESP, which will generally be the HTTP status code you are seeing, and nothing else (Unless there's some other code you haven't posted). You need to read the entire HTTP message to get the response, specifically the body - Assuming index.php uses the body to return the data you need. You can find a description of the HTTP message structure here: https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html
function submitLogin(){
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
var testlabel = document.getElementById('testlabel').value;
var postStr = "username=" + username + "&password=" + password + "&testlabel=" + testlabel;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('mainPage').innerHTML = xmlhttp.responseText;//ATTENTION1
} else {
document.getElementById('mainPage').innerHTML = "Logining......";//ATTENTION2
}
}
xmlhttp.open("POST", "loginto.php", true);
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttp.send(postStr);
}
These are my codes.
If I change the "mainPage" into something else in the //ATTENTION2, the page will auto send a "GET" method, but if I still use the "mainPage" in there, there will be no problem.
However, if I change the "mainPage" into something else in the //ATTENTION1, there will have no problem with the post method, the response things can be shown in the correctly.
So, is there any solution? Thanks!
What does "something else" mean ? You need to have an id of an element in your page, where the content from the ajax response will be rendered.
For example, if you have a
<div id="myID"></div>
somewhere in the page, and change 'mainPage' in //ATTENTION1 to 'myID', then the response from the ajax request will be placed in that div.
The change you make in //ATTENTION2 is for intermediary states because it is on "else", so will not impact what happens when the ajax request is complete.