Parse JSON string to use in AJAX success call - javascript

I have code that generates a JSON string. An example string that is generated by that code is as follows. I have validated it through the JSON lint tool and it validates perfectly.
{"ShipToName" : "( ) CARPINTERIA CA", "ShipToAddress1" : "3785 SANTA CLAUS LANE", "ShipToAddress2" : "", "ShipToCity" : "CARPINTERIA", "ShipToState" : "CA", "ShipToZip" : "93013", "ShipVia" : "UPS", "Terms" : "01", "SalesRep" : "KV1" }
I then have some JQuery that is going to parse that string. Right now I am just trying to alert one of the parts of the string to be sure the code is working correctly. I have tried both of the following with no success:
Attempt #1: Alerts 'undefined'
function hidShipTo_IndexChanged(sender, args) {
var strComboID = $find("<%=rcbCustomer.ClientID%>");
var strValue = strComboID.get_value();
var strShipToVal = $("#hidShipTo").val();
var strData = "{ strSoldToSelected: '" + strValue + "', strShipToSelected: '" + strShipToVal + "' }";
alert("yes");
$.ajax({
type: "POST",
url: "/webservices/ProductServer.asmx/PopulateShipToDetails",
data: strData,
contentType: "application/json; character=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.SalesRep);
},
failure: function (xhr, ajaxoptions, thrownError) {
alert("Error1:" + xhr.status);
alert("Error2:" + thrownError);
}
});
}
Attempt #2: throws an error inside of a JQuery library object
function hidShipTo_IndexChanged(sender, args) {
var strComboID = $find("<%=rcbCustomer.ClientID%>");
var strValue = strComboID.get_value();
var strShipToVal = $("#hidShipTo").val();
var strData = "{ strSoldToSelected: '" + strValue + "', strShipToSelected: '" + strShipToVal + "' }";
alert("yes");
$.ajax({
type: "POST",
url: "/webservices/ProductServer.asmx/PopulateShipToDetails",
data: strData,
contentType: "application/json; character=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.SalesRep);
},
failure: function (xhr, ajaxoptions, thrownError) {
alert("Error1:" + xhr.status);
alert("Error2:" + thrownError);
}
});
}
Any ideas on how I can access each of the items in the JSON String?
Thanks!

since your code does not throw an undefined exception, then we can deduce 'msg' is not undefined.
Use a debugger to see what your msg really contains:
alert(msg.SalesRep);
console.log(msg);
note: contentType should be 'charset=utf-8', not 'character=utf-8'. also the string you're sending is not valid json. It should be double quoted instead of using single quotes.

So the answer was really simple once I checked the console log. I added this line of code and I was able to begin accessing everything in the JSON string:
var obj = $.parseJSON(msg.d);

This makes no sense:
var strData = "{ strSoldToSelected: '" + strValue + "', strShipToSelected: '" + strShipToVal + "' }";
It should just be
var strData = { strSoldToSelected: strValue, strShipToSelected: strShipToVal };

Related

400 bad request for ajax call with GET request parameter passed to controller in spring

i'm showing a drop down list in a page based on the selection i have to show dependent drop down by passing the selected value in drop down list to the controller and return json data as response.please find below code and help me for resolving this .
Please find below ajax code
<script type="text/javascript">
jQuery(document).ready(function () {
$.ajax({
type: 'POST',
dataType : 'json',
contentType : "application/json",
url : "${home}getOPList",
cache: false,
success: function(response){
// var str = JSON.stringify(response);
var operatorList;
// alert("yes");
// alert(str);
for (var i = 0; i < response.length; i++ )
{
console.log(response[i].listOfOperators);
operatorList +="<option value =' "
+ response[i].sno +
" '>"
+ response[i].listOfOperators +
"</option>"
}
$('#opList').html(operatorList);
},
error: function(){
alert('Error while request..');
}
});
$("#opList").change(function(){
$.ajax({
type: 'GET',
dataType : 'json',
contentType : "application/json",
url : "${home}partnerDetails?operator =" +opList,
cache: false,
success: function(response){
// var str = JSON.stringify(response);
var partnerList;
alert("yes");
alert("oplist " + opList);
for (var i = 0; i < response.length; i++ )
{
console.log(response[i].campaignName);
partnerList +="<option value =' "
+ response[i].sno +
" '>"
+ response[i].campaignName +
"</option>"
}
$('#ptList').html(partnerList);
},
error: function(){
alert('Error while request in partners..');
}
});
});
});
</script>
above is the ajax code and when the code gest executed it is directly showing " Error while request in partners.. ".in console it says it is a bad request with 400 response code for the below url.
http://localhost/Promotions/partnerDetails
please suggest on this

Ajax never calls my .NET method?

Hi I have the following AJAX which references a method in my .aspx page. I've done some console debugging and my data.d is always undefined. So I've put a breakpoint in the .aspx page on the first line of the method referenced and it never hits it.
I'm really stuck - so if someone could point me in the right direction that would be great.
AJAX:
var param = { "mySearchString": str };
$.ajax({
type: 'POST',
url: 'myForm.aspx/myMethod',
data: JSON.stringify(param),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function (data) {
$("#MyResults").empty();
console.log(data);
console.log(data.d);
console.log(data.d.length);
for (i = 0; i < data.d.length; i++) {
$("#MyResults").append("<li><a href='#' onClick='SetName(this)'>" + data.d[i].title + "</" + " a>" + "</" + "li>");
}
if (data.d.length == 0)
{
$("#MyResults").empty();
}
}
});
The initial set up for my .NET method:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod(EnableSession = true)]
public static IEnumerable<MyItem> myMethod(string searchString)
{
I'm passing the right type across, and there are no errors on build or when I run it. So I'm a bit stumped!
Add this to your ajax call to see more about the error:
error: function (request, status, error) {
alert('Error: ' + error);
}
Is this an MVC application? Should the url actually be myForm.aspx/myMethod or just myForm/myMethod? What I am getting at is have you ever hit a breakpoint on the server side and is the path correct?
Try adding this as part of the signature
[HttpPost]
You can add the below attribute to the class, which enables the web method to be called from an ajax script.
[System.Web.Script.Services.ScriptService]
you have
var param = { "mySearchString": str };
but the parameter in you Method is
public static IEnumerable<MyItem> myMethod(string searchString)
Both parameters should have the same name.
You're passing a string as parameter, you should pass an object with a string attribute named searchString:
var param = { "mySearchString": str };
$.ajax({
type: 'POST',
url: 'myForm.aspx/myMethod',
data: param,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function (data) {
$("#MyResults").empty();
console.log(data);
console.log(data.d);
console.log(data.d.length);
for (i = 0; i < data.d.length; i++) {
$("#MyResults").append("<li><a href='#' onClick='SetName(this)'>" + data.d[i].title + "</" + " a>" + "</" + "li>");
}
if (data.d.length == 0)
$("#MyResults").empty();
}
});
kindly remove the following properties, and remove the JSON.stringfy
contentType: 'application/json; charset=utf-8',
dataType: 'json',
and kindly don't remove the async because it will freeze your UI if you set it to false.
you can do it like this:
$.ajax({
type: 'POST',
url: 'myForm.aspx/myMethod',
data: param,
success: function (data) {
$("#MyResults").empty();
console.log(data);
console.log(data.d);
console.log(data.d.length);
for (i = 0; i < data.d.length; i++) {
$("#MyResults").append("<li><a href='#' onClick='SetName(this)'>" + data.d[i].title + "</" + " a>" + "</" + "li>");
}
if (data.d.length == 0)
{
$("#MyResults").empty();
}
}
});
I found my answer here: ASP.NET Calling WebMethod with jQuery AJAX "401 (Unauthorized)"
I was hitting this error:
Object {Message: Ajax error: "Authentication failed.", StackTrace:
null, ExceptionType: "System.InvalidOperationException"}
Turns out that I needed to do:
Inside ~/App_Start/RouteConfig.cs change:
settings.AutoRedirectMode = RedirectMode.Permanent;
To:
settings.AutoRedirectMode = RedirectMode.Off;
Hopefully this will help someone else!

Send jquery array via ajax into rails controller

i need to send one array into rails controller via jquery ajax
jquery CODE
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<input type="text" placeholder="Role" name="Role' +
counter +
'" id="textbox' + counter + '" value="" > <input type="text"
placeholder="Search" name="search' + counter +
'" id="se" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#getButton").click(function () {
var fd = new FormData($("#movie-form")[0]);
var name = document.getElementById("file").files[0].name;
var arr = [];
var msg = '';
for(i=1; i<counter;i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
arr[i] = $('#textbox' + i).val();
}
$.each(arr,function(index, item)
{
alert(index);
alert(item);
}
);
fd.append( 'file', name);
fd.append( 'file22', name);
$.ajax({
url: '/create',
data: {fd:fd,arr:arr},
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
return false;
});
But it shows the error
Error occurred while parsing request parameters.
Contents:
REXML::ParseException (The document "[object Object]" does not have a valid root):
To do an ajax POST request via jquery the data has to be a string.
$.ajax({
url: "/create",
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(formData),
function(data){
alert(data)
}
});
Watch out for JSON being undefined in IE6/7. If you need to target those browsers, use this: https://github.com/douglascrockford/JSON-js
Could you console.log your array? That'll be much easer and you can inspect the sub elements when you click on it. In FireFox (with FireBug plugin installed) or in Chrome press F12 to open the dev tools and see the console.
I don't think this will work for IE but you can convert a JavaScript object to JSON with JSON.stringify so you can send your msg as JSON:
try:
for(i=1; i<counter;i++){
arr[i] = $('#textbox' + i).val();
}
msg= JSON.stringify(arr)
The error you're having is from your rails app but you have not posted any code where that error happens.
I'm not sure what rexml does in rails so can't realy help you with that one.

Trying to convert json to xml but shows error

I'm trying to convert the json result into xml type. However, it doesn't seems to work. Couldn't find out what's wrong. Please help.
The code is:
<script src="../Jquery Autocomplete/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="../Jquery Autocomplete/jquery.json-2.2.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function()
{
$(".openModalLink").click(function()
{
var start=$(this).parent().parent().find(".start").val();
var end =$(this).parent().find(".end").val();
$.ajax(
{
type: "POST",
url: "frmCollegeExamScheduleMst.aspx/ServerSideMethod",
data: "{'paraml': '" + start + "','param2': '" + end + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success:function(result)
{
var xmlDoc = $.parseXML(result);
var xml = $(xmlDoc);
var customers = xml.find("Table");
var data = new Array();
var i =0;
$.each(customers, function ()
{
//do something
});
},
error: function(err) {
alert('Error:' + err.responseText + ' Status: ' + err.status);
}
});
});
});
When you specify dataType: "json" the response is converted to a JSON object and does not remain a string.
Try removing the parameter.
Try like this:
success: function(result) {
var xmlDoc = $.parseXML(result.d);
...
}
Notice the result.d. I guess your ASP.NET PageMethod looks like this:
[WebMethod]
public static string ServerSideMethod(string param1, string param2)
{
DataSet ds = ...
return ds.GetXml();
}
This string is JSON serialized. In order to retrieve it on the client the ASP.NET infrastructure adds the d parameter:
{"d":"some xml here"}
Another thing that you should absolutely change in your code is replace:
data: "{'paraml': '" + start + "','param2': '" + end + "'}"
with:
data: JSON.stringify({ param1: start, param2: end })
to ensure that your request parameters are properly JSON encoded. Think for example what will happen if start = 'foo\'bar'. You will end up with:
data: {param1: 'foo'bar', param2: 'baz'}
which as you can see completely breaks your JSON.
If the response from your AJAX request is xml then you should set it accordingly.
$.ajax({
data: {paraml: start, param2: end},
dataType: "xml",
success:function(result) {
var $xml = $(result);
}
});
No need for contentType nor concatenating in data.

unable to execute javascript jquery function

I have a Jquery autocomplete function through callback method. However it doesn't seem to run.
Here is my code:
At Client-Side:
<script type="text/javascript">
$(document).ready(function() {
alert("hi");
$("#Text1").autocomplete({
minLength: 0,
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: 'BlissMaker.aspx/GetNames',
data: "{ 'sname':'" + request.term + "' }",
dataType: "json",
dataFilter: function (data) { return data; },
success: function (data) {
if (data.d != null) {
response($.map(data.d, function (item) {
return {
label: item.Name,
value: item.Id
}
}))
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
}
});
},
focus: function (event, ui) {
$("#Text1").val(ui.item.label);
return false;
}
})
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a><img src='" + item.icon + "' width='32' height='32' /> " + item.Name + "</a>")
.appendTo(ul);
};
}
</script>
At Code-Behind:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<States> GetNames(string sname)
{
List<States> sbStates = new List<States>();
con = new SqlConnection("Data Source=PRATEEK\\SQLEXPRESS;Initial Catalog=BD;Integrated Security=True;Pooling=False");
con.Open();
Me mee = (Me)Session["Me"];
qr = "SELECT FBFriends.FB_Id2, ActiveInfo.Name, ActiveInfo.Profile_Pic, ActiveInfo.Gender FROM [FBFriends],[ActiveInfo] WHERE FBFriends.FB_Id1='" + mee.Id + "' AND ActiveInfo.FB_Id=FBFriends.FB_Id2";
ds = new DataSet(qr);
da = new SqlDataAdapter(qr, con);
da.Fill(ds);
ds.Tables[0].Select(ds.Tables[0].Columns[1].ColumnName + " Like '%" + sname + "%' and " + ds.Tables[0].Columns[3].ColumnName + " = 'Female'");
foreach (DataRow row in ds.Tables[0].Rows)
{
States st = new States();
st.Id = row.ItemArray[0].ToString();
st.Name = row.ItemArray[1].ToString();
st.Value = row.ItemArray[1].ToString();
st.Icon = row.ItemArray[2].ToString();
sbStates.Add(st);
}
return sbStates;
}
It seems that autocomplete function is not getting called as well as Alert()..
Any suggestions on how to call it?
ADDED:
After checking the stack trace, it gives me an error
Unknown Method name GetNames
Any suggestions?
You forgot one closing at the end ")";
$(document).ready(function() {
})
After fixing that part check the response and request in console of firebug or such.
Try cleaning up the code errors and run it again:
Problem at line 19 character 43: Missing semicolon.
}
Problem at line 20 character 41: Missing semicolon.
}))
Problem at line 39 character 13: Expected ')' and instead saw ''.
}
Problem at line 39 character 13: Missing semicolon.
}
Is $(document).ready() getting called at all? If not, is you javascript in a separate file? If so, maybe the file itself is not reachable and the ready() function isn't even being called. Check the <script src=""></script> tags for including the JQuery files and your javascript file.
I'm not sure if this is causing your problem or not, but I noticed in your JQuery $.ajax call you had this line here:
data: "{ 'sname':'" + request.term + "' }",
I've found ajax calls to fail if I concat variables and strings in the data: field of the $.ajax call.
Try this:
declare a variable outside the call like this:
var dataToSend = "{ 'sname':'" + request.term + "' }";
then change the data: field to this:
data: dataToSend,
This may or may not solve your problem, but it looks nicer! Try it anyways!
Thank You everyone. I finally got my mistake.
The Web Method needed to be Static in order to call it and also ScriptManager included in the form must be EnablePageMethods=true
My code is working all fine now. Thanks a lot :)

Categories