Using a JavaScript index variable to access a ViewBag array item - javascript

I am trying to access a global javascript variable in order to pass it as part of the data to my ajax function. Struggling with how to do it because imageIndex does not exist in the current context.
Javascript:
<script type="text/javascript">
var imageIndex = 0;
$(document).ready(function () {
var imageIndex = 0;
getImage();
function getImage() {
$.ajax({
type: "GET",
url: '#Url.Action( "GetImage", "Tally" )',
data: { imageName: '#(ViewBag.images[imageIndex])', contractID: '#(ViewBag.contractId)' },
//dataType: "image/jpeg;base64",
success: function (data) {
console.log(data);
$('#scanImage').attr('src', 'data:image/jpeg;base64,' + data.myImage);
$("#imageName").val('#(ViewBag.image)');
imageIndex++;
},
error: function () {
console.log("got error");
}
});
}
});
</script>

The Issue(s)
1. Remove one of your imageIndex initializations from the top. For all intents and purposes I'd say it really doesn't matter which one in your case.
2. imageIndex is being included as part of imageName as a string, rather than the variable's value.
The Tricky Part
Razor won't let us simply concatenate the variable as we normally would by doing something like:
imageName: '#(ViewBag.images[' + imageIndex + '])'
Because we're including a single quote within the server-side #, C# will tell you that you have an overflowing literal.
The Solution
Instead, we'll need to populate a normal javascript array from the ViewBag.images array.
var imageArray = #Html.Raw(Json.Encode(#ViewBag.images));
// var imageArray = ["image1", "image2", "image3"];
From there, we can now use imageArray[imageIndex] to retrieve the value we're looking for.
$(document).ready(function () {
var imageIndex = 0;
//Convert our ViewBag.images into a JS array
var imageArray = #Html.Raw(Json.Encode(#ViewBag.images));
getImage();
function getImage() {
$.ajax({
type: "GET",
url: '#Url.Action( "GetImage", "Tally" )',
data: { imageName: imageArray[imageIndex], contractID: '#(ViewBag.contractId)' },
//dataType: "image/jpeg;base64",
success: function (data) {
console.log(data);
$('#scanImage').attr('src', 'data:image/jpeg;base64,' + data.myImage);
$("#imageName").val('#(ViewBag.image)');
imageIndex++;
},
error: function () {
console.log("got error");
}
});
}
});

Hmm, I think you are getting it wrong here:
imageName: '#(ViewBag.images[imageIndex])'
try: imageName: '#(ViewBag.images[' + imageIndex + '])'
also, why are you declaring variables twice?
<script type="text/javascript">
var imageIndex = 0; //this
$(document).ready(function () {
var imageIndex = 0; //and this?
....

Related

How to combine 2 function with 1 function in the javascript?

I am creating the function to save data using javascript pass to backend. Now I need to combine two function with 1 function in the javascript. Because I want to click one button can run the two functions.
First function - The first function is once I've clicked the button, the images will show in the page then pass to backend to do the save function.
function save_qr(form) {
html2canvas($("#createImg"), {
onrendered: function(canvas) {
var imgsrc = canvas.toDataURL("image/png");
console.log(imgsrc);
$("#newimg").attr('src', imgsrc);
$("#img").show();
var dataURL = canvas.toDataURL();
$.ajax({
type: "POST",
url: "?f=" + loc,
data: {
imgBase64: dataURL
}
}).done(function(o) {
console.log('saved');
});
}
});
}
Second function- This function will pass to backend to do insert form data function.
function save_qr(form) {
var error_msg = new Array();
$("#" + form + " .blank").each(function() {
if ($.trim($(this).val()) == "") {
error_msg.push("The " + $(this).attr("title") + " should not be blank.");
}
});
var loc = getQueryVariable('loc');
var serialized = $('#' + form).serialize();
var extra = '&action=save';
var form_data = serialized + extra;
if (error_msg.length < 1) {
$.ajax({
type: 'POST',
url: "?f=" + loc,
data: form_data,
beforeSend: function() {
show_overLay();
},
success: function(data) {
if (data) {
console.log(data);
hide_overLay(data);
//$('#save').prop('disabled',true);
window.location = "?loc=" + loc;
} else {
hide_overLay(data);
}
}
});
} else {
alert(error_msg.join("\n"));
}
}
That means I want to do the first function first to show the image first then to do the second function. The url using same location backend within in the two functions. Hope someone can guide me how to combine these two function with 1 function. Thanks.
Noteļ¼šThese two functions are worked if do it separate.
ERROR:
Am I just blind or is it that simply. Rename the functions to save_qr1 and save_qr2 (Currently the functions have the same name) and use them in a new full_save_qr function:
function full_save_qr(form) {
save_qr1(form);
save_qr2(form);
}
The functions are processes synchronous. That means your save_qr1 will be processed before save_qr2. If you want a specific time to happen between the two functions you need to use something like setTimeout
function full_save_qr(form) {
save_qr1(form);
setTimeout(() => save_qr2(form), 1000);
}
Simply add global variable like var isImageShow = false. Call wrap your code like
var isImageShow = false;
function save_qr(form) {
if (!isImageShow) {
isImageShow = true;
// 1st function code
} else {
// 2nd function code
}
}
If you want to check condition on dataURL then declare dataURL as global variable. And update condition as if(!dataURL). Also update var dataURL = canvas.toDataURL(); to dataURL = canvas.toDataURL(); so it will use globally declared dataURL.
var dataURL = "";
function save_qr(form) {
if (!dataURL) {
html2canvas($("#createImg"), {
onrendered: function(canvas) {
var imgsrc = canvas.toDataURL("image/png");
console.log(imgsrc);
$("#newimg").attr('src', imgsrc);
$("#img").show();
dataURL = canvas.toDataURL(); // removed var from here.
$.ajax({
type: "POST",
url: "?f=" + loc,
data: {
imgBase64: dataURL
}
}).done(function(o) {
console.log('saved');
});
}
});
} else {
// 2nd function code
}
}

Cannot read property 'row' of undefined

//anything inside 'pagebeforecreate' will execute just before this page is rendered to the user's screen
$(document).on("pagebeforecreate", function () {
printheader(); //print the header first before the user sees his page
});
$(document).ready(function () {
searchfriend();
function searchfriend() {
var url = serverURL() + "/getcategories.php";
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (arr) {
_getCategoryResult(arr);
},
error: function () {
validationMsg();
}
});
}
function _getCategoryResult(arr) {
var t; //declare variable t
//loop for the number of results found by getcategories.php
for (var i = 0; i < arr.length; i++) {
//add a new row
t.row.add([ //error
"<a href='#' class='ui-btn' id='btn" + arr[i].categoryID + "'>Category</a>" //add a new [Category] button
]).draw(false);
//We drew a [View] button. now bind it to some actions
$("#btn" + arr[i].categoryID).bind("click", { id: arr[i].categoryID }, function (event) {
var data = event.data;
showcategory(data.id); //when the user clicks on the [View] button, execute showcategory()
});
}
$("#categoryresult").show(); //show the results in the table searchresult
}
function showcategory(categoryID) {
//alert(categoryID);
window.location = "showuser.html?userid=" + userid;
}
});
There is an error on line 33 which stated:
"Uncaught TypeError: Cannot read property 'row' of undefined"
However, it seems that I have no idea where the error is coming from.
Is there anyway I can solve this problem?
You look like you are using a third-party jQuery plugin, DataTables.
Follow the usage of DataTables.
var t; //declare variable t
should be
var t = $("#categoryresult").DataTable();
The variable t is not an object with a property called row.
Try with var t = { row: [] }
Edit: I apologize. I got confused add with push method.
So, you need an object with a method called add and assign that object to t

How get a variable from HTML in JavaScript/Ajax Call

I'm using Zend Framework 2.
I would like to know how to get data defined in html in my javascript code.
html
<tr class="MyClass" data-MyData="<?php echo json_encode($array);?>">
javascript
$(document).on('click','.MyClass', function () {
var temp =document.getElementsByClassName("data-MyData");
$.ajax({
url: path_server + "pathDefinedInMyConfig",
type: 'post',
encode: true,
dataType: 'json',
data: {
'temp ': temp
},
success: function (data) {
//some code
},
error: function () {
alert("ERROR");
}
});
});
The problem is I don't have access to row in my Controller method. And i want to have access to My $array defined in html in my Controller.
Problem is that you are trying to find a class by the name data-MyData, but the object you "want" to look for is "MyClass"
Try something like var temp =document.getElementsByClassName("MyClass").attr("data-MyData");
Even better is that since you click on the object with MyClass you can use $(this).attr('data-MyData');
then result will look like: var temp = $(this).attr('data-MyData');
Simply replace temp var assignment line:
var temp =document.getElementsByClassName("data-MyData");
with this one:
var temp = this.getAttribute("data-MyData");
Since you use jQuery use the following:
$('.MyClass').data('MyData')
or
$('.MyClass').attr('data-MyData')
use like this-
$(document).on('click','.MyClass', function () {
var temp =$(this).attr('data-MyData');
$.ajax({
url: path_server + "pathDefinedInMyConfig",
type: 'post',
encode: true,
dataType: 'json',
data: {
'temp ': temp
},
success: function (data) {
//some code
},
error: function () {
alert("ERROR");
}
});});
You have a wrong selector. document.getElementsByClassNames() returns the collections so you have to loop through to get the target element:
var temp =document.getElementsByClassName('MyClass');
[].forEach.call(temp, function(el){
console.log(el.dataset['MyData']);
});
or as you are using jQuery then you can use .data():
var temp =$(this).data("MyData");
and with javascript:
var temp =this.dataset["MyData"];
// var temp =this.dataset.MyData; // <---this way too.

Edit image src with jQuery

I have one question I'm using this code for editing image src's thats creating js but its not working ...(after click on button jquery creating object and then this function will change src's in this created object )
that code where first creating objects and second will edit image src's
function addToplaylist(title)
{
/* some CODE */
var each = playlistts.join('</span><li><img class="plimg" src="/img/cover.png"><span onclick="playinToplaylist($(this).html());" class="titletrack">');
$("#playlist").html('<li><img onload="this.src = \'/img/playlist/\'+$(this).next(\'span.titletrack\').text()+\'.jpg\'" src="/img/cover.png"><span onclick="playinToplaylist($(this).html());" class="titletrack">' + each);
/* some CODE */
}
$(document).ready(function(){
$("body .plimg").attr("src",
function (index) {
var title = $(this).next('span.titletrack').text();
var array = title.split(' - ');
var track = array[0];
var artist = array[1];
var output;
$.ajax({ //instead of getJSON as the function does not allow configurations.
url: "http://ws.audioscrobbler.com/2.0/?method=track.search",
data: {
track: track,
artist: artist,
api_key: "ca86a16ce762065a423e20381ccfcdf0",
format: "json",
lang: "en",
limit: 1
},
async: false, //making the call synchronous
dataType: 'json', //specifying JSON type
success: function (data) {
output = data.results.trackmatches.track.image[0]["#text"];
}
});
return output;
});
});

Advice requested - passing variables between functions using json/jquery & ajax

I've looked over a lot of 'similar' q&a threads on SO but to be honest, as I don't have too much of a grip on js programming, I'm finding it difficult to make sense of a lot of the answers (as far as they may apply to my own situation).
The context is this, I have two php scripts one returning a list of customer_ids (json encoded) for a set period and the other returning their preferences for news feeds (json encoded).
I wrote the following, having googled a bit to get a basic understanding of how to setup an ajax function in jQuery:
$('document').ready(function() {
$.ajax({
type:'GET', url: 'cust_selection.php', data: '',
succes:function(cstmrid) {
var clistlen = cstmrid.length;
var i=0;
var cstmr;
for( ;cstmr=cstmrid[i++]; ) {
$('#adminPanel>ul>li').append("<a href='' onclick='alert("+cstmr+")' class='lst_admin basic'>"+cstmr+"</a>"); //alert to be replaced with a function call which passes customerid to the function below.
}
},
dataType:'json'
});
var cstmrid = "483972258"; //hardcoded for testing purposes
$.ajax({
type:'GET', url:'newsfpref.php?', data:'cref='+cstmrid,
success:function(npfdata) {
var item;
var n=0;
for( ;item=npfdata[n++]; ) {
var news = npfdata[n].nsource;
$('#adminMain>table>tbody').append("<tr><td>"+item+"</td></tr>");
}
},
dataType:'json'
});
});
Now from the first ajax function, I get a list of links which I want to be able to click to launch the second ajax function and pass it the customer id so that it can grab a list of the news sources that they've configured for their pages.
The alert and the hard-coded customer id both suggest that the functions are 'working', but when I try and adjust the first function so that:
...
$('#adminPanel>ul>li').append("<a href='' onclick='getCustomerNP("+cstmr+")' class='lst_admin basic'>"+cstmr+"</a>");
... is calling a modified version of the second function, as below:
...
function getCustomerNP(cstmrid) {
$.ajax({
type:'GET', url:'newsfpref.php?', data:'cref='+cstmrid,
success:function(nprfdata) {
var item;
var n=0;
for( ;item=npfdata[n++]; ) {
var news = npfdata[n].nsource;
$('#adminMain>table>tbody').append("<tr><td>"+item+"</td></tr>");
}
},
dataType:'json'
});
}
Everything seems to just fail at this point. The second function doesn't seem to 'receive' the variable and I'm not sure if it's something elementary that I've overlooked (like some muddled up " and ' placements) or if what I am trying to accomplish is actually not the way jQuery ajax functions interact with each other.
As you can see, I've cannibalised bits of code and ideas from many SO q&a threads, but copying without much of an understanding makes for a frustratingly dependent life.
I would appreciate as much - expansive - comment as you can provide, as well as a solution or two (naturally).
EDIT: Not to confuse anyone further, I've been modifying the above and correcting my (many) errors and typos along the way. At present, the code looks like below:
$('document').ready(function () {
$.ajax({
type: 'GET', url: 'cust_selection.php', data: '',
succes: function (cstmrid) {
var clistlen = cstmrid.length;
var i = 0;
var cstmr;
for (; cstmr = cstmrid[i++]; ) {
var a = $("<a href='' class='lst_admin basic'>" + cstmr + "</a>").click(function () {
getCustomerNP(cstmr)
})
$('#adminPanel>ul>li').append(a); //alert to be replaced with a function call which passes customerid to the function below.
}
},
dataType: 'json'
});
function getCustomerNP(cstmr) {
alert(cstmr);
}
});
You've got a typo in the $.ajax() success function within getCustomerNP(). The function declaration:
success:function(nprfdata) {
... has a parameter nprfdata, but then within the function you use npfdata (missing the r).
Also this code:
var item;
var n=0;
for( ;item=npfdata[n++]; ) {
var news = npfdata[n].nsource;
$('#adminMain>table>tbody').append("<tr><td>"+item+"</td></tr>");
}
...declares and sets variable news that you never use. And it doesn't seem right to increment n in the for test expression but then use n within the loop. You never set item to anything but you use it in your .append().
(Note also that JS doesn't have block scope, only function scope, so declaring variables inside an if or for loop doesn't limit them to that if or for block.)
I would not create inline onclick handlers like that. I'd probably do something more like this:
$('#adminPanel>ul>li').append("<a href='' data-cstmr='"+cstmr+"' class='lst_admin basic'>"+cstmr+"</a>");
...and then within the document ready setup a delegated event handler to catch the clicks on those anchors:
$('#adminPanel>ul>li').on('click', 'a.lst_admin', function() {
$.ajax({
type:'GET', url:'newsfpref.php?', data:'cref='+ $(this).attr('data-cstmr'),
success:function(npfdata) {
var item,
n=0,
// cache the jQuery object rather than reselecting on every iteration
$table = $('#adminMain>table>tbody');
// increment n only after the current iteration of the loop
for( ;item=npfdata[n]; n++) {
// change to use item
$table.append("<tr><td>"+item.nsource+"</td></tr>");
}
},
dataType:'json'
});
});
As you append your like with <a href='' onclick='getCustomerNP("+cstmr+")', Make sure you can access the function getCustomerNP.
Try to define getCustomerNP as
window.getCustomerNP = function(cstmrid) {
...
If you defined it in the $(document).ready(function(){ ... }) block, try this
$('document').ready(function () {
$.ajax({
type: 'GET', url: 'cust_selection.php', data: '',
succes: function (cstmrid) {
var clistlen = cstmrid.length;
var i = 0;
var cstmr;
for (; cstmr = cstmrid[i++]; ) {
var a = $("<a href='' class='lst_admin basic'>" + cstmr + "</a>").click(function () {
getCustomerNP(cstmr)
})
$('#adminPanel>ul>li').append(a); //alert to be replaced with a function call which passes customerid to the function below.
}
},
dataType: 'json'
});
function getCustomerNP(cstmrid) {
$.ajax({
type: 'GET', url: 'newsfpref.php?', data: 'cref=' + cstmrid,
success: function (nprfdata) {
var item;
var n = 0;
for (; item = npfdata[n++]; ) {
var news = npfdata[n].nsource;
$('#adminMain>table>tbody').append("<tr><td>" + item + "</td></tr>");
}
},
dataType: 'json'
});
}
});

Categories

Resources