Remove or escape double quotes - javascript

I'm trying to store items in localStorage; here is my function:
function AddToCart(varer) {
var users = JSON.parse(localStorage.getItem("users") || "[]");
users.push(varer);
console.log(varer);
localStorage.setItem("users", JSON.stringify(users));
}
And result will be in under Application Tab :
And then I'm trying Looping through localStorage and send data to controller:
var holderHTML = '';
var params = "";
var seperator = "";
var info = JSON.parse(localStorage.getItem("users"));
for (var i = 0; i < info.length; i++) {
var Val = info[i];
var key = JSON.stringify(Val)
params += seperator + "items=" + key;
seperator = "&";
}
$.ajax({
type: "GET",
url: "/User/serializeItemsLine",
data: params,
dataType: 'json',
success: function (values) {
console.log(values);
}
})
But the data I'm trying to send contains double quotes (decoded %22) and because of that my action couldn't retrieve data:
Request URL: http://localhost:xxxx/User/serializeItemsLine?items=%22ae90ac1a-64c4-49a7-b588-ae6b69a37d47%22&items=%223e58aa74-4585-4bee-b2e0-ed39a1d95442%22
Query string parameters :
items: "ae90ac1a-64c4-49a7-b588-ae6b69a37d47"
items: "3e58aa74-4585-4bee-b2e0-ed39a1d95442"
Decoded results:
items: %22ae90ac1a-64c4-49a7-b588-ae6b69a37d47%22
items: %223e58aa74-4585-4bee-b2e0-ed39a1d95442%22
Action:
[HttpGet]
public string serializeItemsLine(Guid[] items) {
}

Try doing it this way: + "items=" + Val.
There is no need here to call JSON.stringify(). Your API isn't expecting JSON, so you shouldn't feed it JSON.

Related

View is not passing the model to controller - ASP.Net MVC

This is a basic passing of values from view to controller, but this does not seek to work.When I click the update button that functions to update the record in the database, the values from view, does not correctly pass the values to controller. Upon putting debugger in the javascript, the each variables were able to correctly got its values and evn the object where they are stored.
What could possible the reason for this problem?
here's the button onclick event code in Javascript.
$('#updatePrescription').click(function () {
debugger;
ValidateFields();
var drugListIsEmpty = CheckDrugList();
var error = $(".text-danger").length;
if (error == 0 && !drugListIsEmpty) {
debugger;
var prescription = [];
var template = {};
template.templateName = $("#prescriptionTemplateName").val();
template.templateTypeId = $('input[name=templateTypeId]:checked').val();
template.prescriptionTemplateItemList = [];
template.instructionId = $('.instruction').val();
template.frequencyId = $('.frequency').val();
template.day = $('.inputDays').val();
template.quantity = $('.inputQuantity').val();
template.dispenseLocationId = $('.selectDispenseLocation').val();
template.statusId = $('.status').val();
//template.categoryId = $('.templateCategory').filter(":visible").last().val();
template.templateId = $('#prescriptionTemplateId').val();
//if (template.categoryId == null) {
// template.categoryId = 0;
//}
var x = 0;
$('#tblPrescriptionSaveTemplateBody tr').each(function (key, value) {
debugger;
var row = $(this).closest('tr');
var next_row = $(row).next();
var drugId = $(value).find('.drugId').val();
var dosage = $(value).find('.inputDosage').val();
var dosageUnitId = $(value).find('.selectUnitId').val();
var statusId = "41";
var remarks = $(value).find('.inputDescription').val();
var groupId = $(value).find('.inputGroupNo').val();
var unit = $(value).find('.selectUnitId').val();
var prescriptionTemplateItemId = $(value).find('.prescriptionTemplateItemId').val();
x++;
var obj = {
// templateId: prescriptionTemplateId,
prescriptionTemplateId: template.templateId,
prescriptionTemplateItemId: prescriptionTemplateItemId,
drugId: drugId,
dosage: dosage,
dosageUnitId: dosageUnitId,
instructionId: template.instructionId,
frequencyId: template.frequencyId,
day: template.day,
quanitity: template.quantity,
unit: unit,
remarks: remarks,
dispenseLocationId: template.dispenseLocationId,
groupId: groupId,
statusId: template.statusId
}
template.prescriptionTemplateItemList.push(obj);
//prescription.push(obj)
})
$.ajax({
type: 'POST',
url: '/WestMedicinePrescriptionTemplate/UpdateTemplate',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(template),
success: function (data) {
ShowNotificationMessage(data.notification);
window.location.href = '/WestMedicinePrescriptionTemplate/Index';
}
});
}
});
This is expected to pass the result of model in parameter "newtemplate" in the controller, but it results to null
public ActionResult UpdateTemplate([FromBody] PrescriptionTemplateVM newtemplate)
{
int empId = Convert.ToInt32(HttpContext.Session.GetInt32("EmployeeId"));
var notif = "Update Failed.";
try
{
if (ModelState.IsValid)
{
bool updateSuccessful = _prescription.UpdatePrescriptionTemplateAndItems(newtemplate, empId);
if (updateSuccessful)
{
notif = "Update Successful.";
}
}
}
catch (Exception ex)
{
notif = ex.Message;
}
return Json(new { notification = notif });
}
What could be the problem in the code
do like this:
[HttpPost]
public ActionResult UpdateTemplate(PrescriptionTemplateVM newtemplate)
You need to make sure that you are using the same variables names that you defined in PrescriptionTemplateVM
and dont convert the data to Json. do like this:
$.ajax({
type: 'POST',
url: '/WestMedicinePrescriptionTemplate/UpdateTemplate',
dataType: 'json',
contentType: 'application/json',
data: {newtemplate: template},
success: function (data) {
ShowNotificationMessage(data.notification);
window.location.href =
'/WestMedicinePrescriptionTemplate/Index';
}
});

Url.Action error dont exist object

I have Script
$(function() {
$.support.cors = true;
jQuery.support.cors = true;
$.ajax({
crossDomain: true,
type: 'GET',
url: 'http://example.com/WCFRESTService.svc/GetCategories',
success: function(result) {
var s = '';
for (var i = 0; i < result.length; i++) {
s += '<br>' + result[i]["Name_Category"] + '';
$('#content').html(s);
}
}
});
});
The Url.Action Gives an error on result[i]["Categories_id"].
The name "result" does not exist int the current context
How do I transfer to my object result?
You can't pass JavaScript(Client Side) variable to Url.Action as it is processed at the Server-Side.
As a workaround, you can use placeholder to generate the url. Then use .replace() method to generate the actual url.
var s = '';
//Generate a variable with URL
var url = '#Url.Action("GetAnn", "Home", new { categories_id = -1})';
for (var i = 0; i < result.length; i++) {
s += '<br>' + result[i]["Name_Category"] + '';
$('#content').html(s);
}

getting "undefined" when i print json array with js

I want to parse json array it came down from json.jsp, but when i access parse.js it displays undefined
Here is parse.js
$(document).ready(function() {
$('#login').click(function(event) {
$.get('json.jsp', {
}, function(responseText) {
var myJSONObject1 = responseText;
var myJSONObject = JSON.parse(myJSONObject1);
var len = myJSONObject.length;
var out = "";
for (var i = 0; i < len; i++) {
var student = myJSONObject[i];
out += "<li>"+student.ircEvent + "<li>" + student.method+"<li>"+student.regex;
}
document.getElementById("ajaxResponse").innerHTML = out;
});
});
});
and my json.jsp is,
<%
response.setContentType("plain/text");
User user = new User("RAM","ram#gmail.com");
User user1 = new User("Ravi","ravi#gmail.com");
User user2 = new User("Raghu","raghu#gmail.com");
List list = new ArrayList();
list.add(user);list.add(user1);list.add(user2);
String json = new Gson().toJson(list);
response.getWriter().write(json);
%>
when i access parse.js file, it displays undefined
any ideas......
Just use $.ajax and set the dataType to json. No need to parse anything. jQuery does it for you. http://api.jquery.com/jquery.ajax/
jQuery(document).ready(function($) {
$.ajax({
url: 'json.jsp',
type: 'get',
dataType: 'json',
success: function(data) {
if (data.length) {
var ajaxResponse = document.createElement('table'),
tbody = document.createElement('tbody');
for (var i in data) {
if (data.hasOwnProperty(i)) {
var tr = document.createElement('tr'),
key = document.createElement('td'),
keyText = document.createTextNode(i),
value = document.createElement('td'),
valueText = document.createTextNode(data[i]);
key.appendChild(keyText);
tr.appendChild(key);
value.appendChild(valueText);
tr.appendChild(value);
tbody.appendChild(tr);
}
}
ajaxResponse.appendChild(tbody);
$("#ajaxResponse").append(ajaxResponse);
}
else alert("No data returned!");
}
});
});

How to create a JSON feed

I have a file called parsing.html that parses through a xml feed and converts the metadata into JSON Object called "data". I'm trying to output this JSON "data" as a JSON feed such as http://www.videws.com/gtv/videosources.php. Is doing
document.write(JSON.stringify(data)) the equivalent of creating a JSON feed in this case?
$.ajax({
type: 'GET',
url: 'fakeFeed.xml',
dataType: 'xml',
async: false,
success: function(data, textStatus, jqXHR) {
function getRandom(max) {
return Math.floor(Math.random() * max);
}
function getThumbId(small) {
var num = getRandom(15);
if (num == 0) {
num = 1;
}
if (num < 10) {
num = '0' + num;
}
return num.toString();
}
var categories = new Array(); // Array for the categories
var category = {
name : '',
videos: []
};
var data1 = data;
var data = {
categories: []
};
$(data1).find('item').each(function () {
var el = $(this);
var categoryName = el.find('category').text();
var p = categories.indexOf(categoryName);
if( p == -1) {
categories.push(categoryName);
var category = {
name: categoryName,
videos: []
};
for (var j = 0; j<5; j++) {
var video = {
sources: [el.find('media\\:content, content').attr('url')],
thumb : 'images\/thumbs\/thumb' + getThumbId() + '.jpg',
title : el.find("title").text(),
subtitle : el.find("description").text(),
description: ""
}
//document.write(categories);
category.videos.push(video);
}
data.categories.push(category);
}
});
document.write(JSON.stringify(data));
}
})
im not sure you fully understand what http://www.videws.com/gtv/videosources.php is doing.
if you look at the source code it appears not to have any javascript at all so its not doing a document.write, it is more likely doing all of the conversion to JSON within PHP server side then streaming out.
a good help site for using PHP with JSON is available here: http://www.tutorialspoint.com/json/json_php_example.htm
i would say that if your more of a JS/HTML guru you may get more out of NODEJS than PHP but that's entirely up to you.

Url.Action Passing string array from View to Controller in MVC#

I have a method that returns an array (string[]) and I'm trying to pass this array of strings into an Action.Currently I can't pass my parameters. I am new in MVC3.
Pls let me know why I can't pass parameter to ActionResult..I already define ActionResult with Same parameter name..
thanks all in advance....
$('#export-button').click(function () {
var columnLength = $("#grid")[0].p.colNames.length;
var columnNames = "";
for (var i = 0; i < columnLength; i++) {
if ($("#grid")[0].p.colModel[i].hidden == false) {
columnNames = columnNames + $("#grid")[0].p.colModel[i].name + ',';
}
}
var Val1 = jQuery(txt_search1).val();
alert(Val1); alert(columnNames);
document.location = '#Url.Action("OrgDataExport","Search", new { Val1 = Val1 , columnNames = columnNames})';
});
Try this,
$('#export-button').click(function () {
var columnLength = $("#grid")[0].p.colNames.length;
// columnNames is an object now
var columnNames = {};
for (var i = 0; i < columnLength; i++) {
if ($("#grid")[0].p.colModel[i].hidden == false) {
columnNames[i] = $("#grid")[0].p.colModel[i].name;
}
}
var Val1 = jQuery(txt_search1).val();
document.location = "Home/Index/" + $.param({ Val1 = Val1 , columnNames = columnNames });
});
Your action that takes columnNames as a string array
public ActionResult Index(string val1, string[] columnNames)
{
// Your code
}
UPDATE:
If the URL becomes too big you can submit the values through form using POST method. If your view already have a form use that else create a dynamic one on the fly and submit the values through POST.
$('#export-button').click(function () {
var Val1 = jQuery(txt_search1).val();
$("#hidden-form").remove();
// create a form dynamically
var form = $('<form>')
.attr({ id: "hidden-form",
action: "/Home/Index",
method: "post",
style: "display: none;"
})
.appendTo("body");
// add the "Val1" as hidden field to the form.
$('<input>').attr({ name: "Val1 ", value: Val1, type: "hidden" }).appendTo(form);
var columnLength = $("#grid")[0].p.colNames.length;
// add the "columnNames" as hidden fields to the form
for (var i = 0; i < columnLength; i++) {
if ($("#grid")[0].p.colModel[i].hidden == false) {
var t = $("#grid")[0].p.colModel[i].name;
$('<input>').attr({ name: "columnNames", value: t, type: "hidden"
}).appendTo(form);
}
};
// submit the form
form.submit();
});
for (var i = 0; i < columnLength; i++) {
if ($("#grid")[0].p.colModel[i].hidden == false) {
columnNames = columnNames + $("#grid")[0].p.colModel[i].name + ',';
}
}
var Val1 = jQuery(txt_search1).val();
alert(Val1); alert(columnNames);
document.location = '#Url.Action("OrgDataExport","Search", new { Val1 = Val1 , columnNames = columnNames})';
Hi Louis,
Your are trying to access javascript varaibles Val1 and columnNames from the server side tag and it is not possible. For more details, please refer this URL.
You can do it by following way.
var jsonData = { val1 : Val1, columnNames : columnNames };
$.ajax({
type: "GET", //GET or POST or PUT or DELETE verb
url: "Home/Index", // Location of the service
data: jsonData,
contentType: "application/json; charset=utf-8", // content type sent to server
processdata: true, //True or False
success: function () {
alert("success")
}
});
On your controller side you have to write like
public ActionResult Index(string val1, string columnNames)
{
// Your code
}
You tagged JQuery-Ajax but i don't see any ajax attempt in the code example? So i am guessing you want to know an Ajax orientated solution. You're probably not using Zend Framework, but i hope this answers helps point you in the right direction to a solution.
From JS/Zend framework experience you could look at something like
$('#export-button').click(function () {
....
var actionUrl= "/controller/action/";
$.ajax({
url: actionUrl,
data: {
variable1: "OrgDataExport",
variable2: "Search",
Val1: Val1,
columnNames: columnNames
},
dataType: "json",
success: function(json) {
//do stuff
}
});
....
});
In the ZendFramework controller you can then grab the variables on the request:
$Val1 = $this->_request->getparam("Val1");

Categories

Resources