Reploting a JQplot chart using ajax - ajax

I have been trying to solve this in different ways, but haven't make it work as expected, I feel it isn't so big deal (I really hope so) but my experience and skills with Ajax and jQuery are kind of limited that's why I am appealing to your expertise!
I am working on a chart similar to the one here http://www.jqplot.com/tests/data-renderers.php. but in my case the json file is generated depending on a value that the user choses from a select box. I am using 2 files and ajax calls to accomplish this:
-AnnualB.html is the file where the select box is located and the chart should be displayed.
-Index.php is the file where the query to the database is made (using the value obtained from the selectbox in AnnualB.html) and the json array is generated.
In AnnualB.html I use the GET method to retrieve the value from the selectbox and send it to Index.php, which generates the json data. Based on that json data the chart has to be created in AnnualB... Here is where my problem comes. The function to generate the chart is working fine and the call to send the select value and return the json is also working (have checked with Firebug), but I know am missing something (but don't know what yet) because I don't manage to pass the json data to the function that generates the chart.
My codes in AnnualB.html goes like this (abbreviating some irrelevant information with ...):
Function to generate the chart (Is working ok if the json data is passed)
function CreateGraph() {
$(document).ready(function(){
var ajaxDataRenderer = function(url, plot) {
var ret = null;
$.ajax({
async: false,
url: url,
dataType:'json',
success: function(data) {
ret = data; }
});
return ret; };
$.jqplot.config.enablePlugins = true;
var jsonurl = "./index.php";
var plotData = ajaxDataRenderer(jsonurl);
var series = ...
plot1 = $.jqplot('Chart1', series,{...}}
Ajax Call (PROBABLY WHERE MY MISTAKE/OMISSION IS)
function LoadGraph(int)
{
if (window.XMLHttpRequest)
{xmlhttp=new XMLHttpRequest();}
else
{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.open("GET","index.php?tasel="+int,true);
xmlhttp.send();
xmlhttp.onreadystatechange=function()
{
CreateGraph(int)
}
}
Select box
<select name="tasel" size="1" onchange="LoadGraph(this.value)">
<option value="">Select accounts type:</option>
<option value="3">Tuloslaskelma</option>
<option value="2">Tasevastattava</option>
<option value="1">Tasevastaava</option>
</select>
The related code in Index.php goes like this (Is working ok when the value of the select box (tasel) is passed)):
$tasel = $_REQUEST['tasel'];
if ($tasel == ...2)
{...}
.
.
.
echo "[",$selite, ",";// These 2 variables create the json array
echo $finaljson, "]";
Thanks in advance for your patience and help!

I realized the answer to this question was simpler than what I was expecting.
Instead of making the whole function LoadGraph(int) ajax call, I just needed to call the tasel value ?tasel="+int in the function to generate the chart like this (which is already doing an ajax call):
function CreateGraph() {
$(document).ready(function(){
var ajaxDataRenderer = function(url, plot) {
var ret = null;
$.ajax({
async: false,
url: url,
dataType:'json',
success: function(data) {
ret = data;
}
});
return ret;
};
$.jqplot.config.enablePlugins = true;
var jsonurl = "./index.php?tasel="+int;
var plotData = ajaxDataRenderer(jsonurl);
var series = ...
plot1 = $.jqplot('Chart1', series,{...}
}

var plot1 = undefined;
var plotOptions = undefined;
function CreateGraph() {
$.ajax({
async: false,
url: "./index.php",
dataType:'json',
success: function(data) {
var series = fn... // Convert your json Data to array
if(plot1 != undefined)
{
plot1.destroy();
}
plot1 = $.jqplot('Chart1', series, plotOptions);
}
});
}
$(function(){
$.jqplot.config.enablePlugins = true;
plotOptions = {...}; // jqPlot options
CreateGraph();
});
Hope this might help you..

Related

admin-ajax.php do not recognizes 'action'. $_REQUEST is empty

After two days of fruitless research, I decided to join the community. I hope to get a solution. I develop a plug-in that, among other things, must implement the upload of documents. this should be done using ajax technology. the problem is that the request is approved, but admin_ajax.php reacts like no action was taken. Outside of wp this piece of code works fine, as it was thought out. The problems come with installing this code in wp. Below is my code
PHP. This code in the main class that will call from main modul of plugin
class main{
//other activation methods
private function register_scripts(){
add_action('wp_enqueue_scripts', array($this,'re_add_script'));
}
public function re_add_script() {
wp_enqueue_script('re_upload',plugins_url('re'.'/js/re_upload.js'),array('jquery'));
wp_localize_script('re_upload',"re_ajax",array(
'ajaxurl'=>admin_url("admin-ajax.php")));
add_action( 'wp_ajax_upload', 'processingUpload');
}
}//end of class
//callback function
function processingUpload(){
$clsUpload = new UploadsDocs();
$clsUpload->setRequestedData($_FILES,$_POST['doc_id']);
$clsUpload->checkUploadsFiles();
$clsUpload->outputFilesList();
wp_die();
}
jQuery 're_upload.js'
jQuery(document).ready(function (e) {
jQuery('#bt_upload').on('click', function () {
var toUpload=getFileListToUpload();
var form_data = new FormData();
var ins = input.files.length;
for (var x = 0; x < ins; x++) {
if (isFileToUpload(input.files[x],toUpload)){
form_data.append("files[]", input.files[x]);
}
}
form_data.append("doc_id", jQuery('#doc_id')[0].value);
var data_to_sent={
action: 'upload',
datas: form_data
};
jQuery.ajax({
url: re_ajax.ajaxurl, // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script
cache: false,
contentType: false,
processData: false,
data: data_to_sent,
type: 'post',
success: function (response) {
// do something
},
error: function (response) {
// do something
},
xhr: function(){
//upload Progress
var xhr = jQuery.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
//update progressbar
jQuery('#bt_upload').css("display","none");
jQuery('#progress-wrp').css("display","block");
jQuery('#progress-wrp' +" .progress-bar").css("width", + percent +"%");
(percent<50)? jQuery('#progress-status').addClass('status-less-then-50'): jQuery('.status-less-then-50').removeClass('status-less-then-50').addClass('status-more-then-50');
jQuery('#progress-status').text("Uploading..."+percent +"%");
}, true);
}
return xhr;
},
mimeType:"multipart/form-data"
});
});
});
function getFileListToUpload(){
var list=[];
var elem = document.getElementsByClassName('preview');
var tag_li=elem[0].querySelectorAll('p');
for (var i=0;i<tag_li.length;i++){
list[i]=tag_li[i].textContent.split('(')[0];
}
return list;
}
function isFileToUpload(input_file,files_toUpload){
var res=false;
for(var i=0; i<files_toUpload.length;i++){
if (input_file.name==files_toUpload[i]){
res=true;
break;
}
}
return res;
}
The problem is
add_action( 'wp_ajax_upload', 'processingUpload');
is not called.
The upload is done in two separate invocations of the server. The first invocation displays the upload page to the user. The second invocation processes the AJAX request. Your call to
add_action( 'wp_ajax_upload', 'processingUpload');
is done in the first invocation where it is not needed but not in the second invocation where it is needed.
Please read https://codex.wordpress.org/AJAX_in_Plugins. (Observe carefully how the call to 'add_action( 'wp_ajax_...', ...) is done.) Further, you need to read about nonces.
Try to append action to your ajax url like:
url: re_ajax.ajaxurl?action=upload
and
data: form_data
or pass it to form_data like:
form_data.append('action', 'upload')

How to load a .csv file into crossfilter with d3?

I am trying to load a .csv file into crossfilter for further use it with dc.js and d3. However, if the ndx = crossfilter(data_) is not inside d3.csv(..., it does not work. Is it possible to load data using d3 inside a global/outside variable (in this case ndx)?
var ndx;
private method(){
var data_;
d3.csv("samples.csv", function(data){
var format = d3.timeParse("%m-%y");
data.forEach(function(d: any) {
d.date = format(d.date);
});
data_ = d3.csvParse(data);
});
ndx = crossfilter(data_);
}
How can I load it into crossfilter?
Am I obligated to use crossfilter inside the d3.csv(.. call?
Solution:
I made my .csv became a .json and I loaded it 'synchronously'. Observe below.
var ndx;
private method(){
var data_ = (function() {
var json: any = null;
$.ajax({
'async': false,
'global': false,
'url': "samples.json",
'dataType': "json",
'success': function (data:any) {
json = data;
}
});
return json;
})();
ndx = crossfilter(data_);
}
Observe:
'async': false
This happens because the callback function is executed asynchronously, once the data is returned. This means that if you put the charting code outside of the callback, you are going to get the empty array that you defined because no data has been returned yet.

Ajax is not working with dimmer view

I am developing web based application in that I want to use dimmer view to add master information and as per this parent form needs to be refreshed.
In that dimmer view is working correctly but when I am trying to save values of child form in database using ajax but it doesn't work. If I removed ajax part it saves but it goes to the next page and I don't want this.
Here is my ajax code
<script type="text/javascript">
$(document).ready(function()
{
$('#enter1').click(function(e)
{
alert("In Ajax..");
e.preventDefault();
var ajaxdata = $("#v1").val();
var ajaxdata1 = $("#v2").val();
var ajaxdata2 = $("#v3").val();
var ajaxdata3 = $("#v4").val();
var ajaxdata4 = $("#v5").val();
var ajaxdata5 = $("#v6").val();
var ajaxdata6 = $("#v7").val();
var ajaxdata7 = $("#v8").val();
var ajaxdata8 = $("#v9").val();
var ajaxdata9 = $("#v10").val();
var ajaxdata10 = $("#v11").val();
var value ='v1='+ ajaxdata +'&v2='+ ajaxdata1 +'&v3='+ ajaxdata2 +'&v4='+ ajaxdata3 +'&v5='+ ajaxdata4 +'&v6='+ ajaxdata5 +'&v7='+ ajaxdata6 +'&v8='+ ajaxdata7 +'&v9='+ ajaxdata8 +'&v10='+ ajaxdata9 +'&v11='+ ajaxdata10 ;
alert(value);
$.ajax({
type:"get",
url: "MasterServlet",
data: value,
cache: false,
success: function(data)
{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
return false;
});
});
</script>
And my jsp button
<input type="button" id="enter1" name="enter1" value="Submit">
Can any one suggest me how to save values of dimmer view form using ajax?

Validating using unobtrusive before ajax post

So I have been playing around with the Anti Forgery Token, making progress thanks to you guys.
I have figured out a solution to merge form values anf get my ActionMethods to not puke on the AntiForgery token... I have unfortunately broken validation in the process. The AJAX post fires before client side validation / client side validation is ignored. Server side works however I would dig some validation before the post.. Here is the code I am using.
$(document).ready(function () {
$('input[type=submit]').live("click", function (event) {
event.preventDefault();
// Form with the AntiForgeryToken in it
var _tokenForm = $(this).parents().find("#__AjaxAntiForgeryForm");
// Current Form we are using
var _currentForm = $(this).closest('form');
// Element to update passed in from AjaxOptions
var _updateElement = $(_currentForm).attr("data-ajax-update");
// Serialize the array
var arr = $(_currentForm).serializeArray();
//Merge TokenForm with the CurrentForm
$.merge(arr, $(_tokenForm).serializeArray());
// The AJAX Form Post stuff
$.ajax({
type: "POST",
url: $(_currentForm).attr('action'),
data: arr,
success: function (data) {
$(_updateElement).html(data);
}
});
return false;
});
});
So I am thinking that I need to handle the client side validation some way before the $.ajax goo... Any suggestions would possibly save me some time.
Call this:
var formValid = $("#FormId").validate().form();
if (!formValid) return false;
Added into your code:
$(document).ready(function () {
$('input[type=submit]').live("click", function (event) {
event.preventDefault();
// Form with the AntiForgeryToken in it
var _tokenForm = $(this).parents().find("#__AjaxAntiForgeryForm");
// Current Form we are using
var _currentForm = $(this).closest('form');
var isValid = $(_currentForm).validate().form();
if (!isValid) return false;
// Element to update passed in from AjaxOptions
var _updateElement = $(_currentForm).attr("data-ajax-update");
// Serialize the array
var arr = $(_currentForm).serializeArray();
//Merge TokenForm with the CurrentForm
$.merge(arr, $(_tokenForm).serializeArray());
// The AJAX Form Post stuff
$.ajax({
type: "POST",
url: $(_currentForm).attr('action'),
data: arr,
success: function (data) {
$(_updateElement).html(data);
}
});
return false;
});
});

Needing example to load jqplot with multiple series, date-based data from json file

Been searching and cannot find exactly what I am looking for. Need to load multiple series into one jqplot, with each series coming from its own data file.
The example here http://www.jqplot.com/tests/data-renderers.php does show how to load a series from a file, but when I convert file to have date data, then it stops working, probably just a formatting issue, but cannot solve. What am I doing wrong?
Here is the data in the txt file:
[["7/11/2011 04:00:00am",85.0],["7/12/2011 04:00:00AM",87.4],["7/13/2011 04:00:00AM",90.0]]
Here is the code:
<script class="code" type="text/javascript">$(document).ready(function(){
var line = [ ];
var ajaxDataRenderer = function(url, plot) {
var ret = null;
$.ajax({
// have to use synchronous here, else returns before data is fetched
async: false,
url: url,
dataType:'json',
success: function(data) {
ret = data;
}
});
return ret;
};
var jsonurl = "./jsondata1.txt";
plo12 = $.jqplot('chart2', jsonurl,{
title: 'AJAX JSON Data Renderer',
dataRenderer: ajaxDataRenderer,
axes: {
xaxis: {
renderer:$.jqplot.DateAxisRenderer,
tickInterval: '1 day',
tickOptions:{formatString:'%y/%m/%d'}
}
}
});
});</script>
You could use the dataRendererOptions parameter to declare possible files, like this:
plo12 = $.jqplot('chart2', jsonurl,{
title: 'AJAX JSON Data Renderer',
dataRenderer: ajaxDataRenderer,
dataRendererOptions: {file1:'name_of_file_1', file2:'name_of_file2'}
axes: {
xaxis: {
Next use for-each to iterate trough the dataRendererOptions - Object:
var ajaxDataRenderer = function(url, plot,op) {
var ret = null;
$.each(op,function(i,n) {
$.ajax({
// have to use synchronous here, else returns before data is fetched
async: false,
url: url+'/'+i,
dataType:'json',
success: function(data) {
ret[]= data;
}
}); //end ajax
});//end each
return ret;
}
This code is not testet, but the idea behind could fit your needs.

Resources