transfer to a different url from xmlhttprequest post call - javascript

I am having a xmlhttprequest method like this which gets data authenticated from google sign-in successfully and after that I need to post the data to the login view. Using python and django on the server side.
<form name="Login" method="POST" id="loginForm" action="/login">
function onSignIn(googleUser) {
// Useful data for your client-side scripts:
var profile = googleUser.getBasicProfile();
console.log("ID: " + profile.getId());
console.log('Full Name: ' + profile.getName());
console.log('Given Name: ' + profile.getGivenName());
console.log('Family Name: ' + profile.getFamilyName());
console.log("Image URL: " + profile.getImageUrl());
console.log("Email: " + profile.getEmail());
var id_token = googleUser.getAuthResponse().id_token;
console.log("ID Token: " + id_token);
alert("Token*"+id_token); //this gets executed
var xhr = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhr.open('POST', '/login');
xhr.setRequestHeader("X-CSRFToken", '{{ csrf_token }}');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
console.log('Signed in as: ' + xhr.responseText);
alert("*******Token*"+id_token)
try
{
xhr.send('idtoken=' + id_token);
}
catch (e)
{
alert("*"+e.toString)
console.log('send() error: ' + e.toString());
return false;
}
views.py
in the views i have defined a login method()
def login(request):
if request.method=='POST':
#process the request and send the data to another page with some additonal parameters
role=user_role
email=user_email
fullname=user_name
return render(request, 'ba/dashboard.html', {'role':role,'email':email,'fullname':fullname})
After the post request is completed the page does not get transferred to the dashboard.html page, it stays on the same login page only. I want it to be transferred to the dashboard.html page with the parameters given.
This is the console output no GET request passed after post is completed
[09/Feb/2021 15:53:05] "POST /login HTTP/1.1" 200 4742
Can anyone please tell me how to achieve this? Thanks

This is working for transferring to the different url i had to add this single line
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
**window.location.href="/home"** //I had hoped is there any other way to achieve without using this
}
for passing the parameters i did this from the post method and got in the onreadystatechange as shown above:
return HttpResponse(
json.dumps({'role':user_role,'email':user_email,'fullname':user_name})
)

Related

How to obtain the body response in the client-side?

I am new in web, I am serving an html when a button is clicked on the client side through a request, the body response of that request is the html. How can I retrieve the html or body response from the client side?
I am trying with this code but everything is empty:
var xhr = new XMLHttpRequest();
xhr.open(signedRequest.method, signedRequest.url, true);
console.log('xhr.response: ', xhr.response);
console.log('xhr.responseText: ', xhr.responseText);
console.log('xhr.responseXML: ', xhr.responseXML);
document.write('<p>xhr: ' + xhr + '</p>');
xhr.send();
Any idea on how to obtain the body response in the client-side?
Try to add a div or any input element with the id "demo" and try to run the code below.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = "<strong>The response from the test URL is: </strong>" + this.responseText;
console.log(JSON.parse(this.response));
}
};
xhttp.open("GET", "https://httpbin.org/get", true);
xhttp.send();
<div id="demo"></div>

AJAX returns status code 0? CORS allowed. Is this AJAX implemented incorrectly?

I have a browser action I've implemented it as an AddOn.
I'm testing my construction of the AddOn within my domain
between two machines as server and a client.
I'm stuck at AJAX failing with status code 0.
I set up Apache to enable CORS to make sure that the code is behaving as expected.
I added this line to the apache config and enabled headers:
Header set Access-Control-Allow-Origin "*"
The javascript code: UPDATED
function sendData(data){
var requestdata = 'data1=one&data2=two&data3=three';
var xhr = new XMLHttpRequest();
xhr.open("POST","http://server/test/test.php");
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.onloadstart = function(){
console.log("Onload status: " + xhr.status);
}
xhr.onerror = function(ev) {
console.log("OnError Status: " + xhr.status + ", Loaded: " + ev.loaded + ", Total: " + ev.total);
}
xhr.onreadystatechange = function() {
console.log(xhr.status);
if (xhr.status !== 200){
console.log("Failure :( + Status: " + xhr.status);
//console.log(requestdata);
console.log("Ready State: " + xhr.readyState + ", Status: " + xhr.status +", Response Text: " + xhr.responseText);
} else {
alert("Success!");
}
}
xhr.send(requestdata);
}
test.php
<?php
require '../lib/Database.php';
error_reporting(E_ALL);
$db = new Database('test');
var_dump($db);
json_encode($_POST);
?>
Have I done this AJAX implementation correctly?
If I have, and I have made adjustments for CORS, why is it failing with status code 0?
UPDATE
This is an AddOn I am testing in Firefox.
From the "matches" parameter in manifest.json, navigating to the page in question retrieves data from the page using Vanilla JS on the DOM.
The collected data is held in an object.
The data object is delivered
This is a picture of what's returned in the browser:
UPDATE2
I replaced the POST url with http://httpbin.org/post to see if the data is going anywhere. Nope.

Asmx webservice Xmlhttprequest content-type

I have a piece of javascript code for accessing a asmx webservice
var xml = 'xml=<Webservice><Parameters><Parameter name="PARTCODE" value="WSA10029" /></Parameters></Webservice>';
try {
xhr = new XMLHttpRequest();
xhr.open('POST', url, false);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
};
xhr.send(xml);
} catch (e) {
alert('Error occured in XMLHttpRequest: ' + xhr.statusText + ' ReadyState: ' + xhr.readyState + ' Status:' + xhr.status);
}
The webservice receives the request but the parameter xml is empty at the webservice side. i've tried many different Content-Types but none of them work.
Data data I want to send is xml, therefor I htmlencoded the xml.

How can i change the url path when i receive the response of (xhr.response) to charge the page

newxhr.open("GET","/connected", true);
newxhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
newxhr.setRequestHeader('Authorization', 'Bearer ' + JSON.parse(localStorage.getItem('token')));
newxhr.onreadystatechange = function() {
if(newxhr.readyState == XMLHttpRequest.DONE && newxhr.status == 200){
//The problem is here
window.location.href="/home";
}
}
The actual location is '/connexion' the post worked and i get the token from the server so i did the GET to '/home' but it still in the same page :notice '/home is a protected route' can't get it without a token,

Javascript getting response value after post

I'm triying to post web service. But i want to get response value.
My code is shown below:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'http://www.w3schools.com/webservices/tempconvert.asmx', true);
// build SOAP request
var sr =
'<soapenv:Envelope' + ' ' +
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
'xmlns:api="http://127.0.0.1/Integrics/Enswitch/API" ' +
'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' +
'xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">' +
'<soapenv:Body>' +
'<CelsiusToFahrenheit xmlns="http://tempuri.org/">' +
'<Celsius>44</Celsius>' +
'</CelsiusToFahrenheit>'+
'</soapenv:Body>' +
'</soapenv:Envelope>';
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert('done use firebug to see response');
}
}
}
// Send the POST request
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send(sr);
When i look in firebug, i realized web server response value is:
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><CelsiusToFahrenheitResponse xmlns="http://tempuri.org/"><CelsiusToFahrenheitResult>111.2</CelsiusToFahrenheitResult> </CelsiusToFahrenheitResponse></soap:Body></soap:Envelope>
But i dont know how can i get
111.2 value?
You are getting an xml response from your ajax call. Do do it correctly, you need to parse the xml code.
You can do easily it with jQuery:
var r = $(this.responseText).find("CelsiusToFahrenheitResult").text();

Categories