onchange F(x) to php to Highchart on same page - php

I am continuing a previous question that was asked onclick -> mysql query -> javascript; same page
This is my onchange function for a drop down of names. it is called when each drop down is changed. The idea is to send each runners name into the php page to run a mysql query then return 3 arrays to be entered into javascript.
function sendCharts() {
var awayTeam = document.getElementById('awayRunner').value;
var homeTeam = document.getElementById('homeRunner').value;
if(window.XMLHttpRequest) {
xmlhttp14 = new XMLHttpRequest();
}
else {
xmlhttp14 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp14.onreadystatechange = function() {
if(xmlhttp14.readyState == 4 && xmlhttp14.status == 200) {
var parts = xmlhttp14.responseText.split(','); //THIS IS WHAT IS RETURNED FROM THE MYSQL QUERY. WHEN I ALERT IT, IT OUTPUTS IN THE FORM 14,15,18,16,17,12,13
... code that generates the chart
series: [ {
name: document.getElementById('awayRunner').value,
data: [parts,','], //THIS IS WHERE AN ARRAY MUST BE ENTERED. THIS OUPUTS ONLY ONE NUMBER
type: 'column',
pointStart: 0
//pointInterval
},
{
name: document.getElementById('homeRunner').value,
data: parts, // TRIED THIS
type: 'column',
pointStart: 0
//pointInterval
},
{
name: 'League Avg',
data: [], //THIS IS WHERE 3rd ARRAY MUST BE ENTERED
type:'spline',
pointStart: 0
//pointInterval
},
]
});
}
}
xmlhttp14.open("GET", "getCharts.php?awayRunner="+awayRunner+"&homeRunner="+homeRunner, true);
xmlhttp14.send();
}
my php code looks like this. As you'll see, there are 3 arrays that must be returned to be entered into different spots in the javascript to generate the code.
$away=$_GET['awayRunner'];
$home=$_GET['homeRunner'];
$db=mydb;
$homeRunner=array();
$awayRunner = array();
$totalOverall= array();
$getHome="select column from $db where tmName = '$home'";
$result2 = mysql_query($getHome);
while($row = mysql_fetch_array($result2)){
$homeRunner[]= $row['column'];
}
$getAway="select column from $db where tmName ='$away'";
$result22 = mysql_query($getAway);
while($row2 = mysql_fetch_array($result22)){
$awayRunner[]= $row2['column'];
}
$week = 0;
while($week<20){
$week++;
$teamCount = "select count(column) from $db where week = $week";
$resultTeam = mysql_query($teamCount);
$rowTeam = mysql_fetch_array($resultTeam);
$t = $rowTeam['count(column)'];
$getLeague = "select sum(column) from $db where week = $week";
$resultLeague = mysql_query($getLeague);
while($row3 = mysql_fetch_array($resultLeague)){
$totalOverall[]=$row3['sum(column)']/$t;
}
}
echo join(',',$awayRunner);
currently, by doing it this way, the chart only outputs the second value in the array. for instance, if var parts is equal to 23,25,26,24,23...only 25 is shown.
A previous question resulted with the following answer -
Load the page.
User chooses an option.
An onChange listener fires off an AJAX request
The server receives and processes the request
The server sends back a JSON array of options for the dependent select
The client side AJAX sender gets the response back
The client updates the select to have the values from the JSON array.
I'm lost on #'s 5 - 7. Can someone provide examples of code that gets this done? Normally, I would just ask for direction, but I have been stuck on this problem for days. I'm about ready to scrap the idea of having charts on my site. Thanks in advance
EDIT
this is the first change that I have made to send and receive just one request
<script>
$(function(){
$("#awayRunner").change(function(){
$.ajax({
type: "POST",
data: "data=" + $("#awayRunner").val(),
dataType: "json",
url: "/my.php",
success: function(response){
alert(response);
}
});
});
});
The data displayed in the alertbox is in the form 12,15,16,15. Now, when I enter in
data: response,
only the second number from each is being displayed in the chart. Any ideas?
EDIT
OK, so i figured out that the info in response is a string. It must be converted to an INT using parseInt to be usable in the chart. currently, I have
$("#awayTeam").change(function(){
$.ajax({
type: "POST",
data: "away=" + $("#awayTeam").val(),
dataType: "json",
url: "/getCharts.php",
success: function(response){
var asdf = [];
asdf[0] = parseInt(response[0]);
asdf[1] = parseInt(response[1]);
asdf[2] = parseInt(response[2]);
asdf[3] = parseInt(response[3]);
alert(asdf);
will have to write a function to make this cleaner.

I can't believe it, but I finally got it. here is how I used an onchange method to stimulate a MYSQL query and have the Highchart display the result. The major problem was that the returned JSON array was a string that needed to be converted into an INT. The resultArray variable is then used in the data: portion of the highChart.
$(function(){
$("#awayTeam").change(function(){
$.ajax({
type: "POST",
data: "away=" + $("#awayRunner").val(),
dataType: "json",
url: "/getCharts.php",
success: function(response){
var arrayLength = response.length;
var resultArray = [];
var i = 0;
while(i<arrayLength){
resultArray[i] = parseInt(response[i]);
i++;
}
In the PHP code, the array must be returned as JSON like this
echo json_encode($awayRunner);

Related

Multiple Ajax call with same JSON data key calling one php file

I am trying to validate list of dynamic text fields.
Validation needs an AJAX call to interact with server.
At the backend I have written just one php file that reads the input request data and performs operation. Below is the example.
abc.js
row_count = 6
for (i = 1; i <=row_count; i++) {
id = "#val"+i.toString() ;
$(id).change(function(){
input_val="random";
$.ajax({
url:"url.php",
type:post,
async:true,
dataType: 'json',
data : {temp:input_val},
success:function(result){},
error: function (request, status, error) {}
});
});
}
url.php
<?php
$random_val = $_POST['temp'];
$cmd = 'systemcommand '.$random_val;
$flag = exec($cmd);
if ($flag == 0){
echo json_encode(array("status"=>'Fail'));
}
else{
echo json_encode(array("status"=>'Success'));
}
?>
It works fine when the row_count = 1 (Just one text field) but fails when the input is more than 1.
When the count is more than 1, the php script is not able to read the request data(The key in JSON data "temp"). it is blank in that case.
Any lead or help should be appreciated.
Thanks
Your javascript bit needs some adjusting, because you do not need to define an ajax for every single element. Use events based on a class. Also, since input behave differently than select, you should setup two different event class handlers.
function validateAjax ( element ) {
var input_val = element.val();// get the value of the element firing this off
$.ajax({
url: "url.php",
type: 'post',
async: true,
dataType: 'json',
data : { temp: input_val },
success: function(result) {
// check your result.status here
},
error: function (request, status, error) { }
});
}
$(".validate_change").on("change",function() { // for selects
validateAjax( $(this) );
});
$(".validate_input").on("input",function() { // for text inputs
validateAjax( $(this) );
});
And for your select or input you add that appropriate class.
<select class="validate_change" name="whatever"><options/></select>
<input class="validate_input" name="blah">
PS
I really worry about this code you have:
$cmd = 'systemcommand '.$random_val;
$flag = exec($cmd);
So, you are just executing anything that is coming in from a webpage POST var??? Please say this website will be under trusted high security access, and only people using it are trusted authenticated users :-)

How to post more than 1 var’s with ajax

I've been googling for a way to do this but everything I have found doesn't help me.
I'm not sure how to post all the below variables, If I select only one of them it'll post just fine as well as putting it into the correct database column.
any help would be much appreciated.
function submit() {
var mm10 = $('#10MM'),
mm16 = $('#16MM'),
mm7 = $('#7MM'),
mm2 = $('#2MM'),
fines = $('#Fines'),
bark = $('#Bark'),
cqi = $('#CQI');
$.ajax({
type: "POST",
url: "classes/Post/ChipSubmit.php",
data: ,
success: function(){
$("#successMessage").show();
}
});
};
You can do it in two ways. One using arrays, or two using objects:
function submit() {
var mm10 = $('#10MM').val(),
mm16 = $('#16MM').val(),
mm7 = $('#7MM').val(),
mm2 = $('#2MM').val(),
fines = $('#Fines').val(),
bark = $('#Bark').val(),
cqi = $('#CQI').val();
$.ajax({
type: "POST",
url: "classes/Post/ChipSubmit.php",
data: [mm10, mm16, mm7, mm2, fines, bark, cqi],
success: function() {
$("#successMessage").show();
}
});
} // Also you don't need a semicolon here.
Also you don't need a semicolon at the end of the function.
Using arrays is easier, if you want more precision, use objects:
function submit() {
var mm10 = $('#10MM').val(),
mm16 = $('#16MM').val(),
mm7 = $('#7MM').val(),
mm2 = $('#2MM').val(),
fines = $('#Fines').val(),
bark = $('#Bark').val(),
cqi = $('#CQI').val();
$.ajax({
type: "POST",
url: "classes/Post/ChipSubmit.php",
data: {
"mm10": mm10,
"mm16": mm16,
"mm7": mm7,
"mm2": mm2,
"fines": fines,
"bark": bark,
"cqi": cqi
},
success: function() {
$("#successMessage").show();
}
});
} // Also you don't need a semicolon here.
And in the server side, you can get them through the $_POST super-global. Use var_dump($_POST) to find out what has it got.
Kind of like Praveen Kumar suggested, you can create an object. One thing I was curious about, it looks like you're passing jQuery objects as your data? If that's the case, $_POST is going to say something like [object][Object] or, for me it throws TypeError and breaks everything.
var form_data = {};
form_data.mm10 = $('#10MM').val(); // Input from a form
form_data.mm16 = $('#16MM').val(); // Input from a form
form_data.mm7 = $('#7MM').val(); // Input from a form
form_data.mm2 = $('#2MM').text(); // Text from a div
form_data.fines = $('#Fines').text();
form_data.bark = $('#Bark').text();
form_data.cqi = $('#CQI').text();
$.ajax({
type: "POST",
url: "classes/Post/ChipSubmit.php",
data: form_data,
success: function() {
alert('success');
}
});
}
Then to get those values in your PHP you'd use:
$_POST[mm10] // This contains '10MM' or the value from that input field
$_POST[mm16] // This contains '16MM' or the value from that input field
$_POST[mm7] // This contains '7MM' or the value from that input field
$_POST[mm2] // This contains '2MM' or the value from that input field
And so on...
I tried to put together a jsFiddle for you, though it doesn't show the PHP portion. After you click submit view the console to see the data posted.

How to send my json array to sevaral rows in my sql database

I got several elements called workers, they all got an id, position left, and position top.
I have made it to an array and then made it to a json object, which a would like to send to my database. but when i test it, in the controller and model, it says the value is null.
what to do?
the first function:
function GetUnitInfo(){
for(i=0 ; i < $('.Worker').length ; i++){
$('.Worker').each(function(){
aUnitsInfo = [{'unitid':$(this).attr("id"),
'unitposleft':$(this).position().left,
'unitpostop':$(this).position().top
}];
jUnitsInfo.push(aUnitsInfo[i]);
aUnitsInfo = JSON.stringify(jUnitsInfo);
console.log(i);
});
console.log("unitinfo: "+jUnitsInfo[i].unitid);
console.log("uniposleft: "+jUnitsInfo[i].unitposleft);
console.log("unitpostop: "+jUnitsInfo[i].unitpostop);
console.dir(jUnitsInfo[i]);
}
}
in my log i see 3 objects with the correct values.
then i want to send it to the database:
setInterval(function(){
SaveUnits();
function SaveUnits()
{
GetUnitInfo();
$sLoginEmail = $('#TxtLoginEmail').val();
// TODO: Check that the email is valid
// console.log("The email is:"+$sLoginEmail);
$.ajax({
type: 'post',
url: 'bridge.php',
data: {"sFunction":"SaveUnits", "unitsInfo":jUnitsInfo[i]},
success: function(data){
console.log(data);
$oXml = $(data);
}
});
}
},5000);
And here's where it get's tricky. I know from the first function that my jUnitsInfo[i] is containing the right objects but after this part it seems to be null.
this is my bridge:
if($_POST['sFunction'] == "SaveUnits")
{
require_once 'Controllers/UserController.php';
$oUnitsInfo = new USerController();
echo $oUnitsInfo->SaveUnits($_POST['unitsInfo']);
}
The Controller:
public function SaveUnits($unitsInfo)
{require_once 'Models/UserModel.php';
$oUserModel = new UserModel();
$unitsInfo = json_decode($unitsInfo);
$saveUnits = $oUserModel->SaveUnits($unitsInfo);}
and the model:
public function SaveUnits($unitsInfo){
// Create connection
$con = mysqli_connect("localhost","root","","awesomegame");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$unitsInfo = array();
foreach( $unitsInfo as $row ) {
$sql[] = '("'.mysql_real_escape_string($row['unitId']).'", '.$row['unitPosTop'].','.$row['unitPosLeft'].')';
}
mysql_query('INSERT INTO units (unitid, unitpostop, unitposleft) VALUES '.implode(',', $sql));}}
And when i var dump it in the controller
var_dump(json_decode($unitsInfo));
it just comes back with a null.
how do i send the array correctly? - and get the values written to the database on drifferent rows (one for each worker).
It seems like
jUnitsInfo[i]
is reasonable since you are out of the for loop.
Take the code
function GetUnitInfoAndSave(){
var jUnitsInfo=[];
$('.Worker').each(function(){
var aUnitsInfo ={'unitid':$(this).attr("id"),
'unitposleft':$(this).position().left,
'unitpostop':$(this).position().top
};
jUnitsInfo.push(aUnitsInfo);
});
for(var i=0 ; i < jUnitsInfo.length ; i++){
var $sLoginEmail = $('#TxtLoginEmail').val();
// TODO: Check that the email is valid
// console.log("The email is:"+$sLoginEmail);
var data=$.extend({},{sFunction:"SaveUnits"},jUnitsInfo[i]);
$.ajax({
type: 'post',
url: 'bridge.php',
data: data,
success: function(data){
console.log(data);
$oXml = $(data);
}
});
//console.log("unitinfo: "+jUnitsInfo[i].unitid);
//console.log("uniposleft: "+jUnitsInfo[i].unitposleft);
//console.log("unitpostop: "+jUnitsInfo[i].unitpostop);
//console.dir(jUnitsInfo[i]);
}
}
setInterval(GetUnitInfoAndSave,5000);
PS: $.Ajax and setInterval functions are asynchronous, so you don't know when data are really sent to the server. (This code sends the array items one after another)

How to create a two-dimensional array in PHP and iterate through it with Javascript

Im currently trying to do the follow:
Request a PHP file from my image.js code
In the request call - query out data from my mysql database and save
it in a PHP array
Return the array to image.js as a JSON object.
I got nr 1 + nr 3 covered - what im strugling with is how to save my database attributes correctly into the PHP array and afterwards iterate through each record from the json callback.
Database attribute example:
player_id (unique key) || player_name || player_country || player_image || player_league ||
Question/Challenge 1: Saving the Array (this is what im not sure of)
while ($row = mysql_fetch_assoc($res))
{
$myCallbackArray[] = array($row['player_id'], $row['player_name'], $row['player_country'], $row['player_image']);
}
- The following array, will just be one "flat-array" with no dimension based on saving all corresponding attributes under seperate player_id's?
To give some some context - and assuming the array is fine, we then in a 'next-step' send it back to JS
$callback = $myCallbackArray;
echo json_encode(array('returned_val' => $callback));
Question/Challenge 2: Accessing the array values in JS (this is what im not sure of)
//Save the data
var url = "request.php"; //
var request = $.ajax({
type: "POST",
url: url,
dataType: 'json',
data: { user_id: id},
success: function(data)
{
//HERE WE HANDLE THE RETURNED ARRAY
if(data.returned_val) {
for( var i = 0; i < data.returned_val.length; i++ ){
//HERE I WOULD LIKE TO MAKE THE DIFFERENT ATTRIBUTES ACCESSABLE
}
},
error:function() {
//FAILURE
}
});
return false;
-So in this part im not sure how to actually handle the multi-dimensional array from PHP. I assume we need to save it out in a Javascript array and then we can probably iterate / access each value through an foreach loop - but yet again,- how im not entirely sure?
I'll suggest to use json_encode:
$myCallbackArray []= (object) array(
"player_id" => '...',
"player_name" => '...',
"player_country" => '...',
"player_image" => '...',
"player_league" => '...'
);
$json = json_encode($myCallbackArray);
$json is actually the following:
[{"player_id":"...","player_name":"...","player_country":"...","player_image":"...","player_league":"..."}]
which is valid JSON and you could easily use it in javascript.
I think your accessing the data wrong in your success function, the data comes back as an array. Here is an example:
var request = $.ajax({
type: "POST",
url: url,
dataType: 'json',
data: {user_id: id},
success: function(data){
var myval = data["returned_val"];
alert(myval);
},
error:function() {
//FAILURE
}
});

Retrieving Data with Jquery, AJAX, and PHP from a MySQL Database

I am trying to figure out how to retrieve data from a MySQL database using an AJAX call to a PHP page. I have been following this tutorial
http://www.ryancoughlin.com/2008/11/04/use-jquery-to-submit-form/
But i cant figure out how to get it to send back json data so that i can read it.
Right now I have something like this:
$('h1').click(function() {
$.ajax({
type:"POST",
url: "ajax.php",
data: "code="+ code,
datatype: "xml",
success: function() {
$(xml).find('site').each(function(){
//do something
});
});
});
My PHP i guess will be something like this
<?php
include ("../../inc/config.inc.php");
// CLIENT INFORMATION
$code = htmlspecialchars(trim($_POST['lname']));
$addClient = "select * from news where code=$code";
mysql_query($addClient) or die(mysql_error());
?>
This tutorial only shows how to insert data into a table but i need to read data. Can anyone point me in a good direction?
Thanks,
Craig
First of all I would highly recommend to use a JS object for the data variable in ajax requests. This will make your life a lot simpler when you will have a lot of data. For example:
$('h1').click(function() {
$.ajax({
type:"POST",
url: "ajax.php",
data: { "code": code },
datatype: "xml",
success: function() {
$(xml).find('site').each(function(){
//do something
});
});
});
As for getting information from the server, first you will have to make a PHP script to pull out the data from the db. If you are suppose to get a lot of information from the server, then in addition you might want to serialize your data in either XML or JSON (I would recomment JSON).
In your example, I will assume your db table is very small and simple. The available columns are id, code, and description. If you want to pull all the news descriptions for a specific code your PHP might look like this. (I haven't done any PHP in a while so syntax might be wrong)
// create data-structure to handle the db info
// this will also make your code more maintainable
// since OOP is, well just a good practice
class NewsDB {
private $id = null;
var $code = null;
var $description = null;
function setID($id) {
$this->id = $id;
}
function setCode($code) {
$this->code = $code;
}
function setDescription($desc) {
$this->description = $desc;
}
}
// now you want to get all the info from the db
$data_array = array(); // will store the array of the results
$data = null; // temporary var to store info to
// make sure to make this line MUCH more secure since this can allow SQL attacks
$code = htmlspecialchars(trim($_POST['lname']));
// query
$sql = "select * from news where code=$code";
$query = mysql_query(mysql_real_escape_string($sql)) or reportSQLerror($sql);
// get the data
while ($result = mysql_fetch_assoc($query)) {
$data = new NewsDB();
$data.setID($result['id']);
$data.setCode($result['code']);
$data.setDescription($result['description']);
// append data to the array
array_push($data_array, $data);
}
// at this point you got all the data into an array
// so you can return this to the client (in ajax request)
header('Content-type: application/json');
echo json_encode($data_array);
The sample output:
[
{ "code": 5, "description": "desc of 5" },
{ "code": 6, "description": "desc of 6" },
...
]
So at this stage you will have a PHP script which returns data in JSON. Also lets assume the url to this PHP script is foo.php.
Then you can simply get a response from the server by:
$('h1').click(function() {
$.ajax({
type:"POST",
url: "foo.php",
datatype: "json",
success: function(data, textStatus, xhr) {
data = JSON.parse(xhr.responseText);
// do something with data
for (var i = 0, len = data.length; i < len; i++) {
var code = data[i].code;
var desc = data[i].description;
// do something
}
});
});
That's all.
It's nothing different. Just do your stuff for fetching data in ajax.php as usually we do. and send response in your container on page.
like explained here :
http://openenergymonitor.org/emon/node/107
http://www.electrictoolbox.com/json-data-jquery-php-mysql/

Categories