Shopify Trying to update a customer - javascript

I'm trying to create a view where my customer can update his personal info (like First Name, Last Name, email, ect) using Liquid/JS, but I have failed epicly.
The nearest point that I have reached is this post where they use a form and some AJAX to update but I'm getting code 500. This is the code that I'm using (based on that).
<form action="/a/custmeta" method="POST" id="custmeta">
<input type="text" name="customer[id]" value="{{ customer.id }}" />
<input type="text" name="customer[first_name]" value="{{ customer.first_name }}" placeholder="namespace1.key1" />
<input type="text" name="customer[last_name]" value="{{ customer.last_name }}" placeholder="namespace2.key2" />
<input type="submit" />
</form>
<script>
$('form#custmeta').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
dataType: "json",
data: $(this).serialize(),
url: '/admin/customers/#{{ customer.id }}.json',
success: function (data) {
var formValid = (data.status === 'OK');
if (formValid) {
var msgs = '';
for (var i=0;i<data.messages.length;i++) {
msgs += '-- ' + data.messages[i] + '\n';
}
if (msgs > '') {
alert('SUCCESS WITH MESSAGES:\n\n' + msgs);
}
else {
alert('SUCCESS!');
}
}
else {
alert('Status: ' + data.status + '\nMessage: ' + data.message);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('AJAX or Server 500 error occurred');
}
});
return false;
});
</script>
found this other post where you could do it using the API but dont know how to use it.
Any help?

Related

Submit login with Jquery

When I press the Login button I get a 500 Internal server error in the console. What's the right way to get POST using jQuery? Can you help me?
<button class="login100-form-btn" type="submit" name="login" value="login" id="Login">
Login
</button>
$(function() {
$("#Login").click(function() {
var username_val = $("#username").val();
var password_val = $("#password").val();
var info_creds = 'username=' + username_val + '&password=' + password_val;
if (username_val == '' || password_val == '') {
$("#alert_response_ko").show();
$("#alert_response_ko").html("<p>Devi inserire username e password!</p>");
$("#alert_response_ko").fadeOut(8000);
} else {
$.ajax({
type: "POST",
url: "login.php",
data: info_creds,
cache: false,
success: function(response) {
if (response == 'wrong!') {
console.log('ko');
$("#alert_response_ko").show();
$("#alert_response_ko").html("<p>Username e/o Password Errati!</p>");
$("#alert_response_ko").fadeOut(8000);
}
if (response == 'login_ok!') {
console.log('ok');
window.setTimeout(function() {
window.location.href = './homepage.php';
}, 10);
}
}
});
}
return false;
})
});
The 500 Internal Server Error is a "server-side" error, meaning the problem is not with your PC or Internet connection but instead is a problem with the web site's server.
If you want to use Post, you have to send data as Object Change your
Ajax Function to...
$.ajax({
type: 'POST',
url: 'login.php',
data: {
username: username_val,
password: password_val,
},
cache: false,
success: function (response) {
if (response == 'wrong!') {
console.log('ko');
$('#alert_response_ko').show();
$('#alert_response_ko').html(
'<p>Username e/o Password Errati!</p>'
);
$('#alert_response_ko').fadeOut(8000);
}
if (response == 'login_ok!') {
console.log('ok');
window.setTimeout(function () {
window.location.href = './homepage.php';
}, 10);
}
},
});
Consider the following code.
$(function() {
function showAlert(msg) {
console.log(msg);
$("#alert_response_ko").html("<p>" + msg + "</p>").show().fadeOut(8000);
}
function login(page, user, pass) {
$.ajax({
url: page,
data: {
username: user,
password: pass
},
cache: false,
success: function(results) {
if (results == 'login_ok!') {
console.log('Login Successful');
window.setTimeout(function() {
window.location.href = './homepage.php';
}, 10);
} else {
showAlert("Username e/o Password Errati!");
}
},
error: function(x, e, n) {
showAlert("Username e/o Password Errati! " + e + ", " + n);
}
});
}
$("#Login").closest("form").submit(function(e) {
e.preventDefault();
var username_val = $("#username").val();
var password_val = $("#password").val();
if (username_val == '' || password_val == '') {
showAlert("Devi inserire username e password!");
} else {
login("login.php", username_val, password_val);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" id="username" placeholder="User" /> <input type="password" id="password" placeholder="Password" /> <button class="login100-form-btn" type="submit" name="login" value="login" id="Login">
Login
</button>
</form>
<div id="alert_response_ko"></div>
This might help identify issues. As was suggested, the 500 status is a general Web Server failure. It means that the Web Server encountered an error and may be configured to suppress the error message itself.
Check your PHP Logs and Error handling settings. Better to reveal errors while testing and then hide them when in production.

Changing from a textbox onblur to onKeyDown event

I have the following code on my partial view:
#foreach (var lineItem in Model.LineItems)
{
<tr>
<td>
<img src="#Url.Action("GetImage", "ImageBlocks", new { imageID = lineItem.Product.SelfOrDefault().Image.SelfOrDefault().ImageId, Width = 75 })" alt="Thumbnail" />
</td>
<td>
<span title="#(lineItem.Description ?? "")" id="lineItemDescription">#(lineItem.Product.ReceiptName ?? "")</span><br />
<span id="lineItemSKU">#lineItem.Product.SKU</span>
</td>
<td>
<span>#((lineItem.Product.InventorySummary ?? 0).ToString())</span><br />
</td>
<td><input type="text" id="lineItemQuantity" name="lineItemQuantity" value="#lineItem.Quantity" onblur="changeCartQty(#lineItem.Product.SKU,this.value)" /></td>
#if (lineItem.Discount != null ? lineItem.Discount.DiscountCategory != DiscountCategory.ORDER : true)
{
<td>
<input type="text" id="lineItemAmount" name="lineItemAmount" value="#lineItem.AdjustedUnitPrice.Value.ToString("C")" /><br />(Adj. #(lineItem.DiscountDisplayValue))
</td>
<td>#lineItem.AdjustedTotalLinePrice.Value.ToString("C")</td>
}
else
{
<td>#lineItem.BaseUnitPrice.Value.ToString("C")</td>
<td>#lineItem.TotalLineBaseValue.ToString("C")</td>
}
<td>Remove</td>
</tr>
}
<script>
On the lineItemQuantity text input, I want to change this from onblur to an onKeyDown event to capture the "Enter" key pressed to call the changeCartQty function with the same parameters. Here is the function being called:
function changeCartQty(ProductId, Quantity) {
var userId = $('#ID').val();
$.ajax({
url: "/Orders/AddtoCart",
type: 'POST',
cache: false,
datatype: 'json',
async: false,
data: { "ProductID": ProductId, "Quantity": Quantity, "UserID": userId},
success: function (data) {
console.log("Adjusted Quantity in cart");
success(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.error("[Error in Ajax request, adjust price] Code:" + jqXHR.status + "Error: " + errorThrown + " \nText Status: " + jqXHR.resonseText);
}
})
};
This works fine and the amounts update, I just need to change this to an onChange and I am unsure how this would be done.
Thanks.

Mailchimp via jQuery Ajax. Submits correctly but JSON response is returned as a separate page

I have the following form:
<form class="footer-newsletter-form" id="footer-newsletter" method="post" action="http://xxxxxx.us1.list-manage.com/subscribe/post-json?u=xxxxxxxxxxxxxxxxxxxxxxxxx&id=xxxxxxxxxx&c=?">
<input id="email" name="EMAIL" type="email" class="input-text required-entry validate-email footer__newsletter-field" value="{% if customer %}{{ customer.email }}{% endif %}" placeholder="{{ 'general.newsletter_form.email_placeholder' | t }}" aria-label="{{ 'general.newsletter_form.newsletter_email' | t }}">
<button type="submit" title="Subscribe" class="button button1 hover-white footer__newsletter-button">SUBSCRIBE</button>
<div id="subscribe-result"></div>
</form>
And the following jquery bit:
<script type="text/javascript">
$(document).ready(function () {
function register($form) {
jQuery.ajax({
type: "GET",
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'jsonp',
contentType: "application/json; charset=utf-8",
error : function(err) { console.log('error') },
success : function(data) {
if (data.result != "success") {
console.log('success');
} else {
console.log('not success');
//formSuccess();
}
}
});
}
jQuery(document).on('submit', '.footer-newsletter-form', function(event) {
try {
var $form = jQuery(this);
event.preventDefault();
register($form);
} catch(error){}
});
});
</script>
Which submits correctly. However, when I press the submit button what I expect to happen is that the page does not refresh and when I check the browser console I'll either see "success" or "not success". Instead what happens is I'm sent to a page that displays the following JSON message: ?({"result":"success","msg":"Almost finished... We need to confirm your email address. To complete the subscription process, please click the link in the email we just sent you."}).
So how do I take that success message (or error if there's an error) and have the page not only remain as is, but also capture the success message so I can display a "Success" alert? The success alert I know how to do. I just need help having the browser remain where it is and tell the difference between success and error.
P.S. I'm not sure if this is relevant but the platform is Shopify. I don't think Shopify does anything to prevent the submission from going through as it should or the response coming back so I don't think it is relevant.
The whole issue was the $(document).ready(function () {}); part. For some reason unbeknownst to me that causes the event.preventDefault(); method from running and the form submits regularly. If you remove the $(document).ready(function () {}); part it'll work as intended.
My final code for anyone looking in the future:
Form:
<form class="footer-newsletter-form" method="POST" id="footer-newsletter" action="https://xxxxxxxxxxxxx.us1.list-manage.com/subscribe/post-json?c=?">
<input type="hidden" name="u" value="xxxxxxxxxxxxxxxxxxxxxxxxxxx">
<input type="hidden" name="id" value="xxxxxxxxxx">
<input id="email" name="EMAIL" type="email" class="input-text required-entry validate-email footer__newsletter-field">
<button type="submit" title="Subscribe" class="button button1 hover-white footer__newsletter-button">SUBSCRIBE</button>
<div id="subscribe-result"></div>
</form>
And the JS:
<script>
function register($form) {
$.ajax({
type: "GET",
url: $form.attr('action'),
data: $form.serialize(),
cache: false,
dataType: 'json',
contentType: "application/json; charset=utf-8",
error: function (err) {
console.log('error')
},
success: function (data) {
if (data.result != "success") {
console.log('Error: ' + data.msg);
} else {
console.log("Success");
$($form).find("div#subscribe-result").html("<p class='success-message'>Almost finished... We need to confirm your email address. To complete the subscription process, please click the link in the email we just sent you!</p>");
setTimeout(function() { $($form).find("div#subscribe-result").hide(); }, 7000);
}
}
});
}
$(document).on('submit', '#footer-newsletter', function (event) {
try {
var $form = jQuery(this);
event.preventDefault();
register($form);
} catch (error) {}
});
</script>

show php json data into jquery ajax

I'm very new in this topic.I have a Json result something like this :
{
"span": " 1",
"numcard": "12",
"chan": " Yes",
"idle": "Yes",
"level": "idle ",
"call": "No ",
"name": ""
}
How can I show all the json data using a ajax .I currently have this code written up and although i am getting the data its not quite working the way i want it to be.
$("a[name=cardNo1]").click(function() {
var cardNo1 = $(this).attr("id");
$("a[name=cardNo1]").each(function() {
cardNo1 += "";
});
var dataString = "action=spanchan" + "&cardNo=" + cardNo1;
$.ajax({
type: "POST",
url: "dahdiprocess.php?",
data: dataString,
dataType: 'json',
success: function(data, status) {
if (data != "") {
$.each(data, function(key, val) {
$("#span").val(val.span);
$("#numcard").val(val.numcard);
$("#chan").val(val.chan);
$("#idle").val(val.idle);
$("#level").val(val.level);
$("#call").val(val.call);
$("#name").val(val.name);
});
}
}
});
});
<input id="span" name="span" value="" />
<input id="numcard" name="numcard" value="" />
<input id="chan" name="chan" value="" />
<input id="idle" name="idle" value="" />
<input id="level" name="level" value="" />
<input id="call" name="call" value="" />
<input id="name" name="name" value="" />
when I try to alert ,example alert(val.span) it keep showing undifined .Does anyone with experience in this topic and see if any problem about my code? Any help would be greatly appreciated.Thank you .
You are returning a single set of values so you do not need the each within your success handler. Try this:
success: function(data, status) {
if (data != "") {
$("#span").val(data.span);
$("#numcard").val(data.numcard);
$("#chan").val(data.chan);
$("#idle").val(data.idle);
$("#level").val(data.level);
$("#call").val(data.call);
$("#name").val(data.name);
}
}
In theory, you shouldn't need the data != "" check as your server side code should not be allowed to return an empty response for when the result of the request is 200 OK.
Try this:
$("a[name=cardNo1]").click(function() {
var cardNo1 = $(this).attr("id");
$("a[name=cardNo1]").each(function() {
cardNo1 += "";
});
var dataString = "action=spanchan" + "&cardNo=" + cardNo1;
$.ajax({
type: "POST",
url: "dahdiprocess.php?",
data: dataString,
dataType: 'json',
success: function(data, status) {
if (data != "") {
$("#span").val(data.span);
$("#numcard").val(data.numcard);
$("#chan").val(data.chan);
$("#idle").val(data.idle);
$("#level").val(data.level);
$("#call").val(data.call);
$("#name").val(data.name);
}
}
});
});
should be
if (data != "") {
$("#span").val(data.span);
$("#numcard").val(data.numcard);
$("#chan").val(data.chan);
$("#idle").val(data.idle);
$("#level").val(data.level);
$("#call").val(data.call);
$("#name").val(data.name);
}

Magento newsletter ajax request returns null

I am trying to send a newsletter subscription request to Magento, but It returns null and nothing happens.
I've searched around and found very different URLs to post the request. And also grabbed the code from the file from base template.
In fact, maybe I am not sending the correct parameters or whatever.
This is the code in use:
<form method="post" id="newsletter-form">
<input type="hidden" class="url" value="<?php echo $this->getUrl('newsletter/subscriber/new') ?>">
<input id="newsletter" type="text" name="email" placeholder="RECEBA NOVIDADES" value="" class="input-text myFormInput" maxlength="128" autocomplete="off" style="width: 188px !important">
<button type="submit" id="ajax-newsletter-submit" title="CADASTRAR"
class="button myFormButton" style="margin-top:20px;margin-left: -107px !important;width: 103px">CADASTRAR</button>
</div>
</form>
Javascript:
var newsletterSubscriberFormDetail = new VarienForm('newsletter-form');
$j(function() {
$j("#ajax-newsletter-submit").click(function() {
var email =$j("#newsletter").val();
var url=$j(".url").val();
var dataString = 'email='+ email;
if(email=='') {
$j("#newsletter").focus();
} else {
var a = email;
var filter = /^[a-zA-Z0-9_.-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{1,4}$/;
if(filter.test(a)){
$j.ajax({
type: "POST",
url: url,
data: dataString,
success: function(){
alert('Assinatura realizada com sucesso!');
$j("#newsletter").val('');
}
});
} else {
$j("#newsletter").focus();
}
}
return false;
});
});
Try this code,
var val_form = new VarienForm('your form id');
jQuery("#your form id").submit(function(e)
{
if (val_form.validator && val_form.validator.validate())
{
var postData = jQuery(this).serializeArray();
var formURL = jQuery(this).attr("action");
jQuery.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
alert('success');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('Failure');
}
});
this.reset(); //form field reset
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
}
});

Categories

Resources