I want to load form data and send it to the sever then chart with the returned data. It works fine if the form’s input field have default data and I comment
//$("button").click(function(){
I get no chart all if the default text fields are empty. I tried different ways but still I wont get it load from the form by clicking a button. I am stuck for 2 days now. Please, help. Thanks in advance. Here is the code
<script type="text/javascript">
var chart = null;
var dataString = [];
$(document).ready(function() {
$("button").click(function() {
$(function() {
var city1 = $("#city1").val();
var city2 = $("#city2").val();
dataString = {
city1: city1,
city2: city2
};
requestData();
});
});
function requestData() {
$.ajax({
url: 'array.php',
type: 'POST',
data: dataString,
success: function(point) {
var chartSeriesData = [];
var chartCategory = [];
$.each(point, function(i, item) {
var series_name = item.name;
var series_data = item.data2;
var cagory = series_name;
var series = {
name: series_name,
data: item.data2
};
chartSeriesData.push(series);
chartCategory.push(series_name);
});
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'column',
},
title: {
text: 'Real time data from database'
},
xAxis: {
categories: chartCategory
},
yAxis: {
minPadding: 0.1,
maxPadding: 0.1,
title: {
text: 'Value',
margin: 40
}
},
series: chartSeriesData
});
},
cache: false
});
}
});
</script>
Here is the body section
<body>
<div id="container" style="min-width: 200px; height: 400px; margin: 0 auto"></div>
<div id="city_form">
<form name="contact" action="" method="post">
<label for="city1" id="city1_label">First city</label>
<input type="text" name="city1" id="city1" size="30" value="Amsterdam" />
<label for="city2" id="email_label">Second city</label>
<input type="text" name="city2" id="city2" size="30" value="London" />
<button>Click me</button>
</form>
</div>
</body>
</html>
You are doing a bunch of things incorrectly here, one as pointed out by wirey, other you have to prevent the form submission on click of the button. Eh? When you click the submit button, its default action is to submit the form and take you to the
actionpage. You do have an added eventListener attached, which makes this ajax call and then plots the chart, but the button will still perform its default action, viz. take you to theactionpage, which in you case is the same page, so you don’t even realize that such a thing happened, you may have noticed a flicker or page reload?jQuery allows preventing this default action by calling the
preventDefault()method on your event object, which gets passed to you event listener as the 1st argument. You can read more about it here http://api.jquery.com/event.preventDefault/Try this and let us know if it helped.
HTML
JS
jsFiddle @ http://jsfiddle.net/jugal/V5zt9/6/