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?
Related
I am trying to submit data from a form to an external web page, but after submitting it, a "Thank you for contacting us" page appears.
<form action="HTTPS://WWW.externalPage.com/encoding?encoding=UTF-8" method="POST" class="row">
<div class="col-6">
<label class="form-label" for="first_name">first_name: </label>
<input class="form-control mb-3" id="first_name" maxlength="40" name="first_name" required size="20" type="text" />
</div>
<div class="col-6">
<label class="form-label" for="last_name">last_name: </label>
<input class="form-control mb-3" id="last_name" maxlength="80" name="last_name" required size="20" type="text" />
</div>
<div class="col-6">
<label class="form-label" for="mobile">mobile: </label>
<input class="form-control mb-3" id="mobile" maxlength="40" name="mobile" required size="20" type="text" />
</div>
<div class="col-6">
<label class="form-label" for="email">email: </label>
<input class="form-control mb-3" id="email" maxlength="80" name="email" required size="20" type="text" />
</div>
<div class="col-6">
<label class="form-label" for="company">company: </label>
<input class="form-control mb-3" id="company" maxlength="40" name="company" required size="20" type="text" />
</div>
<div class="col-12 buttonSubmit">
<input class="btn btn-dark" type="submit" name="submit" onclick="Gracias()">
</div>
</form>
With this I am sending the data to the controller, but it must go to another web page (ex: http://web.ReciveData.com/)
I tried to send the form to the web page like this
<form action="http://web.ReciveData.com/" method="POST" class="row">
Submit button with "Thanks()" function:
<input class="btn btn-dark" type="submit" name="submit" onclick="Thanks()">
JavaScript:
function Thanks() {
window.location.href("http://web.MyWebPage.com/Home/Thanks")
}
Also try this:
document.addEventListener('DOMContentLoaded', function () {
var formulario = document.getElementById('form');
var validateName = function (e) {
if (formulario.first_name.value.length == 0) {
return false;
}
return true;
};
var validateEmail = function () {
if (formulario.email.value.length == 0) {
return false;
}
return true;
};
var validatePhone = function () {
if (formulario.mobile.value == "") {
return false;
}
return true;
};
var validateMsj = function () {
if (formulario.mensage.value.length == 0) {
return false;
}
return true;
};
var validar = function () {
return validateName() &&
validateEmail() &&
validatePhone() &&
validateMsj();
};
formulario.addEventListener("submit", handleSubmit);
async function handleSubmit(event) {
event.preventDefault();
if (validar()) {
const form = new FormData(this);
const response = await fetch(this.action, {
method: this.method,
body: form,
headers: {
'Accept': 'application/json'
}
});
if (response.ok) {
this.reset();
window.location.href = 'Http://web.MyWebPage.com/Home/Thanks'
}
}
}
});
But it does not work. Basically what I'm trying to do is load the data, send it to the external web page, and a web page that I created to thank the contact is displayed.
I can think of absolutely nothing, and what I found on the internet are mostly basic examples..
I changed the header to
headers: {
/* 'Accept': 'application /x-www-urlencoded'*/
'Access-Control-Allow-Origin:': 'https://www.externalPage.com'
}
And now the problem is on line fetch(this.action):
Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Invalid name
at HTMLFormElement.handleSubmit
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
This question already has answers here:
Uploading both data and files in one form using Ajax?
(13 answers)
Closed 6 years ago.
Here I want insert the values in Database here normal value like name, email, area... This value getting and after that value passed in next through AJAX and doing insertion part but while file uploading I can't get consloe.log(file); I am getting like this C:\fakepath\Penguins.jpg I don't know how to resolve this,i want get the file value and pass in next page thrugh AJAX and move to tmp folder how can do.
function add_menu() {
var name = $("#name").val();
var address = $("#address").val();
var area = $("#area").val();
var file = $("#file").val();
var gender = $("input[name=gender]:checked").val();
var checkValues = $('input[name=fecility]:checked').map(function() {
return $(this).val();
}).get();
if (name == '') {
$("#span-error").html(' Fill Menu Name. ');
} else if (gender == '') {
$("#span-error").html(' Select Gender. ');
} else if (area == '') {
$("#span-error").html(' Fill area. ');
} else if (checkValues == '') {
$("#span-error").html(' Select Fecilities. ');
} else {
$.ajax({
type: "POST",
url: "ajax_add_menu.php",
data: "name=" + name + "&area=" + area + "&address=" + address + "&gender=" + gender + "&checkbox=" + checkValues,
success: function(data) { // alert(data);
if (data == "success") {
window.location = 'pg_details.php';
}
}
});
}
}
<form class="form-horizontal" role="form" id="formid" method="post" enctype="multipart/form-data">
<div class="form-group">
<label class="col-sm-2 control-label">Name<span class="require">*</span>
</label>
<div class="col-sm-8">
<input type="text" class="form-control" placeholder="Name" name="name" id="name">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Area<span class="require">*</span>
</label>
<div class="col-sm-8">
<input type="text" class="form-control" placeholder="Area" name="area" id="area">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Address<span class="require">*</span>
</label>
<div class="col-sm-8">
<textarea class="form-control" placeholder="Enter Address" name="address" id="address" style="min-height:100px;"></textarea>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Room Standereds<span class="require">*</span>
</label>
<div class="col-sm-8" style="margin-top:10px">
<?php $sqlf="SELECT * FROM pg_fecilitys" ; $resultf=m ysql_query($sqlf); while($rowf=m ysql_fetch_array($resultf)) { echo '<input type="checkbox" id="fecility" name="fecility" value="'.$rowf[ "f_id"]. '" required style="margin: 0px 2px 0px 18px;">'.$rowf[
"f_name"]; } ?>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Gender<span class="require">*</span>
</label>
<div class="col-sm-8">
<label class="radio-inline">
<input type="radio" id="gender" name="gender" value="male">Male</label>
<label class="radio-inline">
<input type="radio" id="gender" name="gender" value="female">Female</label>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">PG Image<span class="require">*</span>
</label>
<div class="col-sm-8">
<input type="file" class="form-control" placeholder="PG Image" name="file" id="file">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="tcb">
<label>
<span id="span-error" style="color:#f00;"></span>
</label>
</div>
</div>
</div>
<div class="form-actions">
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" class="btn btn-primary" onclick="add_menu()">Submit</button>
<!-- <button type="submit" class="btn">Cancel</button> -->
</div>
</div>
</div>
</form>
If you want value of the file, use - var file = $("#file").val(); ,
But if you want file then use - var file = $("#file").get(0).files[0];
Also if you want to pass file with ajax, then use jquery FormData() like:
function add_menu() {
var name = $("#name").val();
var address = $("#address").val();
var area = $("#area").val();
var file = $("#file").val();
var gender = $("input[name=gender]:checked").val();
fd = new FormData();
fd.append('file', $("#file").get(0).files[0]);
fd.append('name ', name );
fd.append('address', address);
fd.append('area', area);
fd.append('gender', gender);
// remaining codes - checking and ajax
////
$.ajax({
type: "POST",
url: "ajax_add_menu.php",
data: fd,
success: function(data) { // alert(data);
if (data == "success") {
window.location = 'pg_details.php';
}
}
});
Try to using form data object instead of string
data: new FormData('#formid'),
Replace this with above line
data: "name=" + name + "&area=" + area + "&address=" + address + "&gender=" + gender + "&checkbox=" + checkValues,
You could not upload file via ajax like this you need metadata, instead of json object, you can code ajax like below:-
// have a look..
formdata= new FormData($('#formid')[0]);
// to console data you do it with just get method on form data like
console.log(formdata.get('file')); // for file
console.log(formdata.get('name')); // name will be displayed
$.ajax ( {
method : 'POST',
url : 'ajax_add_menu.php',
data : formdata,
cache : false,
processData: false,
contentType: false,
success : function ( data, textStatus, jqXHR ) {
// do what ever in your success in code
},
error : function ( jqXHR, textStatus, errorThrown ) {
// do what ever in failure
}
} );
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);
I am trying to populate my json file via form. The javascript doesnt throw any error but the data doesnt load in the json file.I am new to promises as of now. I could see some posts for getting the values from the json file to view, but not vice-versa. Can anyone please help?
Service:
var module=angular.module('app',[]);
module.factory('memberDataStoreService',function($http)
{
var memberDataStore = {};
memberDataStore.addUser=function(adata){
var promise=$http({
method: 'POST',
url: 'data.json',
data: adata});
return promise;
}
return memberDataStore;
});
Controller
if ($scope.registrationForm.$valid) {
$scope.working = true;
var promise = memberDataStoreService.addUser($scope.person);
promise.success(function () {
$scope.showSuccessMessage = true;
});
promise.error(function (data, status) {
$scope.showErrorMessage = true;
});
promise.finally(function () {
$scope.working = false;
});
$scope.doShow = true;
}
html
<div ng-controller="MyController">
<form name="registrationForm" ng-submit="register()" novalidate>
<div ng-show="showSuccessMessage">
Thank you for taking the time to register!
</div>
<div class="error" ng-show="showErrorMessage">
There appears to have been a problem with your registration.<br/>
</div>
<input type="text" placeholder="First Name" name="firstName" ng-model="person.firstName" required/>
<span ng-show="firstNameInvalid"><br/>Please enter a value for First name</span>
<br/>
<input type="text" placeholder="Last Name" name="lastName" ng-model="person.lastName" required/>
<span ng-show="lastNameInvalid"><br/>Please enter a value for Last name</span>
<br/>
<input type="email" placeholder="Email" name="email" ng-model="person.email" required/>
<span ng-show="emailInvalid"><br/>A valid email address is required</span>
<br/>
<select name="research" ng-model="person.levels"
ng-options="obj.label as obj.value for obj in person.channels" required>
<option value="">Where did you hear about us?</option>
</select>
<span ng-show="researchInvalid"><br/>Please tell us where you heard about us</span>
<br/>
<input ng-model="person.newsletterOptIn" type="checkbox" name="newsletterOptIn"
id="newsletterOptIn" value="newsletterOptIn"/>
<label for="newsletterOptIn">Recieve monthly newsletter</label>
<br/>
<input ng-disabled="working" type="submit" value="Register"/>
<span ng-show="working" style="padding-left:10px;">
<img src="loading.gif"/>
</span>
</form>
</div>
</div>
As per angular promise documentation your code should look like this
https://docs.angularjs.org/api/ng/service/$q
if ($scope.registrationForm.$valid) {
$scope.working = true;
var promise = memberDataStoreService.addUser($scope.person);
promise.then(function () {
$scope.showSuccessMessage = true;
}).catch(function (data, status) {
$scope.showErrorMessage = true;
}).finally(function () {
$scope.working = false;
});
$scope.doShow = true;
}