Shopify API return custom message - ajax

I am using the shopify ajax api to add products to my customers cart, and have a js file with the following code
Shopify.onError = function(error) {
alert('Error: ' + error.message);
},
Shopify.onCartUpdate = function(cart) {
alert("There are now "+ cart.item_count + " items in the cart.");
},
Shopify.onItemAdded = function(line_item) {
alert(line_item.title + ' Was aloted to your shopping cart');
},
Shopify.onProduct = function(product) {
alert('Received everything we ever wanted to know about '+ product.title);
},
which i was under the impression would depending on the ajax result return one of the above messages
i am making the call with the following statement
<button class="button" onclick="Shopify.addItem(jQuery('#add_item').val(), jQuery('#add_item_qty').val());return false"><i class="foundicon-cart"></i> Add to cart</button>
which is working though returning the default messages

It appears to be a syntax issue }, should be };, for example:
Shopify.onCartUpdate = function(cart) {
alert("There are now "+ cart.item_count + " items in the cart.");
},
should be
Shopify.onCartUpdate = function(cart) {
alert("There are now "+ cart.item_count + " items in the cart.");
};

Related

My jquery and ajax call is not responding and showing unexpected error in console

I don't know why my code is giving error while making the ajax call and not responding or working at all. I ran this on an html file. I took this function - getParameterByName() from another stackoverflow answer.tweet-container tag is down the code below outside this script and an empty division.I tried some jquery also.
<script>
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
$(document).ready(function(){
console.log("working");
var query = getParameterByName("q")
// console.log("query");
var tweetList = [];
function parseTweets(){
if (tweetList == 0){
$("#tweet-container").text("No tweets currently found.")
} else {
//tweets are existing, so parse and display them
$.each(parseTweets, function(key, value){
//console.log(key)
// console.log(value.user)
// console.log(value.content)
var tweetKey = value.key;
var tweetUser = value.user;
var tweetContent = value.content;
$("#tweet-container").append(
"<div class=\"media\"><div class=\"media-body\">" + tweetContent + "</br> via " + tweetUser.username + " | " + View + "</div></div><hr/>"
)
})
}
}
$.ajax({
url:"/api/tweet/",
data:{
"q": query
},
method: "GET",
success:function(data){
//console.log(data)
tweetList = data
parseTweets()
},
error:
function(data){
console.log("error")
console.log(data)
}
})
});
</script>
strong text
Fix the quotes to resolve your syntax error:
$("#tweet-container").append("<div class=\"media\"><div class=\"media-body\">" + tweetContent + " </br> via " + tweetUser.username + " | " + "View</div></div><hr/>")

MVC Controller getting 404 error

I have an MVC controller that has several Methods on it. One to show the View, 6 that are for jquery ajax methods. The View shows up correctly and here is the simple code
public ActionResult Queues()
{
return View();
}
On that view there are 2 datatable.net grids. That grid gets populated with a ajax call to this
[HttpGet]
public async Task<JsonResult> QueueOne()
{
try
{
....
var results = await GetData(queryString, authUser.AccessToken).ConfigureAwait(false);
var jsonObj = JsonConvert.DeserializeObject<DataTableWrapper<QueueItemForRead>>(results);
return Json(jsonObj, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Logger.Error(ex.Message, ex);
}
return Json("Error occured please try again");
}
which populates the grid correctly.
I have other functions on the page that call another endpoint on the page
public async Task<JsonResult> ItemComplete(Guid QueueId, long version)
{
try
{
...
var results =
await
PutData(queryString, JsonConvert.SerializeObject(itemCompleted), authUser.AccessToken)
.ConfigureAwait(false);
var jsonObj = JsonConvert.DeserializeObject<NewItemCommandResult>(results);
return Json(jsonObj, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Logger.Error(ex.Message, ex);
}
return Json("Error occured please try again");
}
and here is the JS that calls the above endpoint
$.ajax({
url: 'http://localhost:18171/Clients/CurrentActivity/ItemComplete' + "?QueueId=" + data + "&version=" + version,
type: 'PUT',
//contentType: 'application/json',
//dataType: 'json',
success: function (result) {
if (result.Result === 2) {
showSuccessNotification(name +
" has been Delivered to table.",
"Food Delivered");
}
//else {
//}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//Process error actions
console.log(XMLHttpRequest.status + ' ' +
XMLHttpRequest.statusText);
$(buttonName).hide();
},
beforeSend: function () {
// Code to display spinner
$(buttonName).hide();
$(completedAjax).show();
},
complete: function () {
// Code to hide spinner.
$(completedAjax).hide();
}
});
but everytime this function is run all I get a 404 error.
Sorry it was bad cut and paste job, the URL actually has signle quotes around it. and i get the base Url this way
var QueueUrl = '#Url.Action("QueueOne","CurrentActivity")';
so when it renders the actual url is '/Clients/CurrentActivity/QueueOne'
your url doesn't contain " " Or ' ' so it isn't considered as string it should be like
url: "/Clients/CurrentActivity/ItemComplete?QueueId=" + data + "&version=" + version,
Don't Use Your Local Domain IN the Url This Will Cause Problem In production Version if you forget to change it
you can also use Url Helper To Make valid Url Like
url: "#Url.Action("ItemComplete","CurrentActivity",new{area='Clients'})"+"'QueueId=' + data + "&version=" + version,

how to open a url from the barcode scanner in phonegap build

i'am using the Barcode Scanner for phonegap build, How would i retrieve the QR Codes URL data and display the webpage into a Iframe or div
$(document).ready(function(e) {
$("#scanner_mode").click(function() {
cordova.plugins.barcodeScanner.scan(
function (result) {
alert("We got a barcode\n" +
"Result: " + result.text + "\n" +
"Format: " + result.format + "\n" +
"Cancelled: " + result.cancelled);
},
function (error) {
alert("Scanning failed: " + error);
}
);
});
});
Right i have tried this but its not working, so how would i get the src of a iframe to load result.text url
$(document).ready(function(e) {
$("#scanner_mode").click(function() {
cordova.plugins.barcodeScanner.scan(
function (result) {
document.getElementById("frame").src = result.text;
},
function (error) {
alert("Scanning failed: " + error);
}
);
});
});
yep so its working :)
$(document).ready(function(e) {
$("#scanner_mode").click(function() {
cordova.plugins.barcodeScanner.scan(
function (result) {
document.getElementById("frame").src = result.text;
},
function (error) {
alert("Scanning failed: " + error);
}
);
});
});
that works :)

MVC 3 & Uploadify - how to show custom error message?

After uploading a file, before I save it on the disk, I'm doing some validation.
If something fails, I want to show my custom error message to the user.
I've found something sililar here Uploadify: show error message from HTTP response
How to do this in MVC 3 ?
Tony,
Taken straight from ab mvc3 app that I'm working on right now:
<script type="text/javascript">
function initupLoadify() {
$("#fileInput").uploadify({
uploader: '#Url.Content("~/scripts/swf/uploadify.swf")',
script: '#Url.Action("Upload", "Home")',
cancelImg: '#Url.Content("~/Content/cancel.png")',
auto: true,
sizeLimit: 5500000,
fileDataName: 'fileData',
//scriptData: { 'propertyId': $("#PropertyID").val() },
buttonText: 'Add Schedule',
wmode: 'transparent',
//buttonImg: '#Url.Content("~/Content/button.png")', // make nice gradient image for button
onComplete: function (event, queueId, fileObj, response) {
$("#msg").html(response);
// do something
setTimeout(2000, window.location = '#Url.Action("Index")' + '?id=' + response);
return true;
},
onCancel: function (evt, queueId, fileObj, data) {
$("#msg").html("<br />Operation cancelled");
return true;
},
onOpen: function (evt, queueId, fileObj) {
$("#msg").html("<br />Upload in progress");
return true;
},
onError: function (event, queueId, fileObj, errorObj) {
$("#msg").html(fileObj.name + " was not uploaded ");
if (errorObj.status == 404)
$("#msg").html("Could not find upload script. Use a path relative to: " + "<?= getcwd() ?>");
else if (errorObj.type === "HTTP")
$("#msg").html("error " + errorObj.type + ": " + errorObj.status);
else if (errorObj.type === "File Size")
$("#msg").html(fileObj.name + " " + errorObj.type + " Limit: " + errorObj.info / 1000 + " KB");
else
$("#msg").html("error " + errorObj.type + ": " + errorObj.text);
}
});
};
</script>
hope this helps
Here is an MVC 3 example.
If you're using versions 3.0+ use onUploadComplete instead of onComplete (realize their parameters differ).

How can i define a variable in Json?

i want define a variable in Json callback.
Code;
$("select").change(function () {
var $variable = "";
$("select option:selected").each(function () {
$variable += $(this).text() + " ";
});
$("div.yaz").text($variable);
$('#result').html('loading...');
$.getJSON('program-bilgileri.php', function(JSON){
$('#result').empty();
$.each(JSON.$variable, function(i, program){
$('#result')
.append(program.isim +'<br />')
.append(program.bilgi+'<br />')
.append(program.adres+'<hr />');
});
});
})
.trigger('change');
program-bilgileri.php returns;
{
"programlar":[
{
"isim":"Zone Alarm",
"bilgi":"bilgisayarın güvenliğini sağlar",
"adres":"www.zonealarm.com"
},
{
"isim":"Opera",
"bilgi":"güvenli ve hızlı bir web tarayıcısıdır",
"adres":"www.opera.com"
},
{
"isim":"Photoshop",
"bilgi":"güçlü bir imaj işleme yazılımıdır",
"adres":"www.adobe.com"
}
]
}
The problem is here "$.each(JSON.$variable, function(i, program)" if I define $variable in JSON it isn't working.
Any idea?
The problems i see are
Inside the change event you are using $("select option:selected") which finds all select elements in the page, and not the changed one only.
use $(this).children('option:selected') instead.
I am assuming that you are allowing multiple selection on the select element and that is why you are doing += with the $variable.. (you are also adding a space at the end). That means, though, that the variable will be something like "programlar " or "programlar somethingelse".
Your returned JSON though has a key of programlar. A single word, no spaces.. so when you do JSON[$variable] which is the correct way to access an element based on the name in a variable, it does not match.
If the <select> element does not allow multiple selection then the solution is
$("select").change(function() {
var $variable = $(this).children("option:selected").text();
$("div.yaz").text( $variable );
$('#result').html('loading...');
$.getJSON('program-bilgileri.php', function(JSON) {
$('#result').empty();
$.each(JSON[$variable], function(i, program) {
$('#result')
.append(program.isim + '<br />')
.append(program.bilgi + '<br />')
.append(program.adres + '<hr />');
});
});
}).trigger('change');
If indeed it is a multiselect and each option can appear in the JSON then you must check for each option found in the variable.
$("select").change(function() {
var $variable = $(this).children("option:selected").map(function(){
return $(this).text();
}).get();
$("div.yaz").text( $variable.join(' ') );
$('#result').html('loading...');
$.getJSON('program-bilgileri.php', function(JSON) {
$('#result').empty();
for (index=0, length = $variable.length; index < length; index ++) {
$.each(JSON[$variable[index]], function(i, program) {
$('#result')
.append(program.isim + '<br />')
.append(program.bilgi + '<br />')
.append(program.adres + '<hr />');
});
}
});
}).trigger('change');
Try
$.each(JSON['programlar'], function(i, program) ... );
This will iterate over this part of your returned JSON object from PHP:
{
"isim":"Zone Alarm",
"bilgi":"bilgisayarın güvenliğini sağlar",
"adres":"www.zonealarm.com"
},
{
"isim":"Opera",
"bilgi":"güvenli ve hızlı bir web tarayıcısıdır",
"adres":"www.opera.com"
},
{
"isim":"Photoshop",
"bilgi":"güçlü bir imaj işleme yazılımıdır",
"adres":"www.adobe.com"
}

Resources