Getting null value to controller's action passing from javascript using jquery - javascript

What I tried in my project is like passing checkbox's selected value as a comma separated string to json of my controller.. but i'm not getting a value to the json action.. it shows null over there.
How can I do this? Please help me
function getIds(checkList)
{
var idList = new Array();
var loopCounter = 0;
jQuery("input[name=" + checkList + "]:checked").each
(
function()
{
idList[loopCounter] = jQuery(this).val();
loopCounter += 1;
}
);
alert(idList);
jQuery.getJSON("/Photos/CheckForIdsJson", { idList: idList });
}
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult CheckForIdsJson(Int32[] idList)
{
JsonResult result = new JsonResult();
result.Data = idList;
return result;
}

You can have a look at this post : AJAX Post of JavaScript String Array to JsonResult as List<string> Always Returns Null? or this one : Send list/array as parameter with jQuery getJson . It seems that you have to indicate traditional: true in your ajax call.

Use this in your script :
var did ='',
$("#tbl").find("input:checkbox").each(function (i) {
if (this.checked == true) {
did += $(this).val() + ",";
}
});
alert(did);
if (did == "") {
alert("Please Select");
return;
}

Related

JSON array to and from MySql. Saving and Looping

<?
$cl = $row["saved_json_string_column"];
?>
expecting this output from the db query to create a new array
//cl = '[{"ifeid":1,"ans":"Yes","type":"SkipTo","target":"2"},{"ifeid":2,"ans":"Yes","type":"SkipTo","target":"5"}]';
cl = '<? echo $cl;?>';
// I would like to start with the saved 'cl' array and push new items to it.
skptoQarry = new Array();
//javascript function loop (not shown) generates vars and pushes to new array.
thisItem_eid = 1;
yes_no_is_this = 'No';
SkipToTartgetEID = 5;
var skptoQarry_temp = {
"ifeid" : thisItem_eid,
"ans" : yes_no_is_this,
"type" : "SkipTo",
"target" : SkipToTartgetEID
};
skptoQarry.push(skptoQarry_temp);
cl = JSON.stringify(skptoQarry); //for ajax post to php for saving
//this is what is in saved the DB via ajax post
[{"ifeid":1,"ans":"Yes","type":"SkipTo","target":"2"},{"ifeid":2,"ans":"Yes","type":"SkipTo","target":"5"}]
//...but when PHP echos it out only this comes out: cl = "[,]"
// I think i'm saving it wrong or echoing the column data the wrong way.
//read text from mysql and append where needed.
cl = $.parseJSON(cl);
jQuery.each(cl, function (i) {
jQuery.each(this, function (key, value) {
if (key == "ifeid") {
$('div').append('if this id: '+value+'<br>');
} else if (key == "ans") {
$('div').append('is: '+value+'<br>');
} else if (key == "type") {
$('div').append('then: '+value+'<br>');
} else if (key == "target") {
$('div').append('this id: '+value+'<br><br>');
}
});
});
function saveit(){
saved_logic_dialog = JSON.stringify(skptoQarry);
var posturl = "myurl?event=save&saved_logic_dialog="+saved_logic_dialog;
jQuery.ajax({
traditional: true,
type: "POST",
url: posturl,
success: function(data) {
//messages and stuff
}
});
}
//php
$loadvfsql = "SELECT `saved_logic_dialog` FROM `questions` WHERE `id` = '{$id}' ORDER BY `questions`.`question_order` ASC";
$loadv_result=mysql_query($loadvfsql);
while($rows=mysql_fetch_array($loadv_result)){
$clc = $rows['current_logic_cont'];
$cl = $rows['saved_logic_dialog'];
//more stuff
}
This will ensure your array of objects is properly encoded - jQuery will not encode the URL for you.
var posturl = "myurl?event=save&saved_logic_dialog=" + encodeURIComponent(saved_logic_dialog);
When saving to DB - check for properly escaping the value (as it will certainly contain quotes);
When echoing the value back into HTML - use htmlspecialchars($cl) to properly escape the symbols which might have special meaning in HTML.
Before using the value in JavaScript - use JSON.parse(cl) to convert from String into Array.

Custom attr() method cannot be given a different name

I have the following perfectly working code (written by someone else). The problem is that if I simply rename the attr method, I get an error. For example, I rename the method to attrx and get this error:
TypeError: arg.attrx is not a function
Here is the working code:
function Action(name) {
this.attr = function(n) {
if (n=="name") {
return "action";
}
},
this.val = function() {
return name;
};
}
Action.prototype.toString = function() {
return "&" + this.attr("name") + "=" + this.val();
}
When a user triggers an event, the following function is called:
function serializeElements() {
var result = "";
for(var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
result += (arg.attr("name") + "=" + arg.val() + "&");
}
return result;
}
Here is the identical code above but it has the attr method renamed to attrx:
function Action(name) {
this.attrx = function(n) {
if (n=="name") {
return "action";
}
},
this.val = function() {
return name;
};
}
Action.prototype.toString = function() {
return "&" + this.attrx("name") + "=" + this.val();
}
function serializeElements() {
var result = "";
for(var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
result += (arg.attrx("name") + "=" + arg.val() + "&");
}
return result;
}
I cannot figure out the reason that the code does not work (see error at top of message) after I rename the method to attrx or anything else for that matter.
Note: The web page does include jQuery, but I don't think that is what causes the problem.
Here is the code used to call serializeElements:
function addStatesListener() {
$("#states").on("change", function(e) {
var form = $(this.form);
var url = form.attr("action");
var type = form.attr("method");
// pass 1) jQuery 'country' and 'state' objects and 2) a query string fragment, e.g.: '&action=change_state'
var data = serializeElements($("#countries"), $("#states"), new Action("change_state"));
e.preventDefault();
$.ajax({
url: url,
type: type,
data: data,
dataType: "html", // The type of data that you're expecting back from the server
success: function(result) {
$("#cities").html(result); // list of all cities, e.g.: <option value="Albany"</option>
}
});
});
}
The proper answer to your question is want already catch #dinesh, you are passing 3 arguments to your function, and only the third is an Action with the .attrx method you changed.
Considering you are working on jquery objects, and if you want to clean your code, you could use .serialize() method instead of calling the couple .attr() and .val().
.serialize() is the jquery method to serialize form objects.
So you can change your code as follow:
function Action(name) {
this.serialize=function() {
return 'name='+encodeURI(name);
}
}
And then your function serializeElements:
function serializeElements() {
var args = Array.prototype.slice.call(arguments);
return args.reduce(function(a, b){
if (a) return a.serialize() + '&' + b.serialize();
if (b) return b.serialize();
});
}
Then you can call it so:
var data = serializeElements($("#countries,#states"), new Action("change_state"));
As you see, you could put form elements in a comma separated list on jquery selector.
That's it.

Send single item of list from view to controller via AJAX

I have a view composed of a list of users:
#model List<LabelPrinting.Models.UserModel>
and I put these into a JavaScript object:
users = function () { return #Html.Raw(Json.Encode(Model)) }();
I then load a jQuery accordion with the values for each. I then choose to print avery labels for a particular user in the list and set a value. I'm trying to send only that particular user to the controller and am getting a null values for of the user properties:
function PrintAveryLabel(but) {
var id = but.id.substring(9);
var $rad = $(but).closest('tr').siblings().find('.radLabelOther');
if (($rad).is(':checked')) {
var $txtr = $rad.closest('tr').siblings().find('.classRows');
var $txtc = $rad.closest('tr').siblings().find('.classCols');
if ($txtr.val() === "0" || $txtc.val() === "0") {
$("#lblError").text("You have have not selected the rows and columns for the labels.");
$("#MessageDialog").dialog({ title: "Select Rows/Columns" });
$("#MessageDialog").dialog("open");
return false;
}
}
var data = findUser(id);
$.ajax({
type: 'POST',
data: { pat: data },
url: '#Url.Action("PrintUserLabels")'
});
}
The findUser function simply picks the entry in the list that matches the ID.
function findUser(id) {
var data;
for (i = 0; i < cnt; i++) {
if (users[i].UserId === parseInt(id)) {
data = users[i];
break;
}
}
return data;
}
My controller action:
[HttpPost]
public ActionResult PrintUserLabels(UserModel pat)
{
string retval = "";
if (pat.PrintLabel)
{
return RedirectToAction("Label", new { user = pat });
}
else
{
retval = "ERROR - you must make a selection";
Exception e = new Exception(retval);
HandleErrorInfo info = new HandleErrorInfo(e, "DYMO", "PrintPatientLabels");
return RedirectToAction("Error", info);
}
}
The label action is tried and true but I get a null user model. What am I doing wrong?

Convert nested form fields to JSON in Jquery

Trying to do POST of Form object as JSON from front end javacsript/jquery to Spring MVC backend.
Form data has a string array and other string field, looks like below
...
var cityList = [];
citylist.push("SF");
citylist.push("LA");
document.forms["myForm"]["dstCities"].value = cityList;
document.forms["myForm"]["dstState"].value = "CA";
...
Below is my code for converting to JSON,
function convertFormToJSON(){
var jsonObject = {};
var array = $("myForm").serializeArray();
$.each(array, function() {
if (jsonObject[this.name] !== undefined) {
jsonObject[this.name].push(this.value || '');
} else {
jsonObject[this.name] = this.value || '';
}
});
jsonObject = JSON.stringify(jsonObject);
console.log("json: " + jsonObject);
return jsonObject;
};
POST call:
$.ajax({
url: "xxx",
type: "POST",
data: convertFormToJSON(),
contentType: "application/json",
dataType: 'json',
...
});
Json output:
{"dstCities":"SF,LA", "dstState":"CA"}
But I need it to look like
[{"dstCities": ["SF", "LA"], "dstState":"CA"}]
You are passing an array as value to :
document.forms["myForm"]["dstCities"].value = cityList;
but the browser is using toString() on it and it ends up as joined string "SF,LA"
If the intent is to pass it as string array can do:
document.forms["myForm"]["dstCities"].value = JSON.stringify(cityList);
No changes would be needed in convertFormToJSON this way.
If the cities need to be displayed as comma separated values then change
if (jsonObject[this.name] !== undefined) {
jsonObject[this.name].push(this.value || '');
} else {
var value = this.value;
if (this.name === 'dstCities') {
value = value.split(',');
}
jsonObject[this.name] = value || '';
}

spring mvc error ajax [object Object] when return #ResponseBody Map

I want to do a concatenated combobox, for that I am using ajax and javascript in the view, the problem is that the controller receives the data and capture me the result but when returned kicks me error can not return Map, I'm using spring mvc.
I already have 2 libraries of json, that's not the problem I think ..
JSP
....
jQuery(document).ready(function() {
var contexPath = "<%=request.getContextPath()%>";
$('#anios').change(
function(e){
if(jQuery(this).val() != "-1"){
$('#eventos').find('option').remove().end().append(
'<option value="-1">--Select state--</option>');
e.preventDefault();
var val = $(this).val();
jQuery("#eventos").removeAttr("disabled");
alert(val);
//$('#othstate').val('').hide();
$.ajax({
type : "POST",
url : contexPath + '/eventosPublicados.html',
dataType : 'json',
data : {
idAnio : val
}, success : function(data){
//alert(data.lstEventos);
//showEventos(data.lstEventos);
// $('#states').html( data.lstStates );
}, error : function(e) {
alert('Error: '+ e);
}
});
} else {
$("#eventos").attr("disabled", "disabled");
$('#eventos').find('option').remove().end().append(
'<option value="-1">--- Seleccione ---</option>');
}
});
function showEventos(data) {
for (var i = 0, len = data.length; i < len; ++i) {
var msajax = data[i];
$('#eventos').append(
"<option value=\"" +msajax.idEvento + "\">" + msajax.nombre + "</option>");
}
}
});
</script>
..
Controller
#RequestMapping(value= "/eventosPublicados", headers = "Accept=application/json,application/xml")
public #ResponseBody Map<String, ? extends Object> listaEventosPublicados(#RequestParam(value="idAnio", required=true) String anio) throws Exception{
Map<String,Object> model = new HashMap<String, Object>();
List<Evento> eventos = this.eventoService.obtenerEventosPublicadosxAnio(Integer.parseInt(anio));
System.out.println("evento size: " + eventos.size());
model.put("lstEventos", eventos);
return model;
}
If I retrieve the data from the list, which means that if the value "anio" arrives, the problem is to return.
Help me pls
Are you trying like this? where do you parse "eventos" to json?
#RequestMapping(value= "/eventosPublicados", headers = "Accept=application/json,application/xml")
#ResponseBody
public String listaEventosPublicados (#RequestParam(value="idAnio", required=true) String anio)){
// ..... Parsing "eventos" to json
}
To parse json https://code.google.com/p/google-gson/ will be useful

Categories

Resources