PHP variable to JS variable using AJAX - php

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>

Related

get record from php with ajax and change ID attribute

i have a ajax and php as follows but it is not changing the value of html attribute with id #respo
is there any modification require?
$.ajax({
type:"POST",
url:"<?php echo base_url();?>/shortfiles/loadans.php",
dataType: "json",
data: {reccount: reccount},
success: function(response) {
var response = ($response);
$("#respo").text(response);
},
})
and php as
<?php
$id = $_POST['reccount'];
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "testsite");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt update query execution
$sql = "SELECT response from paper WHERE ID=$id";
$result=mysqli_query($link, $sql);
while ($row = mysql_fetch_row($result)) {
$response => $row['response'];
}
echo json_encode($response);
// Close connection
mysqli_close($link);
?>
i want to assign a value of response to html element with id respo
Your code must look like
$.ajax({
type:"POST",
url:"<?php echo base_url();?>/shortfiles/loadans.php",
success:function(data){
var obj = jQuery.parseJSON(data);
document.getElementById('elementName').value = obj.varaibleName;
}
});

Bootstrap Graph not rendered while using a dynamic query

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.

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

insert in database using php, json and jquery

i want to insert data to mysql database using php service and json but when i click nothing happens it shows no error no message and the data is not added to the data base help please
here is the save function
function save(){
var eml = document.getElementById("tbemail").value;
var mp = document.getElementById("tbmdp").value;
var data = {email: eml, mdp: mp}
$.ajax({
url:"http://localhost:800/test/insert.php",
type: 'POST',
data: data,
dataType: 'json',
success: function()
{alert("success");}
error: function()
{alert("fail");}
});
}
and this my php file insert.php
<?php
$json = $_POST['data'];
$new=json_decode($json, true);
$conn= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
mysqli_select_db($conn,"bd") or die ("no database");
$sql = "INSERT INTO user (email,mdp) VALUES ($new['email'],$new['mdp'])";
if (mysqli_query($conn, $sql)) {
echo "created ";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
?>
You don't have "data" key in your $_POST array, you have "email" and "mdp", which you can access directly:
$email = mysqli_real_escape_string($_POST['email']);
$mdp = mysqli_real_escape_string($_POST['mdp']);
There is no json passed in this way, similarly when you have get string, you also don't need to parse it. Turn on error reporting, then you will see that $_POST['data'] is undefined.
BTW, use mysqli_real_escape_string to sanitize the input to prevent from injection.
"Insert.php" - > Not use for get data $json = $_POST['data'];
Only use this and try
$conn= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
mysqli_select_db($conn,"bd") or die ("no database");
$email = $_POST['email'];
$mdp = $_POST['mdp'];
$new1 = json_encode($email);
$new2 = json_encode($mdp);
$sql = "INSERT INTO user ('email','mdp') VALUES ('".$new1."','".$new2."')";
$insert = mysqli_query($sql);
if ($insert) {
echo "created ";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
Your PHP code seems to be correct, but please try the jQuery AJAX code as follows:
function save(){
var eml = document.getElementById("tbemail").value;
var mp = document.getElementById("tbmdp").value;
var data = {email: eml, mdp: mp}
$.ajax({
url: "http://localhost:800/test/insert.php",
type: 'POST',
dataType: 'json',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
error: function () {
alert('fail');
},
success: function (data) {
alert('success');
}
});
}
In your data section has to be passed as JSON String, secondly you missed to in include the data contentType. Here content type is set as application/json, therefore pass the data as JSON string.

Load mysqli php data via ajax call

What I'm trying to do is calling some database data via ajax and php. But the ajax call doesn't work, and I can't find out a solution on the web.
So here is my code:
test.php
<?php
include_once 'db_class.php';
$cat = $_GET['cat'];
$dbconn = new dbconn('localhost', 'root', 'somepsw', 'blog');
$dbconn->set_query("select * from posts where category = '".$cat."'");
echo '<br/>'.$dbconn->query.'<br/>';
$result = $dbconn->result;
$num = $dbconn->num_results;
$array = mysqli_fetch_assoc($result);
echo json_encode($array);
?>
If i type that url on browser: http://127.0.0.1:82/blog/ws/test.php?cat=css
The data returned via jsonEncode is correct, but when i'm loading it on a html page with jquery he can't read the data.
test.html
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
function ajaxCall() {
var css;
$.ajax({
url: 'test.php',
type: "GET",
data: {cat: css},
dataType: 'json',
success: function(rows)
{
alert(rows);
},
error: function() { alert("An error occurred."); }
});
}
ajaxCall();
</script>
</head>
<body></body>
</html>
Thanks in advance.
I just rewrote the php code using PDO, should be more safe now.
db.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpsw = "somepsw";
$dbname= "blog";
try {
#$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpsw);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e) {
echo "Connection failed, an error occured! Please contact server administrator."; //user friendly message
getErrorsLog($e->getMessage());
}
function closeDbConn () {
$dbh = null;
}
function getErrorsLog($message) {
$file = 'dberrors.log';
$date = date("d/m : H:i :");
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new error message to the file
$current .= $date.$message;
$current .= "\r\n";
// Write the contents back to the file
file_put_contents($file, $current);
exit();
}
?>
blogdata.php
<?php
include_once "db.php";
$tableName = "posts";
$data = array();
#$view = $_GET["view"];
if (isset($_GET["view"])) {
$stmt = $dbh->prepare("SELECT * FROM $tableName WHERE category =? ORDER BY created DESC");
}
else {
try {
$stmt = $dbh->prepare("SELECT * FROM $tableName ORDER BY created DESC");
}
catch (PDOException $e) {
getErrorsLog($e->getMessage());
}
}
$stmt->bindValue(1, $view, PDO::PARAM_STR);
$stmt->execute();
$affected_rows = $stmt->rowCount(); //Rows count
if ($affected_rows == 0) {
echo "The data you looking for no longer exist, please contact the administrator.";
exit();
}
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$data[] = $row;
}
echo json_encode($data);
closeDbConn();
?>
Your variable css has no value. You wanted to use the string 'css'. Maybe you want to be able to load other categories, too. So change your ajaxCall function to
function ajaxCall(category)
{
$.ajax({
url: 'test.php',
type: "GET",
data: {cat: category},
dataType: 'json',
success: function(rows) {
alert(rows);
},
error: function() {
alert("An error occurred.");
}
});
}
and call it using
ajaxCall('css');

Categories