jqPlot and JSON formatted Data - json

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.

Related

How to parse json string to integer ? (ajax)

i had problem with these codes.
<script>
$(function() {
$('#submitRegister').click(function (e) {
console.log('jalan fungsi submit');
e.preventDefault();
var paramObj = {};
$.each($('#registerForm').serializeArray(), function (_, kv) {
if (paramObj.hasOwnProperty(kv.name)) {
paramObj[kv.name] = $.makeArray(paramObj[kv.name]);
paramObj[kv.name].push(kv.value);
}
else {
paramObj[kv.name] = kv.value;
}
});
console.log(paramObj);
var dataMitra = paramObj;
var urlAjax = "my url";
$.ajax({
type: "POST",
url: urlAjax,
contentType: "application/json; charset=utf-8",
data: dataMitra,
crossDomain: true,
success: function (data) { alert("ajax worked"); },
error: function (data) { console.log(data); },
dataType: "json",
beforeSend: function (xhr) {
xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("accept", "application/json");
},
headers: {
'Access-Control-Allow-Origin': '*'
}
});
});
});
am using ajax for post to my API, there are several fields that are required to use integers. looks json below
================================================
ada_lahan: "1" *
alamat_juragan: "jalan intan v no. 192"
alamat_lahan: ""
code: "10640" *
country_id: "100" *
email: "gecok123#gmail.com"
juragan: "arjuna"
juragan_refferal: "1" (it should be int)
juragan_stage: "arjuna"
kabupaten_id: "2" *
kecamatan_id: "2" *
kelurahan_id: "4" *
lahan_kabupaten_id: "Kota / Kab*"
latitude_juragan: "-6.1642709" *
longitude_juragan: "106.86704039999995" *
nama_juragan: "bram story"
provinsi_id: "27" *
telepon: "82312233332"
=================================================
note : * means should be integer value
how can i parse the string value to integer ? only for the several fields.
thanks

Laravel AJAX GET and show new data

I've been working on a project and thus far I've been able to POST to the database using AJAX, so when the user submits data the page wont refresh but the data is still uploaded to the database.
Now what I want to do, is show those results to the user without needing to refresh the page. I've spent a lot of time trying to figure it out but right now I'm very stuck. Could anyone point me in the right direction? I've read the documentation on the website, watched hours worth of videos but still have no luck.
The code I have so far.
Script
$.ajax({
type: 'GET', //THIS NEEDS TO BE GET
url: '{{$video->id}}/shownew',
success: function (data) {
console.log(data);
$("#data").append(data);
},
error: function() {
console.log(data);
}
});
Controller
public function shownew($video)
{
$getstamps = DB::table('timestamps')
->where('videoid', '=', $video)
->orderByRaw('LENGTH(timestamp_time)', 'ASC')
->orderBy('timestamp_time', 'asc')
->get();
return response()->json(array('success' => true, 'getstamps' => $getstamps));
}
Console
{success: true, getstamps: Array(3)}
getstamps: Array(3)
0: {
timestamp_id: 128,
videoid: "5",
timestamp_name: "Title",
timestamp_time: 1,
created_at: "2017-10-04 23:28:12",
…
}
1: {
timestamp_id: 129,
videoid: "5",
timestamp_name: "1",
timestamp_time: 1,
created_at: "2017-10-04 23:41:01",
…
}
2: {
timestamp_id: 130,
videoid: "5",
timestamp_name: "1",
timestamp_time: 1,
created_at: "2017-10-04 23:41:21",
…
}
length: 3
__proto__: Array(0)
success: true
__proto__: Object
here is the solution for you problem
$.ajax({
type: 'GET', //THIS NEEDS TO BE GET
url: '{{$video->id}}/shownew',
success: function (data) {
var obj = JSON.parse(data);
var your_html = "";
$.each(obj['getstamps'], function (key, val) {
your_html += "<p>My Value :" + val + ") </p>"
});
$("#data").append(you_html); //// For Append
$("#mydiv").html(your_html) //// For replace with previous one
},
error: function() {
console.log(data);
}
});
This fixed the issue.
$.ajax({
type: 'GET', //THIS NEEDS TO BE GET
url: '{{$video->id}}/shownew',
dataType: 'json',
success: function (data) {
console.log(data);
container.html('');
$.each(data, function(index, item) {
container.html(''); //clears container for new data
$.each(data, function(i, item) {
container.append('<div class="row"><div class="ten columns"><div class="editbuttoncont"><button class="btntimestampnameedit" data-seek="' + item.timestamp_time + '">' + new Date(item.timestamp_time * 1000).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0] +' - '+ item.timestamp_name +'</button></div></div> <div class="one columns"><form action="'+ item.timestamp_id +'/deletetimestamp" method="POST">' + '{!! csrf_field() !!}' +'<input type="hidden" name="_method" value="DELETE"><button class="btntimestampdelete"><i aria-hidden="true" class="fa fa-trash buttonicon"></i></button></form></div></div>');
});
container.append('<br>');
});
},error:function(){
console.log(data);
}
});

JSON - Why I got null object when not using JSON.stringify?

I'm using bootstrap 3 and jquery to develop my app. My question is, why i got null object if not using JSON.stringify instead formValues?
Before using JSON.stringify
var that = this;
var formValues = {
userId: 315,
locale: "en",
};
this.collection.fetch({
type: "POST",
contentType: 'application/json',
dataType: "json",
data: formValues,
success: function(collection, response) {
var template = _.template(accountsSummaryTemplate, {
accounts: that.collection.models
});
that.$el.html(template);
console.log(that.collection);
},
error: function(collection, response) {
console.log(that.collection);
}
});
After using JSON.stringify
var that = this;
function formToJSON() {
return JSON.stringify({
"userId": 315,
"locale": "en",
});
}
this.collection.fetch({
type: "POST",
contentType: 'application/json',
dataType: "json",
data: formToJSON(),
success: function(collection, response) {
var template = _.template(accountsSummaryTemplate, {
accounts: that.collection.models
});
that.$el.html(template);
console.log(that.collection);
},
error: function(collection, response) {
console.log(that.collection);
}
});
Thanks a lot in advance.
If the data property is an object, jQuery serializes it with $.param:
> $.param({userId: 315, locale: "en"});
"userId=315&locale=en"
If you pass in a string instead, jQuery doesn't serialize it. Look at the requests using your web browser's developer tools.
Because that's not a proper data string.
var formValues = "userid=5&locale=en";
Because JS object is not JSON. JSON is string, JS object is an object. If fetch uses jQuery.ajax, it expects either a JS object, or a query string (which is not JSON): "userId=315&locale=en".

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 (){

ajax json output parsing in jquerymobile

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
});