ajax json output parsing in jquerymobile - json

public function actionajaxSearch() {
$data_fetched=Person::model()->findByAttributes (array('Code'=>'Cust0001'));
echo CJSON::encode($data_fetched); }
$('#searchResult').live('pageshow', function(e,info)
{
$.post('?r=mobile/ajaxSearch',$('form').serialize(),
function(res)
{
arrayvalue =res;
$.each(arrayvalue, function(i, profile) {
alert(i);
alert(profile);
});
}
});
I am getting the output as json encode one.
In traversing alert i am getting the value each character not by key or value.
Any help?

Adding the datatype and contenttype solved the problem. Added the complete code for other's ref.
public function actionajaxSearch() {
$data_fetched=Person::model()->findByAttributes (array('Code'=>'Cust0001'));
echo CJSON::encode($data_fetched); }
$('#searchResult').live('pageshow', function(e,info)
{
$.ajax({
beforeSend: function() { $.mobile.showPageLoadingMsg(); },
complete: function() { $.mobile.hidePageLoadingMsg() },
url: '?r=mobile/ajaxSearch',
data: $('form').serialize(),
type: 'POST',
ContentType: "application/json",
dataType: "json",
success:function(res) {
if(res !='')
{
$.each(res, function(key, value) {
var li='<li>'+value['Code']+'</li>';
$("#mylist").append(li); //append li to ul of id list
}); //eachfunction
$('#mylist').listview();
$('#mylist').listview('refresh');
}//sucess
});

Related

How to parse this json file with key and value pair?

How to parse this json file?
I tried the following code, but it didn't work.
I tried the following code, but it didn't work.
{"success":true,
"CourseResult":[
[{"Key":"Course","Value":"Physics"}],
[{"Key":"Course","Value":"Chemistry"}],
[{"Key":"Course","Value":"Math"}],
[{"Key":"Course","Value":"English"}]]}
$.ajax({
type: "POST",
url: "/Course/GetCourse",
dataType: "json",
data: {
registrtionId: rId
},
success: function (data) {
if (data && data.success) {
var rst = JSON.parse(data);
alert(rst.CourseResult[1].Course);
},
error: function (msg) {
}
});

Post list of string null on web api controller

In my web api project, I got a controller named ContactController and a method named Synchro in it which waits for a list of string as below:
[HttpPost]
[Route("api/Contact/Synchro")]
public IHttpActionResult Synchro([FromBody]List<string> listNumTel)
{
List<Profil> listContact = new List<Profil>();
if (listNumTel.Count() > 0)
{
try
{
listContact = Librairie.Contacts.getContactSync(listNumTel);
return Ok(listContact);
}
catch(Exception e) {
return InternalServerError(e);
}
}
else
{
return BadRequest();
}
}
To test that method, I've created the ajax called below:
$("#btn_synchro").click(function () {
$.ajax({
url: '../api/Contact/Synchro',
type: 'POST',
data: {
"listNumTel": [
"+33640512999",
"+33640522997",
"+33640182998",
"+33640742996"]
},
dataType: 'json',
success: function (data) {
alert('Synchro réussi: ' + data);
},
error: function (request, error) {
alert("Erreur lors de la synchro");
}
})
});
When I test on debug mode, the call works fine but the method get a null list. I checked if the json is valid and it is. Does Somebody sees what could be wrong ? Thanks in advance !
Thanks for the answers, but I've just found out the solution. It was all about JSON sent. To send a list of string by an ajax call for example, the JSON should looks like below the variable listNumero
("#btn_synchro").click(function () {
var listNumero =
[ '+33640532999',
'+33640532997',
'+33640532998',
'+33640532996'];
$.ajax({
url: '../api/Contact/Synchro',
type: 'POST',
data: JSON.stringify(listNumero),
contentType: "application/json",
dataType: 'json',
success: function (data) {
alert('Synchro réussi: ' + data);
},
error: function (request, error) {
alert("Erreur lors de la synchro");
}
})
});
You can compare to my post, the JSON is different. Now my web api controller can get the values from the list.

jqPlot and JSON formatted Data

I'm returning a JSON string with an Ajax call in jQuery, I'd like to pump that data into a bar chart using jqPlot.
I got the JSON conversion code from another Stack-Overflow post, but can't understand why this isn't working. My code:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(DTO), //JSON.stringify(AnDParms), combined,
url: "GetAdmitsDischarges.asmx/GetAandD",
dataType: "json",
success: function (data) {
//do chart stuff here.
var line1 = [];
for (var prop_name in data.d) {
line1.push([prop_name, data[prop_name]])
}
var ticks = ['Admits', 'Discharges'];
var plot1 = $.jqplot('chartdiv', [line1], {
title: 'Admits & Discharges',
series: [{ renderer: $.jqplot.BarRenderer}],
axesDefaults: {
tickRenderer: $.jqplot.CanvasAxisTickRenderer
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer
}
}
});
//to prove the flow is working...
//alert("Data: " + data.d);
}, //end of success
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + ' ' + errorThrown + ' ' + XMLHttpRequest);
} //end of error
}); //end of ajax call
In Firebug, the value of line1 is (going from 0 to 32):
[["0", undefined],["1", undefined],...["31", undefined],["32",
undefined]]
While the value of data is:
Object { d="{"Admits":"35","Discharges":"36"}" }
Thanks for any help you can offer...
The problem is your JSON structure:
{
"Admits": "35",
"Discharges": "36"
}
You are providing a JSON object, but jqplot needs array instead:
[
["Admits", 35],
["Discharges", 36]
]
I finally figured it out with the help of Dave Ward of Encosia.com...if you've not checked out his blog, head straight there right now...it's great for all your .Net/jQuery needs.
Here is my javascript:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(DTO),
url: "GetAdmitsDischarges.asmx/GetAandD",
dataType: "json",
success: function (data) {
var jqPlotData = $.map(data.d, function (value, key) {
if (key != "__type") {
return [value]; //was key, value
}
});
var ticks = ['Admits', 'Discharges'];
var plot1 = $.jqplot('chartdiv', [jqPlotData], {
title: 'Admits & Discharges',
seriesDefaults: {
renderer: $.jqplot.BarRenderer,
rendererOptions: { varyBarColor: true },
pointLabels: { show: true }
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: ticks
}
},
highlighter: { show: false }
});
Also, I removed the JSON serialization from my web service, and just returned the object. Hopefully this will help others.

jquery validation onSubmit ajax post JSON response

I have a very complicated post using jquery validation and an AJAX post that gets a JSON response back from the server and puts it in a jqGrid... But it seems as though my onsuccess is never being called at any point...
$(document).ready(function () {
$("#formSearchByMRN").validate({
rules: {
MRN: { required: true, minLength: 6 }
},
messages: {
MRN: 'Please Enter a Valid MRN'
},
submmitHandler: function (form) {
e.preventDefault();
animateLoad();
debugger;
var theURL = form.action;
var type = form.methd;
var data = $(this).serialize();
$.ajax({
url: theURL,
type: type,
data: data,
dataType: "json",
success: function (result) {
debugger;
var data = result;
if (data.split(':')[0] == "Empty record") {
$("#list").unblock();
$('#resultDiv').html('<b><p style="color: #ff00ff">' + data + '</p></b>');
setTimeout(function () {
$('#resultDiv').html("");
}, 10000);
}
else {
binddata(data);
}
}
});
return false;
}
});
});
It would seem I never get into the submmitHandler. Event though I manage to get to my server side function and it does return, it prompts my UI to save a file which contains the JSON results...
No good.
Am I going about validating my form before my AJAX post the wrong way? Does anybody have any advice about best practices in validating AJAX posts?
UPDATE... MARK R. This is what I attempted. It seems as though I never get in to the success function... My suspicion is that I am not really posting via ajax, but instead doing a full post. I don't understand why.
$('#submitMRN').click(function () {
$("#formSearchByMRN").validate({
rules: {
MRN: { required: true, minLength: 6 }
},
messages: {
MRN: 'Please Enter a Valid MRN'
}
});
if ($('#submitMRN').valid()) {
$("#list").block({ message: '<img src="../../Images/ajax-loader.gif" />' });
$.ajax({
url: $('#submitMRN').action,
type: $('#submitMRN').method,
data: $('#submitMRN').serialize(),
dataType: "json",
success: function (result) {
debugger;
var data = result;
if (data.split(':')[0] == "Empty record") {
$("#list").unblock();
$('#resultDiv').html('<b><p style="color: #ff00ff">' + data + '</p></b>');
setTimeout(function () {
$('#resultDiv').html("");
}, 10000);
}
else {
binddata(data);
}
}
});
}
});
$('#SubmitButton').click(function (){
//Check that the form is valid
$('#FormName').validate();
//If the Form is valid
if ($('#FormName').valid()) {
$.post(...........
}
else {
//let the user fix their probems
return false;
}
});//$('#SubmitButton').click(function (){

$jQuery Tree from json data ---> .live is killing me

I'm trying to build a tree from json data, this data are loaded on demand from php files. My problem is that i can't find a way to get to lvl 3 ;). Here is my code:
$(document).ready(function()
{
//Get the screen height and width
var Height = $(document).height()/2;
var Width = $(window).width()/2;
$("#div1").hide();
$("#div2").hide('slow');
$.ajax(
{
type: 'post',
async: true,
url: "getparents.php",
data: {'id' : 12200},
dataType: "json",
cache: false,
beforeSend: function ()
{
//Show the Loading GIF at centered position
$('#loading').css({'top': Height, 'left': Width}).show();
},
success: function(json_data)
{
$("#div1").empty().show();
$('<ul class="parentContainer"></ul>').appendTo("#div1");
$.each(json_data, function(key, object)
{
$('<li id="node">'+object.name+'</li>').data('id', object.id).appendTo(".parentContainer");
if (object.childbool == true)
{
$('li:last').addClass('childfull')
}
});
},
error: function ()
{
$('#loading').hide();
alert('Something Went Wrong with the Loading please hit back in a minute');
},
complete: function ()
{
$('#loading').hide();
}
});
function getChild(id, node)
{
$.ajax(
{
type: 'post',
async: true,
url: "getchilds.php",
data: {'id' : id},
dataType: "json",
cache: false,
beforeSend: function ()
{
$('#loading').show();
},
success: function(json_data)
{
$('<ul class="childContainer"></ul>').appendTo(node);
$.each(json_data, function(key, object)
{
$('<li id="node">'+object.name+'</li>').data('id', object.id).appendTo(".childContainer");
if (object.childbool == true)
{
$('li:last').addClass('childfull')
}
});
},
error: function ()
{
$('#loading').hide();
alert('Something Went Wrong with the Loading please hit back in a minute');
},
complete: function()
{
$('#loading').hide();
}
});
}
$("li.childfull, li.openchildfull").live('click',function()
{
if ($('li.childfull'))
{
var node = $(this);
var id= $(this).data('id');
$(node).html(getChild(id, node));
$(node).removeClass().addClass('openchildfull');
}
else
{
$(node).removeClass().addClass('childfull');
$(node).children().remove();
}
});
});
I think .live is killing me. I get my parents on load; when I click on one I get its children ALL pretty and well, but when I click on a child to get its children I get a very funny behavior. I get its children correctly indented but with no class="childfull" and I get an other copy of them not properly indented but with correct class.. I don't know what is going wrong... Any ideas/corrections are welcome.
P.S: You don't want me to describe to you what happens when I click on the messed up 3rd lvl childfull :P.
Instead of going through the headache of building your own tree, have a look at the jstree plugin. You can pass different formats to it, including json. It allows for complete customization and allows infinite(possible :p) child levels.