getting values from db using ajax and jquery final.html - javascript

i tried to fetch database values using jquery, but it's not working
code - final.html: http://pastebin.com/vMy5invc
api.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "vhc";
$tableName = "users";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$data = array();
$result = mysql_query("SELECT `id`,`name`,`email`,`location` FROM $tableName");
while ( $row = mysql_fetch_row($result) )
{
$data[] = $row;
}
echo json_encode( $data );
?>

you shoud replace $tableName with ".$tableName."
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "vhc";
$tableName = "users";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$data = array();
$result = mysql_query("SELECT `id`,`name`,`email`,`location` FROM ".$tableName."");
while ( $row = mysql_fetch_row($result) )
{
$data[] = $row;
}
echo json_encode( $data );
?>

Related

Parse returned 2D-Array from PHP-Script to Javascript-Variable inside a Wordpress-Codeblock

So I have a standard php-script, which is stored in an external php-file that is located on the server in the main folder (in this case /html/mysite/getlocations.php).
<?php
function getData() {
// MySQL-Connection-Variables
$servername = "xxxxxxxxxx.hosting-data.io";
$username = "xxxxxxxxxxxxxxxxxx";
$password = "xxxxxxxxxxxxxx";
$dbname = "xxxxxxxxxxxx";
// Create connection
$conn = mysqli_connect( $servername, $username, $password, $dbname );
$conn_number = mysqli_connect( $servername, $username, $password, $dbname );
// Check connection
if ( !$conn ) {
die( "Connection failed: " . mysqli_connect_error() );
}
// SQL-Query for Locations
$sql = "SELECT ID, Beschreibung, Straße, Hausnummer, PLZ, Ort, Bezirk, Leiter, Email, Telefon, Website FROM Locations";
//SQL-Query for Number of Entries
$sql_number = "SELECT COUNT(*) FROM Locations;"
$result = mysqli_query( $conn, $sql );
// Size of MySQL-Table
$size = mysqli_query( $conn_number, $sql );
$counter = 0;
// 2D-Array with all the needed informations for further processing
$returnarray = array();
// Number of Table-Entries > 0
if ( mysqli_num_rows( $result ) > 0 ) {
// Iterate over all Entries
while ( $row = mysqli_fetch_assoc( $result ) ) {
$desription = $row[ "Beschreibung" ];
$street = $row[ "Straße" ];
$number = $row[ "Hausnummer" ];
$plz = $row[ "PLZ" ];
$city = $row[ "Ort" ];
$bezirk = $row[ "Bezirk" ];
$leiter = $row[ "Leiter" ];
$email = $row[ "Email" ];
$phone = $row[ "Telefon" ];
$website = $row[ "Website" ];
$returnarray[$counter] = array();
$returnarray[$counter]['name'] = $desription;
$returnarray[$counter]['street'] = $street;
$returnarray[$counter]['number'] = $number;
$returnarray[$counter]['plz'] = $plz;
$returnarray[$counter]['city'] = $city;
$returnarray[$counter]['bezirk'] = $bezirk;
$returnarray[$counter]['leiter'] = $leiter;
$returnarray[$counter]['email'] = $email;
$returnarray[$counter]['telefon'] = $telefon;
$returnarray[$counter]['website'] = $website;
$counter = $counter + 1;
}
}
// Close connection
mysqli_close( $conn );
return $returnarray;
}
echo getData();
?>
This php-scripts connects to a mysql-database, fetches information and stores it in a twodimensional array.
Now I want to retrieve this returned array and put it in a javascript-variable, so I can use it for further processing inside a Wordpress-Codeblock.
So my attempt was this:
<script type="text/javascript">
var data_from_ajax;
$.get('/html/mysite/getlocations.php', function(data) {
data_from_ajax = data;
});
</script>
But this didnt work like I intended it would.
You can create a JSON string using PHP's built-in json_encode function and parse it in JS with JSON.parse.
I don't think you can pass variables directly to Javascript without serialization.

bad request error in angularjs

var successCallback=function(response) {
if(response.success) {
$log.log(response.data);
alert('fetched courses and percentages successfully');
} else {
}
};
var errorCallback = function(response) {
console.log(response.success);
alert( "failure message: " + JSON.stringify(response));
};
var data = { "mis": 111608059};
// data = JSON.stringify(data),
$http.post('api/stu_course_%.php', data).then(successCallback, errorCallback);
The above code gives the following error:
failure message: {"data":"\n\n400 Bad Request\n\nBad RequestYour browser sent a request that this server could not understand.Apache/2.4.18 (Ubuntu) Server at localhost Port 80\n\n","status":400,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"api/stu_course_%.php","data":{"mis":111608059},"headers":{"Accept":"application/json, text/plain, /","Content-Type":"application/json;charset=utf-8"}},"statusText":"Bad Request","xhrStatus":"complete"}
Server-side code in php:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require 'config.php';
function array_push_assoc($array, $key, $value){
$array[$key] = $value;
return $array;
}
$json_request = file_get_contents('php://input');
$request = json_decode($json_request, true);
print_r( $request);
$MIS = $request["mis"];
//$MIS = 111608059;
$data = array();
$result1 = mysqli_query($conn, "select enrolled.course_id, course_code, course_name from enrolled LEFT OUTER JOIN courses ON enrolled.course_id=courses.course_id where MIS='$MIS'");
if (mysqli_num_rows($result1) > 0) {
while($row = mysqli_fetch_assoc($result1)){
$query2 = "select count(course_id) as count from attendance_item group by course_id, MIS having (MIS='$MIS' and course_id='$row[course_id]') ";
$query3 = "select count(course_id) as total_count from lecture group by course_id having course_id='$row[course_id]'";
$result2 = mysqli_query($conn, $query2);
$result3 = mysqli_query($conn, $query3);
$count = mysqli_fetch_assoc($result2);
// print_r ($count);
$total_count = mysqli_fetch_assoc($result3);
// print_r ($total_count);
$percent = $count["count"]/$total_count["total_count"] *100;
// echo $percent;
$data = array_push_assoc($data, $row["course_name"], $percent);
}
// print_r($data);
$success = 1;
json_encode($data);
}
else{
$success = 0;
}
$response = array();
$response["success"] = $success;
$response["data"] = $data;
echo json_encode($response);
?>

why can't I pass the data as json using Ajax and Jquery to the php side?

function delete_user(email)
{
//if(confirm("Do you want to remove this user with mail id: "+email))
//{
var z = {email : email}
console.log(z)
$.ajax({
url: "delete_user.php",
type: 'POST',
data: z,
success: function (data) {
console.log(data);
return false;
var i=0;
var element = "<table style='border-collapse: collapse;'>"
while(data[i] != null)
{
element = element + "<tr style='height:15px' onmouseover='rowbig(this)' onmouseout='rowsmall(this)'><td>"+data[i].fname+"&nbsp"+data[i].lname+"</td><td>"+data[i].email+"</td><td>"+data[i].dob+"</td><td><button onclick='delete_user(\""+data[i].email+"\")'><img src='delete.png' style='height:20px;width:20px'/></button></td></tr>";
i++;
}
element = element + "</table>";
$("#response").html( element );
},
cache: false,
contentType: false,
processData: false
});
//}
}
<?php
header("Content-Type:application/json");
$email ="";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function deliver_res($status_message,$result)
{
header("$status_message");
$response['status_message']=$status_message;
$response['result']=$result;
$json_response=json_encode ($response);
echo $json_response;
}
$servername = 'localhost';
$username = 'root';
$password = '';
$dbname = 'webdata';
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(isset($_POST['email']))
{
$email = test_input($_POST["email"]);
}
else
{
deliver_res("name not received","false");
exit();
}
$sqll="DELETE FROM admindata WHERE email='".$email."';";
$result = mysqli_query($conn,$sqll);
$return_arr = array();
$sqll="SELECT * FROM admindata ORDER BY id DESC ;";
$result = mysqli_query($conn,$sqll);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$row_array['fname'] = $row['fname'];
$row_array['lname'] = $row['lname'];
$row_array['email'] = $row['email'];
$row_array['dob'] = $row['dob'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
echo "\n";
mysqli_close($conn);
?>
I just can't seem to pass the data as JSON using AJAX and Jquery to the PHP side. Is there anything anything wrong with the syntax?

How to get a php array index and use it in javascript

I have a PHP script that returns a latitude and longitude from the database.
Then I have a Javascript loop that loops according to the number of rows the PHP query returns and populate my data object with the logitude and latitude at a given index. The challenge now is - how do I get the index without hard coding it?
PHP
$DBhost = 'localhost';
$DBuser = 'root';
$DBpass = '';
$DBname = 'symptoms';
$con = mysqli_connect($DBhost, $DBuser, $DBpass) or die(mysql_error());
mysqli_select_db($con, $DBname);
$query = mysqli_query($con, 'SELECT latitude,longitude FROM markers') or die(mysql_error());
$longArr = array();
$latArr = array();
$count = 0;
while ($row = mysqli_fetch_array($query)) {
$lat = $row['latitude'];
$lon = $row['longitude'];
$latArr[$count] = $lat;
$longArr[$count] = $lon;
++$count;
}
JavaScript
var latArr = [];
var longArr = [];
var markersD = [];
var num = <?php echo $count ?>;
for (var i = 0; i < num; i++) {
var data = {
lat: '<?php echo $latArr[1]?>',
lon: '<?php echo $longArr[1]?>'
}
console.log(data);
}
You have to create json object via php
while($row = mysqli_fetch_array($query))
{
$json[] = array('lat' => $row['latitude'], 'lon' => $row['longitude']);
}
$json_string = json_encode($json);
=== JS ===
var data = <?php echo json_string; ?>;
console.log(data);
You can put all your coords in one array
$coords = array();
while($row = mysqli_fetch_array($query))
{
$coords[] = array(
'latitude' => $row['latitude'],
'longitude' => $row['longitude'],
)
}
and pass it to the js as a JSON object
var data = <?php echo json_encode($coords) ?>;
console.log(data);
All data you need should be available in the javascript

make a chain combobox using JCombo

i would like to seek some help with my code because my current code wont work...i found this plugin code from this site click here...as of now all are not working even the first combobox filtration...can anyone help me get this code work please.
index.php:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script type="text/javascript" src="jquery/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="jquery.jCombo.min.js"></script>
<script type="text/javascript" src="jquery.jCombo.js"></script>
</head>
<body>
<form>
<select name="position" id="position"></select>
<select name="salary_grade" id="salary_grade"></select>
<select name="salary" id="salary"></select>
</form>
<script type="text/javascript">
$( document ).ready(function() {
$("#position").jCombo({ url: "getPosition.php", selected_value : '150' } );
$("#salary_grade").jCombo({ url: "getSalary_Grade.php?sgid=",
parent: "#position",
selected_value: '178'
});
$("#salary").jCombo({ url: "getSalary.php?salaryid=",
parent: "#salary_grade",
selected_value: '630'
});
});
</script>
</body>
</html>
getPosition.php:
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("test");
// Execute Query in the right order
//(value,text)
$query = "SELECT tcode, position FROM positions";
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row[0], "value" => htmlentities($row[1]));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
// convert into JSON format and print
$response = isset($_GET['callback'])?$_GET['callback']."(".$data.")":$data;
echo $data;
?>
getSalary_Grade.php:
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("test");
// Get parameters from Array
$sgid = !empty($_GET['tcode'])
?intval($_GET['tcode']):0;
// if there is no city selected by GET, fetch all rows
$query = "SELECT id,salary FROM salary_grades WHERE salary_grades.id = '$sgid'";
// fetch the results
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row[0], "value" => htmlentities($row[1]));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
$response = isset($_GET['callback'])?$_GET['callback']."(".$data.")":$data;
$cache->finish($response);
?>
getSalary.php:
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("test");
// Get parameters from Array
$salaryid = !empty($_GET['id'])
?intval($_GET['id']):0;
// if there is no city selected by GET, fetch all rows
$query = "SELECT id,salary FROM salarys WHERE salarys.id = '$salaryid'";
// fetch the results
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row[0], "value" => htmlentities($row[1]));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
$response = isset($_GET['callback'])?$_GET['callback']."(".$data.")":$data;
$cache->finish($response);
?>
This should work:
getSalary.php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Get parameters from Array
$salaryid = !empty($_GET['salaryid'])
?intval($_GET['salaryid']):0;
// if there is no city selected by GET, fetch all rows
$query = "SELECT id,salary FROM salarys WHERE id = $salaryid";
// fetch the results
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row['id'], "value" => htmlentities($row['salary']));
$items[] = $option;
}
}
getSalary_Grades.php
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Get parameters from Array
$sgid = !empty($_GET['sgid'])
?intval($_GET['sgid']):0;
// if there is no city selected by GET, fetch all rows
$query = "SELECT id, salary FROM salary_grades WHERE id = $sgid";
// fetch the results
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row['id'], "value" => htmlentities($row['salary']));
$items[] = $option;
}
}

Categories

Resources