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

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...

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?

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

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

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);

How to trigger AJAX from a search button

I have the following Javascript:
<script>
function showtickets(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "/processes/editticket.php?WTNum=" + str, true);
xmlhttp.send();
}
It works perfectly if I use a selectbox and trigger the function with "onchange". However, my client requested a searchbox instead. I cannot get it to work with a search box. Here is my HTML for the search box and the div where the results should go.
<form class='form-horizontal col-xs-12 col-md-12 col-lg-12' name="editticket" method="post" action="/processes/updateticket.php">
<div class='panel panel-primary'>
<div class='panel-heading'>
<h3 class='panel-title'>Edit Work Tickets</h3>
</div>
<div class='panel-body'>
<div class="input-group">
<span class="input-group-addon">Enter Ticket #</span>
<input type="text" class="form-control" id="search" name="WTNum" >
<span class="input-group-btn">
<button class="btn btn-default" type="button" onclick="showtickets(document.getElementById('search').value)">Search</button>
</span>
<div id="txtHint"><b></b></div>
</form>
Am I missing something!! This is driving me INSANE!!
Thank you all in advance. It is greatly appreciated.
Why not just call the showtickets function without arguments and then inside the function you do this
str = document.getElementById('search').value;
I think you must you javascript debug or alert in some scope to find where error

Categories

Resources