Unable to read custom http headers in javascript onreadystatechange? - javascript

While i am trying to read custom http headers.i am hetting null.
Jersey authentication resource :-
#Path("/redirect")
public class RedirectDemo {
#POST
#Consumes(MediaType. APPLICATION_JSON )
public Response getRedirect(#Context ServletContext context,UserTO user) {
UriBuilder builder = UriBuilder.fromPath(context.getContextPath());
System. out .println("User name is:"+user.getUserName());
System. out .println("Password is:"+user.getPassword());
builder.path("/main.html");
return Response
.status(Response.Status. SEE_OTHER )
.header(HttpHeaders. AUTHORIZATION ,"Response authorize")
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST,
DELETE, PUT")
.header("Access-Control-Expose-
Headers",HttpHeaders. AUTHORIZATION )
.header(HttpHeaders. LOCATION , builder.build())
.build();
}
}
Login – page :-
<! DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<div class="container-test">
<h3>
<strong>iDNS</strong>
</h3>
</div>
<div class="container">
<form class="form-signin" id="loginForm" name="loginForm"
action="/JerseyPageRedirection/redirect/redirect" method="post"
id="login_form">
<div class="errmsg text-center"></div>
<label for="inputEmail">Email address</label> <input
type="email"
id="emailId" class="form-control" name="emailId"<label
type="password"
placeholder="Email address" required autofocus> <br>
for="inputPassword">Password</label> <input
id="password" class="form-control" name="password"
placeholder="Password" required> <br>
<!-- id="login-submit" -->
<button type="button" class="btn btn-lg btn-primary btn-block"
onclick="doLogin()">Sign in</button>
</form>
</div>
<script>
function doLogin() {
var userName = window
.btoa(document.getElementById('emailId').value);
var password = window
.btoa(document.getElementById('password').value);
var formData = JSON.stringify({
userName : userName,
password : password
});
var xhr = new XMLHttpRequest();
xhr.open("POST", "/JerseyPageRedirection/redirect/redirect");
xhr.setRequestHeader("Content-type", "application/json");
xhr.send(formData);
xhr.onreadystatechange = function() {
console.log(xhr.getResponseHeader("Authorization"));//null
window.location.href = xhr.responseURL;//Redirect works
}
}
</script>
</body>
</html>
Headers :-
Issue :-
I am unable read Authorization header content.
I want to read the header value only in javascript. Thanks in advance.

If someone still looking for the answer, you need to set "Access-Control-Expose-Headers" along side with the response. In example :
Access-Control-Expose-Headers: Content-Type,Authorization,X-RateLimit-Limit,X-RateLimit-Remaining,X-RateLimit-Reset

change your callback:
xhr.onreadystatechange = function() {
if(xhr.readyState == 4){//if you are looking only for HTTP 200, then add condition xhr.status == 200
console.log(xhr.getResponseHeader("Authorization"));//will get your response header
window.location.href = xhr.responseURL;//Redirect works
}
}
Note:
readyState Holds the status of the XMLHttpRequest. Changes from 0 to 4:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

Related

AJAX or Javascript POST request for Django form and get the result

I am working on a django based project in which I have integrated ML trained models to check if a https url is legitimate or not. for this I need javascript or ajax to call a rest api for my form in which I want to send a post request so that I can check if a https url is legitimate or not.
NOTE: My code is running successfully and giving correct answers on postman. so just want to integrate it with my HTML form
form.html:
<form role="form" class="form" onsubmit="return false;">
{% csrf_token %}
<div class="form-group">
<label for="data">SITE URL</label>
<textarea id="data" class="form-control" rows="5"></textarea>
</div>
<button id="post" type="button" class="btn btn-primary">POST</button>
</form>
<div id="output" class="container"></div>
<script src="/axios.min.js"></script>
<script>
(function () {
var output = document.getElementById('output');
document.getElementById('post').onclick = function () {
var data = document.getElementById('data').value;
axios.post('http://127.0.0.1:8000/predict/', JSON.parse(data))
.then(function (res) {
output.className = 'container';
output.innerHTML = res.data;
})
.catch(function (err) {
output.className = 'container text-danger';
output.innerHTML = err.message;
});
};
})();
</script>
urls.py:
path('form/', form, name="form"),
path('predict/', predict, name='predict')
here predict/ URL is for my ML model to validate a https URL
ML Model:
I am returning this response:
if list(model.predict([test]))[0] == 1:
return JsonResponse({"Response":"Legitimate"})
else:
return JsonResponse({"Response":"Phishing or fake"})
Below I have provided an example, since you are just looking for a possible solution:
<form role="form" action="{% url 'predict' %}" class="form"
onsubmit="newPrediction(event, this)">
{% csrf_token %}
<div class="form-group">
<label for="data">SITE URL</label>
<textarea id="data" class="form-control" rows="5"></textarea>
</div>
<button id="post" type="button" class="btn btn-primary">POST</button>
</form>
<script>
function newPrediction(e, form) {
e.preventDefault();
const output = document.getElementById('output');
const formData = new FormData(form);
fetch(form.action, {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(html => {
output.innerHTML = html.Response
});
}
</script>
Please comment if you have further questions and I will update this answer.

How can I handle this error : Call to undefined method App\Models\client::findOrFails() and send form data with Js formData object? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have a list of clients with their id. I access to the details of a client with his id in the DB. On the client details page it's possible to update his informations with a modal form.
I'm using JS formData to send the form's informations.
So when sending the informations updated in the form in post to the server I want to reload this client Details page and send the data updated. But I'm getting this error : Call to undefined method App\Models\client::findOrFails() and I'm just getting the crsf_token of the form.
Here is the routes:
Route::get('clients/client_numero/{id}', [ClientDetailsController::class, 'edit_client']);
Route::post('clients/client_numero/{id}', [ClientDetailsController::class, 'update_client']);
The controller :
<?php
namespace App\Http\Controllers;
use App\Models\client;
use Illuminate\Http\Request;
class ClientDetailsController extends Controller
{
//
public function edit_client ($id){
return view('admin.clientDetails', ['client' => client::findOrFail($id)]);
}
public function update_client ($id, Request $request) {
return view ('admin.clientDetails', ['client' => client::findOrFails($id)]);
}
}
The JS code :
// Getting the informations from the form to modify client informations
let modifiyClientInformationsForm = document.getElementById('modifiyClientInformationsForm');
//-----------------------Name----------------------------------
var nameInput = document.getElementById('modifiyClientInformationsForm_name').value ;
//------------------------Prenom------------------------
var prenomInput = document.getElementById('modifiyClientInformationsForm_prenom').value ;
//-----------------------Contact----------------------------
var contactInput = document.getElementById('modifiyClientInformationsForm_contact').value ;
//---------------------------Email------------------------------------
var emailInput = document.getElementById('modifiyClientInformationsForm_email').value ;
//---------------------------Pays------------------------------------
var paysInput = document.getElementById('modifiyClientInformationsForm_pays').value ;
//---------------------------Ville------------------------------------
var villeInput = document.getElementById('modifiyClientInformationsForm_ville').value ;
//----------------------Type----------------------------------------------
var typeInput = document.getElementById('modifiyClientInformationsForm_type').value ;
//-----------------------crsf Token-------------------------------------
var formToken = document.getElementById('modifiyClientInformationsForm_token').value;
//------------------Creating formData object---and---submit form event--------------------------------
modifiyClientInformationsForm.addEventListener('submit' , function(e) {
var action= modifiyClientInformationsForm.getAttribute("action");
e.preventDefault();
var data = new FormData();
data.append( "_token", Laravel.csrfToken );
data.append('_name', nameInput ) ;
data.append('prenom', prenomInput );
data.append('contact', contactInput );
data.append('email', emailInput );
data.append('ville', villeInput );
data.append('pays', paysInput );
data.append('type', typeInput );
const request = new XMLHttpRequest();
request.open('POST', action , true);
request.setRequestHeader("Content-Type", "application/JSON");
request.onreadystatechange = function() {
if (this.readyState == XMLHttpRequest.DONE && this.status == 200) {
console.log(this.responseText);
$ (function(){
alert('Informations submitted');
});
}
};
request.send(data);
});
And the form :
<form class="form-horizontal" method="POST" id="modifiyClientInformationsForm" action="/clients/client_numero/{{ $client ->id }}">
#csrf
<div class="InputAndLabelDiv">
<label for="name" class="InputLabel">Nom :</label>
<input id="modifiyClientInformationsForm_name" type="text" class="MyInput" value="{{$client->name}}">
</div>
<div class="InputAndLabelDiv">
<label for="prenom" class="InputLabel">Prénom(s) :</label>
<input id="modifiyClientInformationsForm_prenom" type="text" class="MyInput" value="{{$client->prénom}}">
</div>
<div class="InputAndLabelDiv">
<label for="contact" class="InputLabel">Contact :</label>
<input id="modifiyClientInformationsForm_contact" type="text" class="MyInput" value="{{$client->contact}}">
</div>
<div class="InputAndLabelDiv">
<label for="email" class="InputLabel">Email :</label>
<input id="modifiyClientInformationsForm_email" type="text" class="MyInput" value="{{$client->email}}">
</div>
<div class="InputAndLabelDiv">
<label for="ville" class="InputLabel">Ville :</label>
<input id="modifiyClientInformationsForm_ville" type="text" class="MyInput" value="{{$client->ville}}">
</div>
<div class="InputAndLabelDiv">
<label for="pays" class="InputLabel">Pays :</label>
<input id="modifiyClientInformationsForm_pays" type="text" class="MyInput" value="{{$client->pays}}">
</div>
<div class="InputAndLabelDiv">
<label for="type" class="InputLabel">Type du client :</label>
<input id="modifiyClientInformationsForm_type" type="text" class="MyInput" value="{{$client->type_du_client}}">
</div>
</div>
<div class="modal-footer">
<button class="btn btn-large MonButon" data-dismiss="modal">Close</button>
<button type="submit" id="modifiyClientInformationsForm_submitButton" class="btn btn-success btn-large Monbuton" > <span class="icon-ok"></span> Enregistrer</button>
</div>
</form>
The method is 'findOrFail' and not 'findOrFails'. This is why you get 'call to undefined method'.

Im new to coding : doing a post request : no errors : but the data is not being sent to my API

My HTML Form: Form from which I'm accessing the data and trying to
send as a POST request to my API
<div id="contactForm">
<h1>Add New Device Here!</h1>
<small>You need to wait for a minute after adding the Device</small>
<form id = "iform" action="http://localhost:8081/ping" method="POST" name="myForm">
<input id = "setrname" name = "fooname" placeholder="Router-Name" type="text" required />
<!-- <input placeholder="Loop-Back" type="text" required /> -->
<input id = "setloopback" name = "foo" placeholder="Loop-Back" type="text" minlength="7" maxlength="15" size="15" pattern="^((\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$">
<select id="Type" name="Router-Type">
<option value="CORE">CORE</option>
<option value="EDGE">EDGE</option>
<option value="IGW">IGW</option>
</select>
<!-- <textarea placeholder="Comment"></textarea> -->
<input value="Submit" class="formBtn" type="submit" onclick="submitform()">
<input class="formBtn" type="reset" />
</form>
</div>
My JavaScript: Sending the HTML form data by JavaScript
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:8081/ping', true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function submitform() {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.flag + ", " + json.status1);
}
};
var insert = {
loop_back: document.getElementById('setrname').value,
status1: 0,
status2: 0,
status3: 0,
status4: 0,
status5: 0,
status: 0,
flag: 0,
rName: document.getElementById('setloopback').value
};
xhr.send(JSON.stringify(insert));
Please help me, suggest me how to correct the above code

How to create a forum with posts and replies for each post

I have a forum page with users' posts. I need to make a reply text area where a user can reply to any post. the problem is whenever a post is replied to, my JS script is unable to detect the specific post that the reply belongs to.
Here is the php snippet that generates a list of the posts and creates a reply form.
echo'
<div id="div'.$post_id.'"></div>
<form name="form'.$post_id.'">'; echo'
<div class="row">
<div class="col-sm-1">
<img src="" width="70" height="70" class="img img-responsive" alt="Your profile picture.">
</div>
<div class="col-sm-4">
<textarea placeholder="Your reply" name="user_reply" class="form-control" maxlength="250" rows="3" required></textarea>
<input type="hidden" name="user_id" value="'.$userId .'">
<input type="hidden" name="time" value="'.$time .'">
<input type="hidden" name="date" value="'.$date .'">
</div>
<div class="col-sm-1">
<button name="data" type="button" onclick="sendReply(\' '.$post_id.' \');">Reply</button>
</div>
</div>
</form>
</div>';
Now here is the JS script that I think should pick the user's reply and send the values to reply.php file
<script>
function sendReply(id){
x='document.form'+id;
post_id = id;
user_id = x.user_id.value;
reply = x.user_reply.value;
date = x.date.value;
time = x.time.value;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("div"+id).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'reply.php?reply='+reply+'&post_id='+post_id+'&user_id='+user_id+'&time='+time+'&date='+date, true);
xmlhttp.send();
}
</script>
Finally here is the error I am getting in the browser console when I click the reply button
(index):121 Uncaught TypeError: Cannot read property 'value' of undefinedsendReply
# (index):121onclick
# VM161:211
This part is the problem:
x='document.form'+id;
post_id = id;
user_id = x.user_id.value;
Here you're creating a variable x that contains a string, but then you try to access it as if it was an object.
Instead, try this:
x = document['form' + id]

Unable to read http header values in javascript

While trying HTTP headers which had i set on server unable to access back on java script.below is my code.Kindly some help me to resolve this.
Jersey :
#Path("/redirect")
public class RedirectDemo {
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response getRedirect(#Context ServletContext context,UserTO user) {
UriBuilder builder = UriBuilder.fromPath(context.getContextPath());
System.out.println("User name is:"+user.getUserName());
System.out.println("Password is:"+user.getPassword());
builder.path("/main.html");
return Response
.status(Response.Status.SEE_OTHER)
.header(HttpHeaders.AUTHORIZATION,"Response authorize")
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
.header("Access-Control-Expose-Headers",HttpHeaders.AUTHORIZATION)
.header(HttpHeaders.LOCATION, builder.build())
.build();
}
}
Java script :
<body>
<div class="container-test">
<h3>
<strong>iDNS</strong>
</h3>
</div>
<div class="container">
<form class="form-signin" id="loginForm" name="loginForm"
action="/JerseyPageRedirection/redirect/redirect" method="post" id="login_form">
<div class="errmsg text-center"></div>
<label for="inputEmail">Email address</label> <input type="email"
id="emailId" class="form-control" name="emailId"
placeholder="Email address" required autofocus> <br> <label
for="inputPassword">Password</label> <input type="password"
id="password" class="form-control" name="password"
placeholder="Password" required> <br>
<!-- id="login-submit" -->
<button type="button" class="btn btn-lg btn-primary btn-block"
onclick="doLogin()">Sign in</button>
</form>
</div>
<script>
function doLogin() {
var userName = window.btoa(document.getElementById('emailId').value);
var password = window.btoa(document.getElementById('password').value);
var formData = JSON.stringify({userName:userName,password:password});
var xhr = new XMLHttpRequest();
xhr.open("POST", "/JerseyPageRedirection/redirect/redirect");
xhr.setRequestHeader("Content-type", "application/json");
xhr.send(formData);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4)
if (xhr.status == 200)
var json_data = xhr.responseText;
window.location.href = xhr.responseURL;
}
}
</script>
</body>
Thanks ,i need to read header values on java script.
See: Accessing the web page's HTTP Headers in JavaScript
This article describes the methods to obtain String representations of all the headers, and a value for a named header: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
DOMString getAllResponseHeaders();
DOMString? getResponseHeader(DOMString header);

Categories

Resources