Unable to read http header values in javascript - 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);

Related

Shopify API request

I am trying to access the Shopify backend to update a customer's email, phone, and name using vanilla JS. the request is returning successfully but the actual values are not changed.
created a custom app for my store and followed the documentation to get access to api for shopify
HTML:
<div class="container with_background">
<form action="" method="" id="updateCustomerForm" class="page-width">
<div class="input-wrapper form-row --100">
<label for="AddressFirstName">First Name</label>
<input type="text" name="address[id]" id="customerId" value="{{customer.id}}" autocapitalize="words" disabled style="display:none;">
<input type="text" name="address[first_name]" id="customerFirstName" value="{{customer.first_name}}" autocapitalize="words">
</div>
<div class="input-wrapper form-row --100">
<label for="AddressLastName">Last Name</label>
<input type="text" name="address[Last_name]" id="customerLarstName" value="{{customer.last_name}}" autocapitalize="words">
</div>
<div class="input-wrapper form-row --100">
<label for="AddressEmail">Email Address</label>
<input type="email" name="address[Email_address]" id="customerEmail" value="{{customer.email}}" autocapitalize="words">
</div>
<div class="input-wrapper form-row --100">
<label for="AddressPhone">Mobile Number</label>
<input type="tel" name="address[Phone]" id="customerPhone" value="{{customer.phone}}">
</div>
<button type="submit" id="saveCustomerToggle" class="btn btn--logout tablinks">Save</button>
</form>
</div>
JS:
document.getElementById("updateCustomerForm").addEventListener("submit", function(e){
e.preventDefault();
e.stopPropagation();
let custID = document.getElementById("customerId").value ;
let custFN = document.getElementById("customerFirstName").value ;
let custLN = document.getElementById("customerLarstName").value ;
let custEM = document.getElementById("customerEmail").value ;
let custPH = document.getElementById("customerPhone").value ;
console.log(custFN);
let customerdata = {
"customer": {
"customer.id": custID,
"customer.first_name": custFN ,
"customer.last_name": custLN,
"customer.email": custEM,
"customer.phone": custPH,
}
};
console.table(customerdata);
let formData = new FormData(document.getElementById("updateCustomerForm"));
console.log(formData);
const xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('PUT', "https://{api_key}:{api_password}#{store}.myshopify.com/admin/api/2022-04/customers/" + {{customer.id}} +".json", true);
xhr.setRequestHeader("Content-type", "application/json")
xhr.send(JSON.stringify(customerdata));
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr);
console.log("1");
console.log(formData);
console.table(customerdata);
} else {
console.log(xhr);
console.log("2");
console.log(formData);
}
} else {
console.log(xhr);
console.log("3");
console.log(formData);
}
};
any idea why it's returning true but it's not taking action for the actual values?

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

xhttp.send() get error POST 500 (Internal Server Error)

when trying to send the data to the server the error POST 500(internal server Error ) display
here is my form
<form class="input-group" id="f">
<div class="form" style="display :-webkit-inline-box;">
<input type="text" class="form-control" name="comment" placeholder=" Comment ">
<span class="input-group-btn">
{{--<input class="btn btn-default" type="button" onclick="loadDoc()" value="Comment!">!--}}
<input class="btn btn-default" type="button" onclick="loadDoc()" value="Comment!">
</span>
</div>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form><!-- /input-group -->
and this is the javascript code
function loadDoc() {
var dd = document.getElementById('f');
var d = [];
r=0;
for (var i = 0; i < dd.elements.length; i++){
if(dd[i].type == "text") {
d[r] = dd[i].value;
r++;
}
}
var xhttp = new XMLHttpRequest();
var url = "/place/{{$place->id}}";
var params = "data="+d;
xhttp.open("POST", url , true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.response);
console.log(json);
}
};
xhttp.send(params);
}
i am trying to make a comment
If you don't plan to use CSRF Token, than go to the
App/Http/Kernel.php
And delete or comment line
\App\Http\Middleware\VerifyCsrfToken::class
And your profilem is solved... otherwise add _token param in that xhttp request...

Unable to read custom http headers in javascript onreadystatechange?

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

Categories

Resources