Can't pass an array and a string into controller with JavaScript - javascript

I hope someone can help me with this issue that I have.
I'm trying to pass an array into controller with JavaScript like this:
$('#send') .lick(function () {
var items = {};
var grid = $('#grid') .ata('kendoGrid');
var selectedElements = grid .elect();
for (var j = 0; j < selectedElements .ength; j++) {
var item = grid .ataItem(selectedElements[j]);
items['grid[' + j + '] .arecidoCodigo'] = item .arecidoCodigo;
}
$ .jax({
type: "POST",
data: items,
url: '#Url .ction("Index", "Busqueda")',
success: function (result) {
console .og(result);
}
})
})
This works fine.
But when I tried to pass another value, in this case a string data, the array is sending null into the controller but the string value is not null.
This is my code when I tried to send another value, in this case the array and the string data:
$('#send') .lick(function () {
var items = {};
var grid = $('#grid') .ata('kendoGrid');
var selectedElements = grid .elect();
var enviarDest = $('#destinatario') .al();
for (var j = 0; j < selectedElements .ength; j++) {
var item = grid .ataItem(selectedElements[j]);
items['grid[' + j + '] .arecidoCodigo'] = item .arecidoCodigo;
}
var postData = { marcas: items, destinatario: enviarDest };
$ .jax({
type: "POST",
data: postData,
url: '#Url .ction("Index", "Busqueda")',
success: function (result) {
console .og(result);
}
})
})
And this is the code of my controller:
public async Task<ActionResult> Index(List<MarcaParecido> marcas, string destinatario)
{
..
}
Here is when I receive the list marcas null and the string destinatario is not null, I don't know what am I doing wrong.

Try using JsonResult instead of async in your controller:
public JsonResult Index(List<MarcaParecido> marcas, string destinatario)
{ .. }

Related

Replace string in text area with the value of ajax response

I have an ajax function that returns a shorturl of an url from a textarea.
When I want to replace the shorturl by the actual url in the text area by using replace, the code not work. this is my implementation
Ajax function:
function checkUrl(text) {
var bit_url = "";
var url = text;
var username = "o_1i42ajamkg"; // bit.ly username
var key = "R_359b9c5990a7488ba5e2b0ed541db820";
return $.ajax({
url: "http://api.bit.ly/v3/shorten",
data: {
longUrl: url,
apiKey: key,
login: username
},
dataType: "jsonp",
async: false,
success: function(v) {
bit_url = v.data.url;
}
});
}
and a function that call the checkurl function is implemented as follow
$("#urlr").change(function() {
var text = $("#Pushtype_message").val();
var c = "";
var msgtext = "";
var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
var MsgStr = $("#Pushtype_message").val();
var Arr = text.split(" ");
urllist = new Array();
urluri = new Array();
i = 0;
for (var n = 0; n < Arr.length; n++) {
txtStr = Arr[n];
var urltest = urlRegex.test(txtStr);
if (urltest) {
urllist[i] = txtStr;
}
}
for (var i = 0; i < urllist.length; i++) {
// console.log(urllist[i].toString());
checkUrl(urllist[i]).done(function(result) {
var response = (result.data.url);
console.log(response);
MsgStr.replace(urllist[i], response);
console.log(MsgStr);
$("#Pushtype_message").val(MsgStr);
});
}
});
In my text area I put this text:
test utl function https://www.google.Fr test success
and I get in my console the following result
main.js http://bit.****
main.js test utl function https://www.google.Fr test success
As you see, the function return an urlshortner but the initial text still the same. My expected result is: test utl function http://bit.l**** test success, but this don't work.
When working with textarea you can simply replace their text.
$("#Pushtype_message").text(MsgStr);
You need the assign the new value to MsgStr
for(var i=0; i<urllist.length; i++){
// console.log(urllist[i].toString());
checkUrl(urllist[i]).done(function(result){
var response=(result.data.url);
console.log(response);
MsgStr = MsgStr.replace(urllist[i],response);
console.log(MsgStr);
$("#Pushtype_message").val(MsgStr);
});
}
i is defined outside your for loop and used inside it urllist[i]=txtStr; but its value is never assigned, it's alaways = 0:
i=0;
for (var n = 0; n < Arr.length; n++) {
txtStr = Arr[n];
var urltest=urlRegex.test(txtStr);
if(urltest)
{
urllist[i]=txtStr;
}
}
I found the solution about my problem,
I affect urllist[j] to a new variable text, because in the checklist function urllist[j] return an undefined value.
var j=0;
for(j; j<urllist.length; j++){
var text=urllist[j];
checkUrl(urllist[j]).done(function(result){
var response=result.data.url;
console.log(urllist[j]);
MsgStr1 = MsgStr.replace(text,response);
console.log(MsgStr1);
$("#Pushtype_message").val(MsgStr1);
});
}
});

Uncaught TypeError: Cannot read property 'HotelInfo' of undefined

//an ajax call to the api
jQuery(document).ready(function() {
jQuery.ajax({
url:"http://localhost:8080/activitiesWithRealData?location=%22SEA%22&startDate=%2205-14-16%22&endDate=%2205-16-16%22&theme=%22food%22",
dataType: 'JSON', type: 'GET',
success: function (data)
var viewModel;
if(data) {
viewModel = new dealsPageModel(data);
var idList = "";
for (var i = 0; i< data.packageDeal.length; i++)
{
if (i == data.packageDeal.length -1)
{ idList += data.packageDeal[i].hotelId;
}
else
{idList += data.packageDeal[i].hotelId + ',';
}
}
var searchUrl = "http://terminal2.expedia.com/x/hotels?hotelids=" + idList + "&apikey=6weV4ksGIJ5eQhd58o2XTDwVo35lZf2S";
//another call to another api to return hotel specific info
jQuery.get(searchUrl, function ( )
{
for(var i=0; i<viewModel.dealList.length; i++)
{
var hotelId = viewModel.dealList[i].hotelId;
for(var i=0; i<data.HotelInfoList.HotelInfo.length; i++)
{
var url = HotelInfoList.HotelInfo[i].ThumbnailUrl;
var name = HotelInfoList.HotelInfo[i].Name;
}
// Get the hotelid from the current deal
// Loop through the hotelinfolist.hotelInfo and find out the url for the hotel idList
//Loop through the hotelinfolist.hotelInfo and find out the name for the hotel
viewModel.dealList.push(new deal(data.packageDeal[i], url, name));
}
ko.applyBindings(viewModel);
});
}
}
})
});
You loop through data.HotelInfoList.HotelInfo but operate on HotelInfoList.HotelInfo[i].ThumbnailUrl. The data. at the beginning is missing.
Also, place data in the callback function in jQuery.get:
jQuery.get(searchUrl, function(data){
// …
your data is in data.HotelInfoList not in HotelInfoList
your loop should be like this
for(var i=0; i<data.HotelInfoList.HotelInfo.length; i++)
{
var url = data.HotelInfoList.HotelInfo[i].ThumbnailUrl;
var name = data.HotelInfoList.HotelInfo[i].Name;
}

jQuery filter result

I need your help. I get hash tags data from Tumblr via ajax and I loop through them to output them. Before I output the tags I want to do some filtering, and in the output if I have 4 of the same hash tag I need to only output it once.
Here is an example where without the filtering.
jsFiddle
$.ajax({
url: "http://api.tumblr.com/v2/blog/testhermes.tumblr.com/posts",
dataType: 'jsonp',
data: {
api_key : "d01TZzpbq12cD7Zv7dM4EwLndkAAIEsExnLl9PNvsHYuyuDwKq"
},
success: function(results){
var posts = results.response.posts;
var text ='';
for (var i in posts)
{
p = posts[i];
a = p.tags;
for(var j in a) {
c = a[j];
text += ''+ c +'<br>';
$("body").append(text);
}
}
}
});
thank you
You just have to hold value in array and check every time you insert item whether it exist in array or not.
$.ajax({
url: "http://api.tumblr.com/v2/blog/testhermes.tumblr.com/posts",
dataType: 'jsonp',
data: {
api_key : "d01TZzpbq12cD7Zv7dM4EwLndkAAIEsExnLl9PNvsHYuyuDwKq"
},
success: function(results){
var posts = results.response.posts;
var text ='';
var arr = [];
for (var i in posts)
{
p = posts[i];
a = p.tags;
for(var j in a) {
c = $.trim(a[j]);
if(jQuery.inArray(c, arr) == -1)
{
arr.push(c);
var text = ''+ c +'<br>';
$("body").append(text);
}
}
}
}
});
Here is JS FIDDLE link.
Simply keep track of tags you've already seen in an object, then only output the link if you haven't seen the tag before.
var seen_tags = {};
for (var i in posts)
{
p = posts[i];
a = p.tags;
for(var j in a) {
c = a[j];
if(!(c in seen_tags)) {
text += ''+ c +'<br>';
$("body").append(text);
seen_tags[c] = true;
}
}
}

CSV-import via jquery - variable locked in

i use a nice code to import csv data.
However, my variable seems to be somehow caught within the function so i cannot access it from other places in my .js ...
see my two alert functions in the code below.
Code copied from post(How to read data From *.CSV file using javascript?)
$(document).ready(function () {
$.ajax({
type: "GET",
url: "../recipes.csv",
dataType: "text",
success: function (data) {
processData(data);
}
});
});
function processData(allText) {
var allTextLines = allText.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
var lines = [];
for (var i = 0; i < allTextLines.length; i++) {
var data = allTextLines[i].split(',');
if (data.length == headers.length) {
var tarr = [];
for (var j = 0; j < headers.length; j++) {
tarr.push(data[j]);
}
lines.push(tarr);
}
}
dataArray = (lines + "").split(';');
alert(dataArray[1]); // here it works
}
alert(dataArray[1]); // here it doesn't work: "ReferenceError: dataArray is not defined"
The dataArray variable that the function processData(...) uses exists only inside the function.
In order to use it outside the function you need to declare it. For example:
var dataArray = {};
function processData(allText) {
var allTextLines = allText.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
var lines = [];
for (var i=0; i<allTextLines.length; i++) {
var data = allTextLines[i].split(',');
if (data.length == headers.length) {
var tarr = [];
for (var j=0; j<headers.length; j++) {
tarr.push(data[j]);
}
lines.push(tarr);
}
}
dataArray = (lines + "").split(';');
alert(dataArray[1]);
}
$(document).ready(function () {
$.ajax({
type: "GET",
url: "../recipes.csv",
dataType: "text",
success: function (data) {
processData(data);
alert(dataArray[1]); // here it will return the data from processData(...)
}
});
});
What is the scope of variables in JavaScript?. Here is an interesting thread for variable scope in JavaScript.

jquery problem in IE with dynamic dropdown selection

Hi jquery/javascript gurus,
I am trying to use jquery ajax function to populate the dropdown, it works fine with FF, but IE give the javascript error snow below in the scrnshot. howver IE does get the data and selects it.
Am i doing something wrong?
function getAjaxFunction(thisval, curval) {
$.ajax({
type: "POST",
url: "lookup.do?param="+thisval,
cache: false,
success: function(data) {
var values = data;
var vals = values.split(";");
$("#dropdown").find("option").remove().end();
for (var i = 0; i < vals.length; i++) {
var parts = vals[i].split(":");
$("#dropdown").append($('<option />').val(parts[0]).text(parts[1]));
}
$("#dropdown").val(curval);
}
});
}
You say val(curval) at the end of your function, but your function parameter is named currval with two Rs.
This worked!
function getAjaxFunction(thisval, curval) {
$.ajax({
type: "POST",
url: "lookup.do?param="+thisval,
cache: false,
success: function(data) {
var values = data;
var vals = values.split(";");
$("#dropdown").find("option").remove().end();
for (var i = 0; i < vals.length; i++) {
var parts = vals[i].split(":");
$("#dropdown").append($('<option />').val(parts[0]).text(parts[1]));
}
try {
$("#dropdown").val(curval);
} catch(ex) {
setTimeout("$('#dropdown').val('"+curval+"')",1);
}
}
});
}

Categories