i having issues getting a page to redirect after a button click and some validation. i have tried multiple soluitons and keep getting to the same result where the address bar populates the url but no redirection. if i refresh with f5 or click on the refresh button of the browser than it works and the page redirects and load fine. this is on all browsers that i have tried. So i must be missing something or doing something wrong. below is my code:
........
..............
//render function for json + templates like handlebars, xml + xslt etc.
render: function (dataItem, statuses) {
$list.html(template(dataItem.content));
// action button events
//$('.action a').on("click",function (e){
$('.action a').bind('click', function(e){
var $this = $(this),
action = $this.attr("action"),
$id = $this.closest('ul').attr('id');
// get which link was click for appropriate action
switch(action){
case 'prev' :
break;;
case 'edit' :
if($this.hasClass("actionEnabled")) {
$().ajaxCall(checkURL,{'ID':$id})
.done(function(data){
if(data.result == 0) {
var baseURL = window.location.href.replace(window.location.hash, '') + '#',
url = baseURL + secondUrl_part + "?ID=" + $id;
// url = "http://mysite/index.php#/page/destPage.php?ID=idabcdefgh"
// tried with javascript all these different methods -> still did not work
// method 1
$(location).attr('href', "http://mysite/index.php#/page/destPage.php?ID=idabcdefgh");
// method 2
window.location = "http://mysite/index.php#/page/destPage.php?ID=idabcdefgh";
// method 3
window.location.href = "http://mysite/index.php#/page/destPage.php?ID=idabcdefgh";
// method 4
window.location.replace("http://mysite/index.php#/page/destPage.php?ID=idabcdefgh");
// even tried with return false as suggested by some people
//return false;
} else {
// todo error message no longer exist
}
})
.fail(function(){
// todo error : could not be loaded
})
} else {
e.preventDefault();
// to do add message cannot edit
}
break;;
case 'del' :
break;
}
});
}
..........
.......
.....
here is the code based on Ivan's answer
//render function for json + templates like handlebars, xml + xslt etc.
render: function (dataItem, statuses) {
$list.html(template(dataItem.content));
// action button events
//$('.action a').on("click",function (e){
$('.action a').bind('click', function(e){
var $this = $(this),
action = $this.attr("action"),
$id = $this.closest('ul').attr('id');
// get which link was click for appropriate action
switch(action){
case 'prev' :
break;;
case 'edit' :
if($this.hasClass("actionEnabled")) {
$().ajaxCall(checkURL,{'ID':$id})
.done(function(data){
if(data.result == 0) {
var baseURL = window.location.href.replace(window.location.hash, '') + '#',
url = baseURL + secondUrl_part + "?ID=" + $id;
$(location).attr('href', url);
location.reload();
} else {
// todo error message no longer exist
}
})
.fail(function(){
// todo error : could not be loaded
})
} else {
e.preventDefault();
// to do add message cannot edit
}
break;;
case 'del' :
break;
}
});
}
Related
I'm trying to show an alert every time customer is trying to add variant quantity that is bigger than available quantity. When that's happens I see 422 response from add.js -
{status: 422, message: "Cart Error",…}
description: "All 1 Black Basic High Waisted Briefs - black / 1 are in your cart."
message: "Cart Error"
status: 422
I need to display the description for customers, how that is possible?
Here is my code -
var shopifyAjaxAddURL = '/cart/add.js';
var shopifyAjaxCartURL = '/cart.js';
var shopifyAjaxStorePageURL = '/search';
$(document).on('submit', 'form[action="/cart/add"]:not(.noAJAX, .feedback-go_to_cart)', function(e) {
var $form = $(this);
//Add to cart
$.post(shopifyAjaxAddURL, $form.serialize(), function(itemData) {
//Enable add button
$btn.html(theme.icons.tick + ' ' + {{ 'products.product.added_to_cart' | t | json }});
setTimeout(function(){
//Not added, show message
if(typeof(data) != 'undefined' && typeof(data.status) != 'undefined') {
var jsonRes = $.parseJSON(data.responseText);
window.showQuickPopup(jsonRes.description, $btn);
} else {
//Some unknown error? Disable ajax and submit the old-fashioned way.
$form.addClass('noAJAX');
$form.submit();
}
});
Your code seems bit buggy. Possible solution could be, check if the status is 422 and send the customer an alert message.
if( itemData.status === 422 ) { alert('Quantity not available in the inventory') }
Full code might look like:
var shopifyAjaxAddURL = '/cart/add.js';
var shopifyAjaxCartURL = '/cart.js';
var shopifyAjaxStorePageURL = '/search';
$(document).on('submit', 'form[action="/cart/add"]:not(.noAJAX, .feedback-go_to_cart)', function (e) {
var $form = $(this);
//Add to cart
$.post(shopifyAjaxAddURL, $form.serialize(), function (itemData) {
if( itemData.status === 422 ) { alert('Quantity not available in the inventory') }
else {
//Enable add button
$btn.html(theme.icons.tick + ' ' + {{ 'products.product.added_to_cart' | t | json }});
setTimeout(function () {
//Not added, show message
if (typeof (data) != 'undefined' && typeof (data.status) != 'undefined') {
var jsonRes = $.parseJSON(data.responseText);
window.showQuickPopup(jsonRes.description, $btn);
} else {
//Some unknown error? Disable ajax and submit the old-fashioned way.
$form.addClass('noAJAX');
$form.submit();
}
}
});
I perform an edit to ensure against duplicate emails by making an ajax call and supplying a callback. If a duplicate exists, I want to return false from submit event. Is there an elegant way to achieve this without setting async=false? What I tried (see emailCallback) is not working.
submit event
EDIT (included the rest of the submit handler).
$("#form-accounts").on("submit", function (e) {
e.preventDefault();
if (!$(this).get(0).checkValidity()) return false;
if (!customValidation(true, false)) return;
checkDupEmail(emailCallback);
function emailCallback(result) {
if (result) return (function () { return false } ());
}
if ($("#submit").text() == "Create Account") {
var formData = $("#form-accounts").serialize().replace("''", "'");
ajax('post', 'php/accounts.php', formData + "&action=create-account", createSuccess);
function createSuccess(result) {
if (isNaN(result)) {
showMessage(0, result);
return;
}
localStorage.setItem("account-id", result);
debugger
setUsertype($("input[name=user-type]:checked").val());
showMessage(1, "Account Created");
};
return
}
var rString = randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
};
var anRandom = randomString(14, rString);
$("#code").val(anRandom);
console.log("v-code=" + anRandom);
$("#submit").css({ 'display': 'none' });
$("#verify").css({ 'display': 'block' });
var subject = "Writer's Tryst Verification Code"
$("#subject").val(subject);
var msg = "This mail is intended for the person who requested verification of email ownership at Writers-Tryst (" + getWriterTrystURL() + ").\n\n" + "Double click on the code below and then copy it. Return to our website and and paste the code.\n\nYour verification code: \n\n" + anRandom;
$("#msg").val(msg);
var formData = $("#form-accounts").serialize().replace("''", "'");
ajax('post', 'php/sendmail.php', formData, successMail, "create-account error: ");
function successMail(result) {
$("#ver-email-msg").val("An email has been sent to you. Double-click the verification code then copy and paste it below.").css({ 'display': 'block' });
}
});
function checkDupEmail(callback) {
var data = {};
data.action = "validate-email";
data.email = $("#email").val();
ajax('post', 'php/accounts.php', data, emailSuccess);
function emailSuccess(result) {
if (parseInt(result) > 0) {
showMessage(0, "The email address is in use. Please supply another or login instead of creating a new account.")
callback(true);
} else callback(false);
}
}
Instead of passing a callback, why don't you just submit the form when your Ajax call completes successfully?
$("#form-accounts").on("submit", function (e) {
// Always cancel the submit initially so the form is not submitted until after the Ajax call is complete
e.preventDefault();
...
checkDupEmail(this);
...
});
function checkDupEmail(form) {
var data = {};
data.action = "validate-email";
data.email = $("#email").val();
ajax('post', 'php/accounts.php', data, function(result) {
if (parseInt(result) > 0) {
showMessage(0, "The email address is in use. Please supply another or login instead of creating a new account.")
} else {
form.submit();
}
}
}
A better approach than that would be to submit your form using Ajax. That would eliminate the need for two calls to the server.
I am trying to explicitly get the system properties from my table but it is not working. I can see that the URL is returning all the data including these fields if I use https://myservice.azure-mobile.net/tables/todoitem?__systemProperties=* but on the code I cannot get it as item.__version or item.version. I have tried adding todoitemtable = WindowsAzure.MobileServiceTable.SystemProperties.All; but no success! I have also looked at http://azure.microsoft.com/en-us/documentation/articles/mobile-services-html-validate-modify-data-server-scripts/ but this is adding a new column instead of using the existing system columns.
$(function() {
var client = new WindowsAzure.MobileServiceClient('https://ib-svc-01.azure-mobile.net/', 'key');
var todoItemTable = client.getTable('todoitem');
// = WindowsAzure.MobileServiceTable.SystemProperties.All;
// Read current data and rebuild UI.
// If you plan to generate complex UIs like this, consider using a JavaScript templating library.
function refreshTodoItems() {
var query = todoItemTable.where({ complete: false });
query.read().then(function(todoItems) {
var listItems = $.map(todoItems, function(item) {
return $('<li>')
.attr('data-todoitem-id', item.id)
.append($('<button class="item-delete">Delete</button>'))
.append($('<input type="checkbox" class="item-complete">').prop('checked', item.complete))
.append($('<div>').append($('<input class="item-text">').val(item.id))
.append($('<span class="timestamp">'
+ (item.createdAt && item.createdAt.toDateString() + ' '
+ item.createdAt.toLocaleTimeString() || '')
+ '</span>')));
});
$('#todo-items').empty().append(listItems).toggle(listItems.length > 0);
$('#summary').html('<strong>' + todoItems.length + '</strong> item(s)');
}, handleError);
}
function handleError(error) {
var text = error + (error.request ? ' - ' + error.request.status : '');
$('#errorlog').append($('<li>').text(text));
}
function getTodoItemId(formElement) {
return $(formElement).closest('li').attr('data-todoitem-id');
}
// Handle insert
$('#add-item').submit(function(evt) {
var textbox = $('#new-item-text'),
itemText = textbox.val();
if (itemText !== '') {
todoItemTable.insert({ text: itemText, complete: false }).then(refreshTodoItems, handleError);
}
textbox.val('').focus();
evt.preventDefault();
});
// Handle update
$(document.body).on('change', '.item-text', function() {
var newText = $(this).val();
todoItemTable.update({ id: getTodoItemId(this), text: newText }).then(null, handleError);
});
$(document.body).on('change', '.item-complete', function() {
var isComplete = $(this).prop('checked');
todoItemTable.update({ id: getTodoItemId(this), complete: isComplete }).then(refreshTodoItems, handleError);
});
// Handle delete
$(document.body).on('click', '.item-delete', function () {
todoItemTable.del({ id: getTodoItemId(this) }).then(refreshTodoItems, handleError);
});
// On initial load, start by fetching the current data
refreshTodoItems();
});
I was trying to access the system properties from within the API scripts and found this and thought it was useful and relevant: http://www.brandonmartinez.com/2014/10/22/retrieve-system-properties-in-azure-mobile-services-javascript-backend/
Basically you can do this (example from the post):
myTable.read({
systemProperties: ['__createdAt', '__updatedAt'],
success: function(tableEntries) {
// So on and so forth
}
}
I am using a script with jQuery:
$(document).ready(function () {
var button;
var line;
var inputs;
var params = {};
var updatefield;
$('button.update').click(function () {
button = $(this);
params['button'] = button.val();
line = button.closest('.line');
updatefield = line.find('td.resultFromGet');
inputs = line.find('input');
inputs.each(function (id, item) {
switch($(item).attr('type')){
case 'checkbox':{
params[$(item).attr('name')] = new Array($(item).is(':checked'));
break;
}
default:{
params[$(item).attr('name')] = new Array($(item).attr('value'));
break;
}
}
});
//alert(JSON.stringify(params, null, 4));
$.get( 'core/ajax/correct_exec.php', params )
.done(function (data){
if(data == '1'){
$(updatefield).html('UPDATE_RECORD_SUCCESS');
} else {
$(updatefield).html( data );
}
});
});
});
The page I am getting is doing echo '1'; from PHP in case of success.
I try to test this with data == 1 but it doesn't work even though it is a success. In fact, it sends me $(updatefield).html( data ); which is 1. So why can't it just print UPDATE_RECORD_SUCCESS?
The data response is coming with white space, if you use trim() function something like this, then if condition should be executed.
if(data.trim() == '1'){
$('#updatefield').html('UPDATE_RECORD_SUCCESS'); //this should be executed
} else {
$('#updatefield').html( data );
}
Here you can see the space with data in chrome debugger.
There is a form that i want to submit and url rewrite at the same time. I can change url by adding onsubmit="rewrite_form(event);" option in form :
function rewrite_form(e) {
var form = document.forms[0]; // .getElementById("form1");
window.location = '/search/' + form.f.value + '_' + form.t.value + '.htm/' + form.amt_from.value;
if (e && e.preventDefault) { e.preventDefault(); }
return false;
}
Url changes but other values of form not posted to url generated page.
Just change the form's action property instead.
function rewrite_form(e) {
var form = documen.forms[0];
form.action = 'newurl';
//rest of code, make sure not to call e.preventDefault(); or return false
//because the form will not get submitted
}
i got the solution:
function rewrite_form() {
//Create custom link here
----------------------------
----------------------------------
//create form submit action
var url = '/search/' +'your custom link';
document.getElementById('FormId').action = url;
document.FormId.submit();
}