XmlHttp request doesn't retrieve values [duplicate] - ajax

This question already has answers here:
How to make a GET Request in XMLHttpRequest?
(3 answers)
Closed 4 months ago.
I have an AJAX login request that calls a PHP File which processes the request data and echo if the login is successful or not. The JS script doesn't receive any values from the request
Here is the code:
document.getElementById("Login-Accedi-Btn").addEventListener("click", (event) => {
var xmlHttp = new XMLHttpRequest();
loginusernameinput = document.getElementById("Login-Username-Input").value;
loginpasswordinput = document.getElementById("Login-Password-Input").value;
if (loginusernameinput == "" || loginpasswordinput == "") {
loginerror("Errore: Username o Password vuoti");
}
xmlHttp.open("GET", "logincheckajax.php?user=" + loginusernameinput + "&password=" + loginpasswordinput, true);
xmlHttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
loginstatus = xmlHttp.responseText;
if (loginstatus == "Corretto") {
window.reload;
} else {
if (loginstatus = "SbagliatoUserOPassword") {
loginerror("Errore: Username o Password non corrispondenti")
} else {
if (loginstatus = "UsernameOPasswordNonSettati") {
loginerror("Errore: Username o Password non rilevati nell'autenticazione");
} else {
loginerror("Errore non definito");
}
}
}
}
}
})

You must call send to actually send the request.
You might want to look into the newer fetch API as it can be simpler to set up and use.

Related

What is XMLHttpRequest's life cycle? When will the XMLHttpRequest be destroyed?

When is XMLHttpRequest destroyed?
I just wrote the simple function below, and xmlhttp has been sent successfully, but responseText isn't sent to the function SetStringinDiv(). The variable str is empty and the variable location has value.
I have no idea how to fix it, and I don't know what the keyword for this problem is, either. If this kind of question already exists, please tell me how to find it or what the keyword is.
<script>
function foo(){
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var str = xmlhttp.responseText;
SetStringinDiv("div1", str);
}
}
xmlhttp.open("GET", "uri", true);
xmlhttp.send();
}
</script>
<script>
function SetStringinDiv(location, str) {
document.getElementById("location").innerHTML = location;
document.getElementById("str").innerHTML = str;
if (document.getElementByID(location) == null) {
document.getElementById("error").innerHTML += ">> error, can not find the div, "
+ location + "\n";
}
document.getElementByID(location).innerHTML = str;
}
</script>
Check for xmlhttp.status != 200 and print out an error. Print out the readystate and status on each call to onreadystatechange. I think you will see an error message in statusText.
These days it is recommended to not use the onreadystatechange callback. I use the code below. Note that if the server does not respond and does not close the connection that your request won't timeout for quite some time (2-5 minutes) - either in your code or that below. If it is sitting there, shut down the server. You will get an immediate error response then.
var req = new XMLHttpRequest(),
done = function(response) {
callback(cache[uri.split('/').pop()] = cache[uri] = response);
};
req.open("GET", uri + ".lispz", true);
req.onerror = function(err) {
done({
uri: uri,
error: err
});
}
req.onload = function() {
return (req.status != 200) ? req.onerror(req.statusText) : done(run(req.responseText));
};
req.send();

AJAX XMLHttpRequest state undefined

In the following piece of JavaScript code, i'm executing GetData.php using AJAX. However, when i remove the comments to see the request object's state property, it turns up as undefined, although the PHP script is getting executed properly and my page is changing as i want it to. But i still need the state property. Any clue on what's going on here ?
function refreshPage()
{
var curr = document.getElementById('list').value;
var opts = document.getElementById('list').options;
for(var i=0;i<opts.length;i++)
document.getElementById('list').remove(opts[i]);
var request = new XMLHttpRequest();
request.onreadystatechange=
function()
{
if(request.readyState == 4)
{
//alert(request.state);
//if(request.state == 200)
{
fillOptions();
var exists = checkOption(curr);
var opts = document.getElementById('list').options;
if(exists == true)
{
for(var i=0;i<opts.length;i++)
if(curr == opts[i])
{
opts[i].selected = true;
break;
}
}
else
{
opts[0].selected = true;
}
refreshData();
}
/*else
{
alert(request.responseText);
//document.close();
}*/
}
}
request.open("GET","GetData.php?Address=" + address + "&Port=" + port,true);
request.send();
}
Do you mean request.status not request.state?
Try changing it to the .status and it should work just fine :)

django with ssl redirect and ajax post gives a 301 error

I am using this django snippet [1] to redirect to my https website. I know it does not work with POST requests so I did not add the {'SSL': True } in the all the url POST requests in my urls.py. However I always get a 301 error (in my access logs), although the view does what it is asked to do.
The view is 'called' by an ajax request and returns a json object.
def confirm(request, username):
if username == request.user.username:
user = get_object_or_404(User, username=username)
if request.method == 'POST':
response_dict = {
'status': True,
'added_total': count,
'username': username,
'message': message
}
return HttpResponse(simplejson.dumps(response_dict), mimetype='application/javascript')
else:
return HttpResponseRedirect('/fx/%s?page=%s' % (username, '1'))
else:
raise Http404(u'Not a valid user')
I also tried to add the {'SSL': True} argument but I still get the 301 error.
for ajax post requests I also use this snippet:
$.ajaxSetup({
beforeSend:function (xhr, settings) {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != "") {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
What am I doing wrong?
EDIT: This is my action from urls.py
url(r'^confirm/(\w+)/$', confirm),
[1] http://djangosnippets.org/snippets/85/

AJAX to submit to page using POST method

I have this piece of AJAX that validates the login credentials by sending the username and password via GET method. I want to update this code to use POST method, but I don't know where to start or what to change.
The reason I'm doing this is the data that will be sent to another page will be big and GET doesn't send it all.
This is the code I have:
function createObject()
{
var request_type;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer")
{
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
request_type = new XMLHttpRequest();
}
return request_type;
}
var http = createObject();
var usr;
var psw;
function login()
{
usr = encodeURI(document.getElementById('username').value);
psw = encodeURI(document.getElementById('password').value);
http.open('get', 'login.php?user='+usr+'&psw='+psw);
http.onreadystatechange = loginReply;
http.send(null);
}
function loginReply()
{
if(http.readyState == 4)
{
var response = http.responseText;
if(response == 0)
{
alert('Login failed! Verify user and password');
}
else
{
alert('Welcome ' + usr);
document.forms["doSubmit"].elements["usr"].name = "usr";
document.forms["doSubmit"].elements["usr"].value = usr;
document.forms["doSubmit"].elements["pwd"].name = "pwd";
document.forms["doSubmit"].elements["pwd"].value = psw;
document.forms["doSubmit"].action = location.pathname + "user/";
document.forms["doSubmit"].submit();
}
}
}
This code uses GET and send the parameters in the URL and waits for the reply. I want to send the parameters via POST due to size.
The data that will be sent is for a <textarea name='taData' id='taData'></textarea>
Change the line of code as described below:
From:
http.open('get', 'login.php?user='+usr+'&psw='+psw);
To:
http.open('post', 'login.php');
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
http.send('user=' + usr + '&psw=' + psw + '&tboxName=' + yourTextBoxValue);
More on the topic:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms757849(v=vs.85).aspx

Control flow with XmlHttpRequest?

XmlHttpRequest works through callbacks. So how can I return a value? I tried to set a global variable, but that doesn't seem to be working.
var response = null; // contains the most recent XmlHttpRequest response
// loads the info for this username on the page
function loadUsernameInfo(username) {
getUserInfo(username);
var profile = response;
if (profile) {
// do stuff
}
else {
indicateInvalidUsername(username);
}
}
getUserInfo() can't return a result, because of the callback:
function getUserInfo(username) {
var request = createRequest();
request.onreadystatechange = userObjFromJSON;
var twitterURL = "http://twitter.com/users/show/" + escape(username) + ".json";
var url = "url.php?url=" + twitterURL;
request.open("GET", url, true);
request.send(null);
}
The callback:
function userObjFromJSON() {
if (this.readyState == 4) {
alert(this.responseText);
response = this.responseText;
}
}
How can I get the response back to loadUsernameInfo()?
You can do synchronous requests, though it is not recommended - the A is for Asynchronous... But the general idea to implement this correctly would be:
var response = null; // contains the most recent XmlHttpRequest response
// loads the info for this username on the page
function loadUsernameInfo(username) {
getUserInfo(username, onLoadUsernameComplete);
}
function getUserInfo(username, oncomplete) {
var request = createRequest();
request.__username = username;
request.onreadystatechange = oncomplete;
var twitterURL = "http://twitter.com/users/show/" + escape(username) + ".json";
var url = "url.php?url=" + twitterURL;
request.open("GET", url, true);
request.send(null);
}
function onLoadUsernameComplete(req) {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
var profile = req.responseXML;
if (profile) {
// do stuff
}
else {
indicateInvalidUsername(req.__username);
}
}
}
}

Resources