Submit and load with ajax json - php

index.html:
Function drawChart() {
var jsonData = $.ajax({
url: "server.php",
dataType: "json",
async: false
}).responseText;
var obj = jQuery.parseJSON(jsonData);
var data = google.visualization.arrayToDataTable(obj);
var options = {
title: 'Number of visitors / <?php echo $unit; ?>'
};
var chart = new google.visualization.BarChart(
document.getElementById('chart_div'));
chart.draw(data, options);
}
}
server.php:
$SQLString = "SELECT (...)'".$_POST['value']."' (...)
$result = mysql_query($SQLString);
(...)
$data[$i] = array(...)
echo json_encode($data);
So, index.html get data from server.php right?
Can I send some values to server.php which are important to do the query before index.html do the jsonData...etc? How?
Thanks :)

Example of a query parameter:
var jsonData = $.ajax({
url: "server.php?someQuery=" + query,
dataType: "json",
async: false
}).responseText;

You can send using post method via ajax. Here is a JQuery example:
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
http://api.jquery.com/jQuery.ajax/

you can use a library that will do it automatically for you, using phery http://phery-php-ajax.net, in your case it would be:
the event phery:json will deal with the JSON sent from the server
var remote = phery.remote('data', {'argument': 'you want to send'}, {'target':'server.php'}, false);
remote.bind('phery:json', function(event, obj){
var data = google.visualization.arrayToDataTable(obj);
var options = {
title: 'Number of visitors / <?php echo $unit; ?>'
};
var chart = new google.visualization.BarChart(
document.getElementById('chart_div'));
chart.draw(data, options);
});
remote.phery('remote'); // call the remote AJAX function
in your server.php
function data($data){
$r = new PheryResponse;
// $data['argument'] will have 'you want to send'
$SQLString = "SELECT (...)'".$_POST['value']."' (...)"
$result = mysql_query($SQLString);
(...);
$data[$i] = array(...);
return $r->json($data);
}
Phery::instance()->set(array(
'data' => 'data'
))->process();

Related

How populate chart.js with sql data?

I'm using chart.js to generate charts on my page.
However I want these charts to be populated by my SQL database.
I'm able to get my data out of my database, but I won't draw the chart
I got a canvas on my main page called "OmzetChart" , this is where the chart should come.
<script>
$.ajax({
type: 'POST',
url: 'templates/getdata.php',
success: function (data) {
lineChartData = data;
//alert(JSON.stringify(data));
var ctx = document.getElementById("OmzetChart").getContext("2d");
var myLineChart = new Chart(ctx, {
type: 'line',
data: lineChartData
});
}
});
</script>
The page of GetData.php results in the following (This is what I need, just want it into my chart):
[{"dag":"23","0":"23","uur":"13","1":"13","SomOmzet":"23.00","2":"23.00"},{"dag":"23","0":"23","uur":"18","1":"18","SomOmzet":"2.50","2":"2.50"}]
Getdata.php:
<?php
include ("../PDO.php");
$conn = DatabasePDO::getInstance();
$sql = "SELECT DATEPART(DD, receiptdatetime) as dag ,DATEPART(hh, receiptdatetime) as uur, ISNULL(abs(cast(sum(NetAmount) as decimal (10,2))),0) as SomOmzet FROM ReceiptLine a , Receipt b, ReceiptLineDetail c
where a.LineType = 200 and a.receiptID = b.receiptid and a.receiptlineID = c.receiptlineID
group by DATEPART(DD, receiptdatetime), DATEPART(hh, receiptdatetime)";
$st = $conn->prepare($sql);
$st->execute();
$list = array();
while ( $row = $st->fetch() ) {
$list[] = $row;
}
$conn = null;
echo json_encode( $list );
?>
json_encode() produces a JSON string. You need to parse this with JSON.parse() before you can use it.
$.ajax({
type: 'POST',
url: 'templates/getdata.php',
success: function (data) {
lineChartData = JSON.parse(data); //parse the data into JSON
var ctx = document.getElementById("OmzetChart").getContext("2d");
var myLineChart = new Chart(ctx, {
type: 'line',
data: lineChartData
});
}
});
Also, using $.ajax() method's dataType parameter, you can leave this parsing to jQuery.
$.ajax({
type: 'POST',
url: 'templates/getdata.php',
dataType: 'json', //tell jQuery to parse received data as JSON before passing it onto successCallback
success: function (data) {
var ctx = document.getElementById("OmzetChart").getContext("2d");
var myLineChart = new Chart(ctx, {
type: 'line',
data: data //jQuery will parse this since dataType is set to json
});
}
});

json object in php not being read

I want to pass username and password to a php script and check in the database. On the client side I use the following script to make a json object and post it to the php file.
var myobj = {};
myobj["usrname"]= $( "#customer option:selected" ).text();
myobj["usrpass"]= $("#psw").val();
var myjson = JSON.stringify(myobj);
$.ajax({
method: "POST",
url: "checkpass.php",
data: myjson
})
.done(function( msg ) {
alert( msg );
});
On the server side, when I see in firebug, the post is passed as
Parametersapplication/x-www-form-urlencodedDo not sort
{"usrname":"XXXXXXX...
JSON
usrname
"XX"
usrpass
"justdoit"
Source
{"usrname":"XXX","usrpass":"justdoit"}
however when i run the php script to check the query the it returns an error
$usrname = $_POST['usrname'];
$usrpass = $_POST['usrpass'];
$sql = "select count(*) from glusers where EmpName='$usrname' and EmpPass='$usrpass'";
$result = $conn->query($sql);
if($result >0){
$output = 'Success';
} else
{
$output = 'fail';
}
I have tried through all the posts but cannot get this to work.
Thanks in advance.
Regards,
Echo and die the statement in order for ajax to have a success event
Js File
var myobj = {};
myobj["usrname"] = 'myUsername';
myobj["usrpass"] = 'myPassword';
$.ajax({
type: "post",
url: "url",
dataType: "json",
data: {post_data: myobj},
contentType: "application/x-www-form-urlencoded",
success: function (responseData) {
console.log(responseData);
},
error: function (errorThrown) {
console.log(errorThrown);
}
});
PHP action File
/** if we print post we will get the following array * */
//print_r($_Post);
//die()
//Array
//(
// [post_data] => Array
// (
// [usrname] => myUsername
// [usrpass] => myPassword
// )
//
//)
if (isset($_Post['post_data'])) {
$myPost = $_Post['post_data'];
$usrname = $myPost['usrname'];
$usrpass = $myPost['usrpass'];
$sql = "select count(*) from glusers where EmpName='$usrname' and EmpPass='$usrpass'";
$result = $conn->query($sql);
$num_row = $result->num_rows;
if ($num_row > 0) {
$output = 'Success';
} else {
$output = 'fail';
}
echo json_encode($output);
die();
}
Try This :
in js file :
$(document).on("ready", function(){
// Create an object using an object literal.
var ourObj = {};
// Create a string member called "data" and give it a string.
// Also create an array of simple object literals for our object.
ourObj.data = "Some Data Points";
ourObj.arPoints = [{'x':1, 'y': 2},{'x': 2.3, 'y': 3.3},{'x': -1, 'y': -4}];
var savedata = JSON.stringify(ourObj)
$.ajax({
type:"POST",
url:"Users.php",
data: {"points" : JSON.stringify(ourObj)},
success: function(data) {
// Do something with data that came back.
alert(data);
}
})
});
In PHP File :
if (isset($_POST["points"])) {
$points = json_decode($_POST["points"]);
echo "Data is: " . $points->data . "<br>";
echo "Point 1: " . $points->arPoints[0]->x . ", " . $points->arPoints[0]->y;
}
Try this:
var myobj = '{
usrname:'+$( "#customer option:selected" ).text()+',
usrpass:'+$("#psw").val()+'
}';
or
var myobj = {};
myobj.usrname= $( "#customer option:selected" ).text();
myobj.usrpass= $("#psw").val();
Use Json2 library as follows,
var myobj = {};
myobj["usrname"]= $( "#customer option:selected" ).text();
myobj["usrpass"]= $("#psw").val();
var myjson = JSON2.stringify(myobj);
$.ajax({
method: "POST",
url: "checkpass.php",
data: myjson
})
.done(function( msg ) {
alert( msg );
});
Well actually you php code is invalid because you pass json day not name value pair so you cant get it from $_POST['username']. You need to get the whole post data and decode it like this.
$data = json_decode(file_get_contents('php://input'), true);
Now $data is dictionary array of username and password. Also sanitize your data before passing to query to avoid sql injection.

Error when using jQuery Ajax POST (json) with php

On page load I use this code to display data from database:
<script>
$(function feed(){
var page = 1;
var type = '<?php echo $filter ;?>';
var theData = {};
theData['page'] = 'profile';
theData['type'] = type;
theData['username'] = '<?php echo $user_data->username; ?>';
theData['get_activities'] = 'true';
$.ajax({
type: "POST",
url: "data.php",
data: theData,
dataType:'json',
success: function(data){
$("#activities").html(data.activity_feed);
if(page < data.total_pages){
$("#activities").after('<div id="loader"><button id="load_more_activities">Load more</button></div>');
}
}
});
$("#activity_container").on("click", "#load_more_activities", function(){
var next = page+=1;
var type = '<?php echo $filter ;?>';
var theData = {};
theData['page'] = 'profile';
theData['type'] = type;
theData['username'] = '<?php echo $user_data->username; ?>';
theData['get_activities'] = 'true';
theData['page_num'] = next;
$.ajax({
type: "POST",
url: "data.php",
data: theData,
dataType: "json",
success: function(data){
$("#activities").append(data.activity_feed);
if(next == data.total_pages){
$("#loader").html("No more data");
} else {
$("#loader").html('<div id="loader"><button id="load_more_activities">Load more</button></div>');
}
},
});
});
});
</script>
Everything work fine, but if I refresh page more than 5 or 6 times or if load_more_activities function is called more than 5 or 6 times...then post is not executed and I don't get any data displayed...
Is something wrong with this code or there are maybe some restrictions from my host provider?
When post is executed:
When post is not executed:
My host provider has a protection from several sending ajax data with variables named "username" or "password". So when this happens, server detect some kind »brute-force« and then drop-all-packets.

send data through an array

I want to send data through an array
This transmitter code:
<script type="text/javascript">
$(function() {
$(".cat_button").click(function() {
var element = $(this);
var test = $("#cou").val();
var test2 = $("#category2").val();
var data = [
{data:test},
{data:test2}
];
if(test=='' || test2=='.....')
{
alert("fill data");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="http://tiggin.com/ajax-loader.gif" align="absmiddle"> <span class="loading">Loading...</span>');
$.ajax({
type: "POST",
url: "insert2.php",
data: {data: data},
cache: false,
success: function(response){
console.log(response);
}
});
}
return false;
});
});
</script>
This code reception:
print_r($_POST['data']); // dumps an array
$course = $_POST['data'][0]['data'];
$category = $_POST['data'][1]['data'];
$insert_new_cou = mysql_query("insert into course (name,cat_id) values ('$course','$category')") or die($insert_new_cou."<br/><br/>".mysql_error());
But show me the following error:
Cannot use string offset as an array
I think the solution using Jtgson but I do not know how to use it
It can be done by JSON encoding your array of objects. In the $.ajax call:
...
url: "insert2.php",
data: {data: JSON.stringify(data)},
...
On the PHP side use json_decode() to get an array of objects from the JSON string:
$data = json_decode($_POST['data']);
$course = $data[0]->data;
$category = $data[1]->data;

jquery passing variables to php file

acctually i am not familier much with jquery.. i got this jquery script this is passing variables to the file which is showing data in json format.. but here i'm unable to show that data..plz see this piece of code
$(document).ready(function() {
var globalRequest = 0;
$('#search').bind('keyup', function(event) {
if (event.keyCode == 13) {
searchAction();
}
});
$('#search-link').bind('click', function(event) {
searchAction();
});
var searchAction = function() {
var value = $('#search').val();
var cat = $('#category').val();
var country = $('#country').val();
var page = $('#page').val();
var resultContainer = $('#results');
if (value.length < 3 && globalRequest == 1) {
return;
}
_gaq.push(['_trackEvent', 'Search', 'Execute', 'Page Search', value]);
globalRequest = 1;
$.ajax({
url: "search.php",
dataType: 'json',
type: 'GET',
data: "q="+value+"&category="+cat+"&country="+country+"&page="+page,
success: function(data){
globalRequest = 0;
resultContainer.fadeOut('fast', function() {
resultContainer.html('');
console.log(data.length);
for (var x in data) {
if (!data[x].price)
data[x].price = 'kA';
if (!data[x].img)
data[x].img = 'assets/images/no.gif';
var html = '<div class="res-container">';
html += '<h2>'+data[x].Title+'</h2>';
html += '<img src="'+data[x].img+'">';
html += '<h3>Price: '+data[x].price+'</h3>';
html += '</div>';
resultContainer.append(html);
}
resultContainer.fadeIn('fast');
});
}
});
};
});
in search.php data is in simple echo.. how to get data from search.php and show here..
sorry for bad english
First,
you shouldn't concatenate your parameters but use a hashmap:
$.ajax({
url: "search.php",
dataType: 'json',
type: 'GET',
data: {
q : value,
category : cat,
country : country,
page : page }
As your method is (type: 'GET'), just use the ($_GET[param] method) in the php file
<?php
$value = htmlentities($_GET['q']);
$category = htmlentities($_GET['category ']);
$country = htmlentities($_GET['country ']);
In the js callback function, this is how you log the whole response ('something' is a tag) :
success: function(data){
var $xml = $(data);
console.log($xml); // show the whole response
console.log($xml.find('something')); // show a part of the response : <something>value</something>
});
It is a bit hard to understand what your problem is but my guess is that you need to json encode the data before echoing it back in search.php.
simplified example......
eg.
<?php
$somevar = $_GET['a']
$anothervar = $_GET['b']
//Do whatever
$prepare = array('a'=>$result1,'b'=>$result2) //etc..
$json = json_encode($prepare);
echo $json;
exit();
?>
Then you can access the results in the javascript with:
success: function(data){
var obj = $.parseJSON(data);
alert(data.a);
$("#some_element").html(data.b);
}

Categories