ajax error, the data is burried - javascript

this is my code
main.js
var save_method, table;
//Menerapkan plugin datatables
$(function(){
table = $('.table').DataTable({
"processing" : true,
"ajax" : {
"url" : "ajax/ajax_user.php?action=table_data",
"type" : "POST"
}
});
});
ajax_user.php
<?php
include "../config/database.php";
include "../library/view.php";
if ($_GET['action'] == "table_data") {
$query = mysqli_query($mysqli, "SELECT p.*, v.nama_provinsi, k.nama_kota, j.nama_tagihan FROM pelanggan P
INNER JOIN provinsi v ON p.id_provinsi = v.id_provinsi
INNER JOIN kota k ON p.id_kota = k.id_kota
INNER JOIN jenis_tagihan j ON p.id_jenis_tagihan = j.id_jenis_tagihan
ORDER BY p.id DESC");
$data = array();
$no = 1;
while($p = mysqli_fetch_assoc($query)) {
$row = array();
$row[] = $no;
$row = $p['nama_masjid'];
$row = $p['nama_pengurus'];
$row = $p['id_pelanggan'];
$row = $p['tagihan'];
$row = $p['nama_provinsi'];
$row = $p['nama_kota'];
$row = $p['nama_tagihan'];
$data[] = $row;
$no++;
}
$output = array("data" => $data);
echo json_encode($output);
}
?>
and this is my error
The last data in the array appears but the previous data disappears what's wrong ?

try this :
$data = [];
$i=0;
while($p = mysqli_fetch_assoc($query)) {
$data[$i]['nama_masjid'] = $p['nama_masjid'];
$data[$i]['nama_pengurus']= $p['nama_pengurus'];
$i++;
}
echo json_encode($data);

Related

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);
?>

Executing a Php Mysql function from Onclick NO POST

I have a php Mysql interaction and i wish to trigger the Mysql Search through an ONCLICK event.
iv thought about using a JS function or JQ and parsing the ID of selected through JS function but then im unsure as how i would re-execute the php to re-search the database with the new JS Veriable...
The code below is accurate and is what im working with...
How would i re execute the php with the new ID.. Much appreciated..
<div class="contentheader">
<header> Welcome Please Choose a Catagory</strong></header>
</div>
<div id='smallpagination' class='smallpagination'>
<?php
//search according to chosen search critera NOT LIMITED//
include("conect.php");
$startit = 0;
$startfrom = rand(0, 20);
$displayto = $startfrom + 10;
$search = "";
$startedfrom = $startfrom;
$sql = "SELECT * FROM testdata
WHERE title LIKE '%%$search%%'
LIMIT $startfrom , $displayto";
// check how many results //
$result = $conn->query($sql);
$row_cnt = $result->num_rows;
while ($row = mysqli_fetch_assoc($result)) {
$videos = $row['videos'];
$v_id = $row['id']; //<!---important is Video ID and needed for video click selection---->
$id = $row['id'];
$Name = $row['Name'];
if (empty($Name)) {
$Name = 'Annonymous';
}
$image = $row['image'];
$info = $row['info'];
if (empty($info)) {
$info = 'Contact Listee (if Provided) , No Item Information Given';
}
$phone = $row['phone'];
if (empty($phone)) {
$phone = 'See Listing';
}
$title = $row['title'];
$locate = $row['locate'];
if (empty($locate)) {
$locate = 'Not Provided';
}
$postcoded = $row['postcode'];
if (empty($postcoded)) {
$postcoded = '???';
}
$price = $row['price'];
if (empty($price)) {
$price = '?';
}
if ($price == '0') {
$price = '?';
}
$date = $row['stamp'];
if (empty($date)) {
$date = '';
}
if ($startit < 1) {
$gotid = $row['id'];
$startit = $startit + 1;
};
$vidd = $row['id'] - 0.01;
$pidd = $row['id'] - 0.02;
$type = $row['type'];
$showinglocate = $row['id'] - 0.03;
$showingphone = $row['id'] - 0.04;
$displaytype = "minlist";
//Thumbnails sized listings
if ($displaytype == "minlist") {
echo "
<div class='floaterminhomepage'>
<div class='innerfloaterminhomepage' >";
if (!empty($videos)) {
echo "
<video id='$v_id' style='position:absolute; top:0%; left:0%; width:100%; height:100%; background-size: cover; object-fit:fill;' preload='metadata' onclick='showdata({$v_id});'>
<source src='vid/{$row['videos']}.mp4' type='video/mp4'>
<source src='vid/{$row['videos']}.mp4' type='video/ogg'>
<source src='vid/{$row['videos']}.mp4' type='video/webm'>
</video >";
}
if (empty($videos)) {
echo "<img id='$vidd' src='pageimages/blank.png' style='position:absolute; top:0%; left:0%; width:100%; height:100%;'>";
}
echo "
</div>
</div>
";
}
};
?>
</div> <!---smallpagination--->
<script>
------ > SHOWDATA
RETRIEVE
ID
SCRIPT
HERE < -----
</script>
Then re-execute the folling php
----HOW WOULD I GO ABOUT THIS RE_EXECUTION.
<?php
$displayto = $startfrom;
$sql = "SELECT * FROM testdata
WHERE id={$gotid};
";
// check how many results //
$result = $conn->query($sql);
$row_cnt = $result->num_rows;
while ($row = mysqli_fetch_assoc($result)) {
$videos = $row['videos'];
$v_id = $row['id']; //<!---important is Video ID and needed for video click selection---->
$Name = $row['Name'];
if (empty($Name)) {
$Name = 'Annonymous';
}
$image = $row['image'];
$info = $row['info'];
if (empty($info)) {
$info = 'Contact Listee (if Provided) , No Item Information Given';
}
$phone = $row['phone'];
if (empty($phone)) {
$phone = 'See Listing';
}
$title = $row['title'];
$locate = $row['locate'];
if (empty($locate)) {
$locate = 'Not Provided';
}
$postcoded = $row['postcode'];
if (empty($postcoded)) {
$postcoded = '???';
}
$price = $row['price'];
if (empty($price)) {
$price = '?';
}
if ($price == '0') {
$price = '?';
}
$date = $row['stamp'];
if (empty($date)) {
$date = '';
}
$type = $row['type'];
};
echo "<div id='smallpagdata' class='smallpagdata'>
ID={$v_id}<br>
NAME={$Name}<br>
TITLE={$title}<br>
INFO={$info}<br>
PHONE={$phone}<br>
LOCATION={$locate}<br>
PRICE={$price}<br>
Listed={$date}<br>
</div>";
?>
Does "NO POST" mean "no GET" as well? Otherwise you could put your retrieval script in a different file and call that with jQuery.get or XMLHttpRequest.

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

XML not parsing in jQuery

When I try to parse my PHP-generated XML file using the jQuery Feeds plugin, it doesn't do what it's supposed to - loop through the template below and output the XML <title> tag in the place of <!=title!>. Instead, it returns just one instance of the template with nothing in place of <!=title!>.
Nothing is returned in the Chrome JavaScript console.
Strangely, I have a similar PHP-generated XML file that works just fine.
Here's the jQuery I'm using:
$('.feed').feeds({
feeds: {
feed1: 'http://www.comfyshoulderrest.com/scrape.php?id=1' // this one doesn't work
},
//max: 3,
loadingTemplate: '<h1 class="feeds-loader">Loading items...</h1>',
entryTemplate: '<div class="item"><div class="image"><img src="images/tie.jpg" style="width: 100%;"></div>' +
'<div class="text"><ul class="list-inline">' +
'<li><span class="price text-warning"><strong>£7.00</strong></span> <span class="text-muted"><strike>£14.00</strike></span></li>' +
'<li class="text-muted"><strong>Topman</strong></li></ul>' +
'<!=title!>' +
'</div></div>'
});
Here's the code that generates the XML file:
<?php
function scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country) {
header("Content-Type: application/xml; charset=UTF-8");
$xml = new SimpleXMLElement('<rss/>');
$xml->addAttribute("version", "2.0");
$channel = $xml->addChild("channel");
$channel->addChild("product_url", $product_url);
$channel->addChild("shop_name", $shop_name);
$channel->addChild("photo_url", $photo_url);
$channel->addChild("was_price", $was_price);
$channel->addChild("now_price", $now_price);
$html = file_get_contents($list_url);
$doc = new DOMDocument();
libxml_use_internal_errors(TRUE);
if(!empty($html)) {
$doc->loadHTML($html);
libxml_clear_errors(); // remove errors for yucky html
$xpath = new DOMXPath($doc);
/* FIND LINK TO PRODUCT PAGE */
$products = array();
$row = $xpath->query($product_location);
/* Create an array containing products */
if ($row->length > 0)
{
foreach ($row as $location)
{
$product_urls[] = $product_url_root . $location->getAttribute('href');
}
}
$imgs = $xpath->query($photo_location);
/* Create an array containing the image links */
if ($imgs->length > 0)
{
foreach ($imgs as $img)
{
$photo_url[] = $photo_url_root . $img->getAttribute('src');
}
}
$result = array();
/* Create an associative array containing all the above values */
foreach ($product_urls as $i => $product_url)
{
$result = array(
'product_url' => $product_url,
'shop_name' => $shop_name,
'photo_url' => $photo_url[$i]
);
$item = $channel->addChild("item");
$item->addChild("product_url", $result['product_url']);
$item->addChild("shop_name", $result['shop_name']);
$item->addChild("photo_url", $result['photo_url']);
}
//print_r($result);
}
else
{
echo "this is empty";
}
echo $xml->asXML();
}
/* CONNECT TO DATABASE */
$dbhost = "xxx";
$dbname = "xxx";
$dbuser = "xxx";
$dbpass = "xxx";
$con = mysqli_connect("$dbhost", "$dbuser", "$dbpass", "$dbname");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_GET['id'];
/* GET FIELDS FROM DATABASE */
$result = mysqli_query($con, "SELECT * FROM scrape WHERE id = '$id'");
while($row = mysqli_fetch_array($result)) {
$list_url = $row['list_url'];
$shop_name = $row['shop_name'];
$photo_location = $row['photo_location'];
$photo_url_root = $row['photo_url_root'];
$product_location = $row['product_location'];
$product_url_root = $row['product_url_root'];
$was_price_location - $row['was_price_location'];
$now_price_location - $row['now_price_location'];
$gender = $row['gender'];
$country = $row['country'];
scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country);
}
mysqli_close($con);
?>

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