Bootstrap Graph not rendered while using a dynamic query - php

The graph executes correctly when i use a static query. But when i use a dynamic query it doesnt render even when the query returned is same to the static query.
//$sql = "SELECT `". $_GET["field2"] ."`, COUNT(*) as defectCount FROM `defects` GROUP BY `". $_GET["field2"] ."`";
$sql = "SELECT `user_13`, COUNT(*) as defectCount FROM `defects` GROUP BY `user_13`";
Here the commented code doesnot works but the other one works though they throw the same query when i checked on my console.
//code in pie.php
$("#submitgraph").click(function()
{
var graph_type=$("#graph_type").val();
var field_one=$("#field_type1").val();
var field_two=$("#field_type2").val();
$.ajax({
url: "http://localhost/ac/data/data.php?field1="+field_one+"&field2="+field_two,
type: "GET",
async: true,
success: function(response){
console.log(response);
setTimeout(function(){
if(graph_type=="piechart")
{
document.getElementById("pie_draw").style.display = "block";
}
}, 1000);
}
});
});
////code in data.php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "hp";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT `". $_GET["field2"] ."`, COUNT(*) as defectCount FROM `defects` GROUP BY `". $_GET["field2"] ."`";
//the commented code works
//$sql = "SELECT `user_13`, COUNT(*) as defectCount FROM `defects` GROUP BY `user_13`";
$result = $conn->query($sql);
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
$result->close();
$conn->close();
echo json_encode($data);
?>
//code in data_a.js
//Flot Pie Chart
$(function() {
//var data ;
$.ajax({
url : "data/data.php",
type : "GET",
dataType: 'json',
success : function(data){
var datas = [];
for(i=0;i<data.length;i++) {
var obj = {
label : data[i].user_13,
data : data[i].defectCount
};
datas.push(obj);
}
var plotObj = $.plot($("#flot-pie-chart"), datas, {
series: {
pie: {
show: true
}
},
grid: {
hoverable: true
},
tooltip: true,
tooltipOpts: {
content: "%p.0%, %s", // show percentages, rounding to 2 decimal places
shifts: {
x: 20,
y: 0
},
defaultTheme: false
}
});
}
});
});

I Think one of the problem is that your ajax request type is
type : "POST"
in code in pie.php
but in your data.php your request type become GET
Try to change the
$_GET["field2"]
to
$_POST["field2"]
let me know if it works.

Related

Check if value is exist in database jQuery and php

I m having a bit of trouble while validating value in database.
This is my html and js Code:
<input type="text" name="Unieke-voucher" value="" size="40" maxlength="8" minlength="8" id="voucher" aria-required="true" aria-invalid="false" placeholder="XYZ 1234">
var searchTimeout; //Timer to wait a little before fetching the data
jQuery("#voucher").keyup(function() {
vCode = this.value;
clearTimeout(searchTimeout);
searchTimeout = setTimeout(function() {
getUsers(vCode);
}, 400); //If the key isn't pressed 400 ms, we fetch the data
});
var searchTimeout; //Timer to wait a little before fetching the data
jQuery("#voucher").keyup(function() {
vCode = this.value;
clearTimeout(searchTimeout);
searchTimeout = setTimeout(function() {
getUsers(vCode);
}, 400); //If the key isn't pressed 400 ms, we fetch the data
});
function getUsers(vCode) {
jQuery.ajax({
url: 'voucher.php',
type: 'GET',
dataType: 'json',
data: {value: vCode},
success: function(data) {
if(data.status) {
jQuery("#codeError").html('');
console.log(data);
} else {
jQuery("#codeError").html('Value not found');
}
console.log(data);
}
});
}
With this getting value with keyup event and sending to php script till here working fine.
And this is php script:
$dbname = "voucher";
$dbuser = "root";
$dbpass = "root";
$dbhost = "localhost";
// Create connection
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$voucherCode = $_GET['VoucherCode'];
$voucherCode['status'] = false;
//echo $voucherCode;
$result = mysqli_query($conn, "SELECT * FROM VoucherCode WHERE `code` LIKE '$voucherCode' LIMIT 1");
if(mysqli_num_rows($result)) {
$userData = mysqli_fetch_assoc($result);
$voucherCode['code'] = $Code;
$voucherCode['status'] = true;
}
echo json_encode($voucherCode);
I am always getting status value even providing correct value.
When i print_r table like
$resultAll = mysqli_query($conn, "SELECT * FROM VoucherCode");
$data2 = mysqli_fetch_all($resultAll);
print_r($data2);
I am able to see all data is there.
I am not sure what i am doing wrong here. Can anyone help me with this please.
Thanks in advance.

PHP variable to JS variable using AJAX

I'm trying to convert a PHP variable to a JS variable so I can use it in a game I'm making. When I check the map code it is just undefined. Thanks in advance. FYI the PHP works.
<script>
var mapCode;
var used;
var active;
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
data: {
mapCode: $mapCode,
used: $used,
active: $active,
},
dataType: "text",
});
}
</script>
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
mysqli_select_db($conn, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
// echo "Connected successfully";
$query = "SELECT mapCode FROM mapCodes";
$result = mysqli_query($conn, $query);
$mapCode = mysqli_fetch_row($result);
$query1 = "SELECT used FROM mapCodes";
$result1 = mysqli_query($conn, $query1);
$used = mysqli_fetch_row($result1);
$query2 = "SELECT active FROM mapCodes";
$result2 = mysqli_query($conn, $query2);
$active = mysqli_fetch_row($result2);
mysqli_close($conn);
?>
I understand that the PHP Code is hideous but it works and I'm going to 'pretty it up' later when the whole thing is working
If the file extension is .php and not .js then this should work
<script>
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
data: {
mapCode: "<?php echo $mapCode; ?>",
used: "<?php echo $used; ?>",
active: "<?php echo $active; ?>",
},
dataType: "text",
});
}
</script>
If you have .js file then declare javascript variable before including your js in .php file
<script>
var mapCode = "<?php echo $mapCode; ?>";
var used = "<?php echo $used; ?>";
var active = "<?php echo $active; ?>";
</script>
then in .js file you will get easily
<script>
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
data: {
mapCode: mapCode,
used: used,
active: active,
},
dataType: "text",
});
}
</script>
You only need to use <?php echo $mapCode;?> instead $mapCode. .... php variables can't be reed whithout open Php tag
My current project is actually dealing with lots of ajax calls,
here is the simplified version of what I use to communicate with server:
// php
// needed functions
function JSONE(array $array)
{
$json_str = json_encode( $array, JSON_NUMERIC_CHECK );
if (json_last_error() == JSON_ERROR_NONE)
{
return $json_str;
}
throw new Exception(__FUNCTION__.': bad $array.');
}
function output_array_as_json(array $array)
{
if (headers_sent()) throw new Exception(__FUNCTION__.': headers already sent.');
header('Content-Type: application/json');
print JSONE($array);
exit();
}
// pack all data
$json_output = array(
'mapCode' => $mapCode,
'used' => $used,
'active' => $active
);
// output/exit
output_array_as_json( $json_output );
// javascript
function _fetch()
{
return $.ajax({
url: 'getMapCode.php', // url copied from yours
type: 'POST',
dataType: 'json',
success: function(data, textStatus, req){
console.log('server respond:', data);
window.mydata = data;
},
error: function(req , textStatus, errorThrown){
console.log("jqXHR["+textStatus+"]: "+errorThrown);
console.log('jqXHR.data', req.responseText);
}
});
}
window.mydata = null;
_fetch();
I have not tested this, but let me know I'll fix it for you.
How did i get you, you need to get the result from ajax request, to do it, you should first setup your php outputs your results, so the ajax can get outputed results from php like this:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
mysqli_select_db($conn, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
// echo "Connected successfully";
$query = "SELECT mapCode FROM mapCodes";
$result = mysqli_query($conn, $query);
$mapCode = mysqli_fetch_row($result);
$query1 = "SELECT used FROM mapCodes";
$result1 = mysqli_query($conn, $query1);
$used = mysqli_fetch_row($result1);
$query2 = "SELECT active FROM mapCodes";
$result2 = mysqli_query($conn, $query2);
$active = mysqli_fetch_row($result2);
mysqli_close($conn);
// Outputing results:
echo json_encode(array('mapCode'=>$mapCode[0], 'used'=>$used[0], 'active'=>$active[0]));
?>
Then in ajax, use success for listening return message after ajax finished:
<script>
var mapCode;
var used;
var active;
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
data: {
/** Your data to send to server **/
},
dataType: "text",
success: function(data) { /** Here is data returned by php echo **/
var temp = $.parseJSON(data);
mapCode = temp['mapCode'];
used = temp['used'];
active = temp['active'];
}
});
}
</script>

why jquery-ui autocomplete list does not show on large list

On smaller list of options the autocomplete drop down list does show on focus. but if the options are more than a specific number (50 to be exact) it no longer shows.
How to make it show no matter what the number of options in the list ?
$(document).ready(function() {
var sst;
//auto complete for artist
$('#artist').autocomplete({
source: 'artists.php',
minLength: 0,
select: function(a, b) {
sst = b.item.value;
}
}).focus(function() {
$(this).data("uiAutocomplete").search($(this).val());
});
//auto complete for title
$('#title').autocomplete({
source: function(request, response) {
$.ajax({
url: "titles.php",
dataType: "json",
data: {
q1: sst,
q2: request.term
},
success: function(data) {
response(data);
}
});
},
minLength: 0
}).on('focus', function(event) {
$(this).autocomplete("search", "");
});
});
the mysql query :
<?php
$db = mysql_connect('localhost','root','1313');
if(!$db){
die( "connection failed ");
}
$db_s = mysql_select_db("LYRICSFINDER",$db);
$data = array();
$searchTerm1 = trim(strip_tags($_GET["q1"]));
$searchTerm1 = addslashes($searchTerm1);
$searchTerm2 = trim(strip_tags($_GET["q2"]));
$searchTerm2 = addslashes($searchTerm2);
$query = "SELECT TITLE FROM DATA WHERE ARTIST LIKE '%".$searchTerm1."%' AND TITLE LIKE '%".$searchTerm2."%' ORDER BY TITLE ASC";
$result = mysql_query($query,$db);
$i=0;
while($row = mysql_fetch_assoc($result) ){
$data[] = $row['TITLE'];
$i++;
if($i>50)break;
}
mysql_close($db);
echo json_encode($data);
?>

Send GET in Ajax call and PHP script

I want to POST data from form. It works fine.
In the other functionality i want to get data from database.
I don't know where is mistake. I suspect that AJAX call is fine.
My PHP code:
<?php
$uuid = $_POST['uuid'];
$minor = $_POST['minor'];
$mayor = $_POST['mayor'];
$lokalizacja = $_POST['lokalizacja'];
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else{
echo "Polaczono";
}
$sql = "INSERT INTO beacons (uuid, major, minor, lokalizacja)
VALUES ('$uuid', '$minor', '$mayor', '$lokalizacja')";
if ($conn->query($sql) === TRUE) {
echo "Dane dodano prawidłowo";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sqlget = "SELECT uuid, major, minor, lokalizacja FROM beacons";
$result = $conn->query($sqlget);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo json_encode(array("value" => "UUID: " . $row["uuid"]));
}
} else {
echo "Brak rekordów w bazie";
}
$conn->close();
?>
AJAX call:
$('#admin').submit(function(e){
e.preventDefault();
if( ($("input[name=uuid]").val().length) > 40 || ($("input[name=minor]").val().length) > 5 || ($("input[name=mayor]").val().length) > 5 || ($("input[name=lokalizacja]").val().length) > 20){
$(".error-pola").show();
} else{
$.post('administrator-connect.php', $(this).serialize() )
.done(function(){
$(".success-wyslanie").show();
})
.fail(function(){
$(".error-wyslanie").show();
});
}
});
$(document).ready(function() {
$.ajax({
type: "GET",
url: 'administrator-connect.php',
dataType: 'json',
success: function(data)
{
alert("fsdfsd"+ data);
},
error: function(){
alert("not");
}
});
});
I am using:
echo json_encode(array("UUID" => $row["uuid"]));
and in ajax:
var jqxhr = $.get( "administrator-get.php", function(data) {
var jsonx = JSON.parse(JSON.stringify(data));
$( "#data-listing" ).html(jsonx);
});
But I get response:
{"UUID":"B9407F30-F5F8-466E-AFF9-25556B57FE6D"}
How to get only string ?
If you write this
dataType: 'json',
It expect for JSON value not string be sure to return only JSON.
You returns string value not JSON.
With like this code
echo "Polaczono";
Any echo would be the return value for ajax
At last you should return only one value like this.
echo json_encode($result);//an array result
You can check by string return. By removing dataType

how to use ajax in wordpress to show database columns using php and Json

I'm new using ajax and I have a code to display from wordpress some information from database columns.
I have this PHP code to connect with the database and create the JSON file:
<?php
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if (isset($username) && isset($password)) {
//CONEXION
$host="localhost";
$user="DB_Username";
$pass="DB_Password";
$dbname="DB_Name";
//Conexion
$conexion = mysqli_connect($host, $user, $pass,$dbname)
or die("unexpected error");
//gWe made the search
$sql = "SELECT * FROM Column WHERE A_Login='$username'";
mysqli_set_charset($conexion, "utf8");
if(!$result = mysqli_query($conexion, $sql)) die();
$clients = array();
$num_result = mysqli_num_rows($result);
if ($num_result == 0) {
$clients = array("error" => "true", "msg" => "We can't found this user", "data" => $username);
} else {
while($row = mysqli_fetch_array($result))
{
$id=$row['ID'];
$Name=$row['Name'];
if ($row['A_Login'] == $username && $row['A_Password'] == $password){
$clients[] = array('id'=> $id, 'Name'=> $Name);
} else {
$clients[] = array('error'=> "true", "msg" => "Incorrect data");
}
}
}
$close = mysqli_close($conexion)
or die("Unespected error with DB");
}
else {
$clients = array("error" => "true", "msg" => "You must fill all fields", "username" => $username);
}
//We build the JSON
$json_string = json_encode($clients);
echo $json_string;
?>
In a wordpress page I have this code, I build a form where if the user click the submit button call doLogin()
<script type="text/javascript"> function doLogin(){
data = {username: jQuery("#user").val(), password: jQuery("#pass").val()}
console.log(data);
jQuery.ajax({
type: "POST",
url: "Mywebsiteurl.php",
data: data,
beforeSend: function(){
},
success: function(data){
console.log(data);
//var arr = JSON.parse(data);
//$('#forma').html(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
console.log(textStatus);
console.log(errorThrown);
}
});
} </script>
I need to show in <div id="forma"> a kind of list usign html, for example:
Id: VALUE ID
Name: VALUE NAME
and more information...
When i try to print in my website the required information using $('#forma').html(data); I obtain error or just an empty space.
How can I fix it? thanks.
In WordPress we need to hook the ajax hook to your check_user function here.
add_action('wp_ajax_your_action_from_js', 'your_function');
//Using ajax for non-logged users as well (PUBLIC)
add_action('wp_ajax_nopriv_your_action_from_js', 'your_function');
Check below code for how it is done regarding your context.
In functions.php
function check_user() {
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if (isset($username) && isset($password)) {
//CONEXION
$host="localhost";
$user="DB_Username";
$pass="DB_Password";
$dbname="DB_Name";
//Conexion
$conexion = mysqli_connect($host, $user, $pass,$dbname)
or die("unexpected error");
//gWe made the search
$sql = "SELECT * FROM Column WHERE A_Login='$username'";
mysqli_set_charset($conexion, "utf8");
if(!$result = mysqli_query($conexion, $sql)) die();
$clients = array();
$num_result = mysqli_num_rows($result);
if ($num_result == 0) {
$clients = array("error" => "true", "msg" => "We can't found this user", "data" => $username);
} else {
while($row = mysqli_fetch_array($result))
{
$id=$row['ID'];
$Name=$row['Name'];
if ($row['A_Login'] == $username && $row['A_Password'] == $password){
$clients[] = array('id'=> $id, 'Name'=> $Name);
} else {
$clients[] = array('error'=> "true", "msg" => "Incorrect data");
}
}
}
$close = mysqli_close($conexion)
or die("Unespected error with DB");
}
else {
$clients = array("error" => "true", "msg" => "You must fill all fields", "username" => $username);
}
//We build the JSON
$json_string = json_encode($clients);
echo $json_string;
}
add_action('wp_ajax_check_user', 'check_user');
//Using ajax for non-logged users as well (PUBLIC)
add_action('wp_ajax_nopriv_check_user', 'check_user');
In your JS called file.
In the script the action is related to your _your_action_from_js. So action is needed for knowing where the ajax has to hit. In our case it executes our check_user and returns the appropriate values.
<script type="text/javascript">
function doLogin(){
data = {action: 'check_user', username: jQuery("#user").val(), password: jQuery("#pass").val()}
console.log(data);
jQuery.ajax({
type: "POST",
url: ajax_url,
data: data,
beforeSend: function(){
},
success: function(data){
console.log(data);
//var arr = JSON.parse(data);
//$('#forma').html(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
console.log(textStatus);
console.log(errorThrown);
}
});
}
</script>
Reference Simple AJAX Form: http://wptheming.com/2013/07/simple-ajax-example/
CODEX Reference: https://codex.wordpress.org/AJAX_in_Plugins
WordPress has specific methods to enable ajax requests.
// registering ajax request for Logged users
add_action( 'wp_ajax_my_action', 'my_action_callback' );
// registering ajax request also for public area
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
function my_action_callback()
{
// Your code here
wp_die(); // this is required to terminate immediately and return a proper response
}
To call it:
jQuery(document).ready(function($) {
var data = {action: "my_action", username: jQuery("#user").val(), password: jQuery("#pass").val()}
jQuery.ajax({
url: '/wp-admin/admin-ajax.php',
data: data,
method: 'POST',
success: function(response) {
console.log(response);
},
error: function(a,b,c) {
}
});
});
Source: https://codex.wordpress.org/AJAX_in_Plugins

Categories