I've got all my html working correctly but there seems to be a problem with my php code when i try to autocomplete a field
search.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link href="css/style.css" rel="stylesheet" type="text/css">
<SCRIPT LANGUAGE="JavaScript" src="js/jquery.js"></SCRIPT>
<SCRIPT LANGUAGE="JavaScript" src="js/script.js"></SCRIPT>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<div class="main">
<div class="">scriptime</span></div>
<div id="holder">
Enter Keyword : <input type="text" id="keyword" tabindex="0"><img src="images/loading.gif" id="loading">
</div>
<div id="ajax_response"></div>
</div>
</body>
</html>
here my php code
names.php
<?php
include("Connections/myphp.php");
$keyword = $_POST['data'];
$sql = "select username from ".$users." where ".$username." like '".$keyword."%' limit 0,20";
//$sql = "select username from ".$users."";
$result = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($result))
{
echo '<ul class="list">';
while($row = mysql_fetch_array($result))
{
$str = strtolower($row['username']);
$start = strpos($str,$keyword);
$end = similar_text($str,$keyword);
$last = substr($str,$end,strlen($str));
$first = substr($str,$start,$end);
$final = '<span class="bold">'.$first.'</span>'.$last;
echo '<li><a href=\'javascript:void(0);\'>'.$final.'</a></li>';
}
echo "</ul>";
}
else
echo 0;
?>
ajax code
/*
cc:scriptime.blogspot.in
edited by :midhun.pottmmal
*/
$(document).ready(function(){
$(document).click(function(){
$("#ajax_response").fadeOut('slow');
});
$("#keyword").focus();
var offset = $("#keyword").offset();
var width = $("#keyword").width()-2;
$("#ajax_response").css("left",offset.left);
$("#ajax_response").css("width",width);
$("#keyword").keyup(function(event){
//alert(event.keyCode);
var keyword = $("#keyword").val();
if(keyword.length)
{
if(event.keyCode != 40 && event.keyCode != 38 && event.keyCode != 13)
{
$("#loading").css("visibility","visible");
$.ajax({
type: "POST",
url: "names.php",
data: "data="+keyword,
success: function(msg){
if(msg != 0)
$("#ajax_response").fadeIn("slow").html(msg);
else
{
$("#ajax_response").fadeIn("slow");
$("#ajax_response").html('<div style="text-align:left;">No Matches Found</div>');
}
$("#loading").css("visibility","hidden");
}
});
}
else
{
switch (event.keyCode)
{
case 40:
{
found = 0;
$("li").each(function(){
if($(this).attr("class") == "selected")
found = 1;
});
if(found == 1)
{
var sel = $("li[class='selected']");
sel.next().addClass("selected");
sel.removeClass("selected");
}
else
$("li:first").addClass("selected");
}
break;
case 38:
{
found = 0;
$("li").each(function(){
if($(this).attr("class") == "selected")
found = 1;
});
if(found == 1)
{
var sel = $("li[class='selected']");
sel.prev().addClass("selected");
sel.removeClass("selected");
}
else
$("li:last").addClass("selected");
}
break;
case 13:
$("#ajax_response").fadeOut("slow");
$("#keyword").val($("li[class='selected'] a").text());
break;
}
}
}
else
$("#ajax_response").fadeOut("slow");
});
$("#ajax_response").mouseover(function(){
$(this).find("li a:first-child").mouseover(function () {
$(this).addClass("selected");
});
$(this).find("li a:first-child").mouseout(function () {
$(this).removeClass("selected");
});
$(this).find("li a:first-child").click(function () {
$("#keyword").val($(this).text());
$("#ajax_response").fadeOut("slow");
});
});
});
when i try to search a name it give me an error saying : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where like 'ben%' limit 0,20' at line 1
$sql = "select username from ".$users." where ".$username." like '".$keyword."%' limit 0,20";
you missed the $users and $username what their values are?
2 Things:
I don't think you need data:"data="+keyword, looking at your php data:keyword will suffice.
Second,
try changing your query to:
$sql = "select username from users where username like '".$keyword."%' limit 0,20";
since your php does not seem to have $users or $username set.
Related
I need to check from the database if email exists or not by using Ajax. I am getting a response, but coming with some HTML content. I have given below my code what I have followed.
My Ajax code:
var username_state = false;
var email_state = false;
$('#username').on('blur', function(){
var username = $('#username').val();
if (username == '') {
username_state = false;
return;
}
$.ajax({
url: 'user_list.php',
type: 'post',
data: {
'username_check' : 1,
'user_name' : username,
},
success: function(response){
$("html").html($("html", response).html());
if (response == 'taken' ) {
response.find(element).remove();
alert('hi');
username_state = false;
$('#username').parent().removeClass();
$('#username').parent().addClass("form_error");
$('#username').siblings("span").text('Sorry... Username already taken');
}
else if (response == 'not_taken') {
username_state = true;
$('#username').parent().removeClass();
$('#username').parent().addClass("form_success");
$('#username').siblings("span").text('Username available');
}
}
});
});
My php Code
$db = mysqli_connect('localhost', 'root', '', 'my_assesment');
if (isset($_POST['username_check'])) {
$username = $_POST['user_name'];
// echo $username;
$sql = "SELECT * FROM user_information
WHERE user_name='".$_POST["user_name"]."'";
//echo $sql;
$results = mysqli_query($db, $sql);
if (mysqli_num_rows($results) > 0) {
//$response = true;
echo "taken";
}else{
$response = false;
echo 'not_taken';
}
This is am getting response
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<!-- jQuery -->
not_taken
Looking at the output you are receiving my guess is that the ajax request is being sent to the same page. If that is the case then initially wrap the entire username checking code within a suitable if test and ensure that any HTML buffer content is disposed of completely before sending the response to the ajax callback.
/*
Test that the request is a POST request and that
the variables you are expecting have been sent.
As you are using data sent by the client you MUST
take precautions to mitigate SQL injection attacks.
Use a Prepared statement rather than directly embedding
user supplied data in the SQL.
*/
if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
$_POST['username_check'],
$_POST['user_name']
)){
$db = mysqli_connect('localhost', 'root', '', 'my_assesment');
$sql='SELECT `user_name` FROM `user_information` WHERE `user_name`=?';
$stmt=$db->prepare( $sql );
$stmt->bind_param('s',$_POST['user_name']);
$stmt->execute();
$stmt->store_result();
$rows=$stmt->num_rows;
$stmt->close();
$response=( $rows > 0 ) ? 'taken' : 'not_taken';
# flush buffer to remove any other HTML / text content
ob_clean();
#exit completely from this logic branch
exit( $response );
}
The test page I used to try to figure out the fault in the callback was exactly as follows. Essentially rather than respecting the checkbox to do a test and querying the db a random integer determines if the status is taken or not_taken simply to test the logic in the callback.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
$_POST['username_check'],
$_POST['user_name']
)){
/*
$db = mysqli_connect('localhost', 'root', '', 'my_assesment');
$sql='SELECT `user_name` FROM `user_information` WHERE `user_name`=?';
$stmt=$db->prepare( $sql );
$stmt->bind_param('s',$_POST['user_name']);
$stmt->execute();
$stmt->store_result();
$rows=$stmt->num_rows;
$stmt->close();
*/
$rows=mt_rand(0,1);
$response=( $rows > 0 ) ? 'taken' : 'not_taken';
ob_clean();
exit( $response );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>?Username Check Test Page</title>
<script src='//code.jquery.com/jquery-latest.js'></script>
<style>
label{display:block;padding:1rem;}
.form_success{background:rgba(0,255,0,0.25)!important;}
.form_error{background:rgba(255,0,0,0.25)!important;)}
</style>
</head>
<body>
<form name='usercheck'>
<label>Username:<input type='text' id='username' name='user_name' value='geronimo' /></label>
<label>Username Check:<input type='checkbox' name='username_check' value=1 /></label>
</form>
<script>
var username_state = false;
var email_state = false;
$('#username').on('blur', function(){
var username = $('#username').val();
if (username == '') {
username_state = false;
return;
}
$.ajax({
url: location.href, // 'user_list.php' ~ same page here!
type: 'post',
data: {
'username_check' : 1,
'user_name' : username,
},
success: function(response){
alert(response);
// no idea what this is doing
// $("html").html($("html", response).html());
if (response == 'taken' ) {
// this caused issues for me... no error as such but prevented further processing
// response.find(element).remove();
alert('hi - choose another username');
username_state = false;
$('#username').parent().removeClass();
$('#username').parent().addClass("form_error");
$('#username').siblings("span").text('Sorry... Username already taken');
}
else if (response == 'not_taken') {
username_state = true;
alert('ok - that user name is fine');
$('#username').parent().removeClass();
$('#username').parent().addClass("form_success");
$('#username').siblings("span").text('Username available');
}
}
});
});
</script>
</body>
</html>
This question already has answers here:
jquery serialize and multi select dropdown
(6 answers)
Get the values of 2 HTML input tags having the same name using PHP
(4 answers)
Closed 6 years ago.
I want to change the status in the database, with a select dropdown field.
I am sending with ajax. The first row is always working, but with multiple data i cant update the second, third..etc
I tried with serialize(), but its not working.
select from database:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".allbooks").change(function(){
var allbooks = $(this).val();
var dataString = "allbooks="+allbooks;
$.ajax({
type: "POST",
data: dataString,
url: "get-data.php",
success: function(result){
$("#show").html(result);
}
});
});
});
</script>
</head>
<body>
<?php
define("HOST","localhost");
define("USER","root");
define("PASSWORD","");
define("DATABASE","hotel");
$euConn = mysqli_connect(HOST, USER, PASSWORD, DATABASE);
$selectRooms = "SELECT * FROM proba WHERE status='inRoom'";
$resultRooms = mysqli_query($euConn,$selectRooms);
if (mysqli_num_rows($resultRooms) > 0) {
echo "<div id='reserved' align='center'>";
While ($row = mysqli_fetch_array($resultRooms)) {
echo $row[1];
echo $row[0];
?>
<select name="allbooks" id="allbooks">
<option name="years">Choose</option>
<?php
for($i=1; $i<=19; $i++)
{
echo "<option value=".$i.">".$i."</option>";
}
?>
</select><br />
<?php }
}
else
echo "<h4>nothing in the db</h4></div>";
?>
<div id="show">
</div>
</body>
</html>
and getting the results:
if(!empty($_POST["allbooks"])) {
var_dump($_POST);
$id = 2;
//echo $_POST['modelS'];
$room = $_POST['allbooks'];
$sql2 = "UPDATE proba SET room='$room' WHERE id_reservation='$id'";
$query = mysqli_query($euConn, $sql2);
var_dump($query);
}
How to change, or what would be a simple solution? Thanks for the help.
You have multiple select elements on the rendered page with the id allbooks That's wrong, IDs must be unique. You'll want to change those to a class and use $(".allbooks").change(function(){ ....
As far as sending the row id to the server with the update, you'll need to first add the row id to the select box so you can retrieve it later, something like '<select name="allbooks" class="allbooks" data-row-id="' . $row['id_reservation'] . '"> would work.
I would also recommend splitting the work up into several functions to better organize your code (classes would be even better)
It's hard to test without access to the DB, but this should do it for you. Note that I have the update function on the same page and updated the ajax url property to '' which will send the data to a new instance of the current page to handle the update.
<?php
require_once ("db_config.php");
function updateRoom($euConn, $newRoomVal, $id)
{
$stmt = $euConn->prepare("UPDATE proba SET room=? WHERE id_reservation=?");
$stmt->bind_param('ii', $newRoomVal, $id);
/* execute prepared statement */
$stmt->execute();
/* close statement and connection */
$affectedRows = mysqli_stmt_affected_rows($stmt) > 0;
$stmt->close();
return $affectedRows;
}
function getRooms($euConn)
{
$selectRooms = "SELECT * FROM proba WHERE status='inRoom'";
$resultRooms = mysqli_query($euConn,$selectRooms);
$rows = mysqli_fetch_all($resultRooms,MYSQLI_ASSOC);
return count($rows) < 1 ? '<h4>nothing in the db</h4></div>' : createSections($rows);
}
function createSections($rows)
{
$sections = [];
foreach( $rows as $row){
$options = [];
for ($i = 1; $i <= 19; $i++)
$options[] = "<option value=" . $i . ">" . $i . "</option>";
$options = implode('', $options);
$select = '<select name="allbooks" class="allbooks" data-row-id="' . $row['id_reservation'] . '"><option value="">Choose</option>' . $options . '</select><br/>';
// .. build all your other row elements here....
$section = 'some other compiled html'.$select;
$sections[]=$section;
}
return implode('', $sections);
}
$euConn = mysqli_connect(HOST, USER, PASSWORD, DATABASE);
if(isset($_POST["allbooks"]) && $_POST["allbooks"] !='') {
$updated = updateRoom($euConn,$_POST["allbooks"],$_POST["rowId"] );
echo json_encode(['success'=>$updated]);
exit;
}
$pageSections = getRooms($euConn);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".allbooks").change(function(){
var $this = $(this);
var allbooks = $this.val();
var rowId = $this.data('row-id');
var dataString = "allbooks="+allbooks+'&rowId='+rowId;
$.ajax({
type: "POST",
data: dataString,
url: "",
success: function(result){
$("#show").html(result);
}
});
});
});
</script>
</head>
<body>
<div id='reserved' align='center'>
<?php echo $pageSections ?>
<div id="show">
</div>
</body>
</html>
I am making a live search page and I think there is something wrong with the jquery part of the code. And maybe even only with the "mustache" part. Because When I check my browser's "network" page I can see it is sending to the .php page. But it does not show anything.
my code:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Search</title>
</head>
<body>
<p>Search: <input type="text" id="query"></p>
<p>
<input type="radio" name="match_type" value="0"> Begins with |
<input type="radio" name="match_type" value="1"> Ends with |
<input type="radio" name="match_type" value="2" checked> Contains
</p>
<hr/>
<ul id="results"></ul>
<script src="//code.jquery.com/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/0.8.1/mustache.min.js"></script>
<script type="mustache/x-tmpl" id="names_tmpl">
{{#names}}
<li>{{name}}</li>
{{/names}}
{{^names}}
<li><em>No matches found</em></li>
{{/names}}
</script>
<script>
$("#query").keyup(function(){
var q = $(this).val();
var match_type = $("input[type=radio]:checked").val();
var data = {query: q, match_type: match_type};
if(q.length == 0 || q == " ") {
return false;
}
$.ajax({
url: "instant-search.php",
data: data,
type: "post",
dataType: "json",
success: function(res) {
var tmpl = $("#names_tmpl").html();
var html = Mustache.to_html(tmpl, res);
$("#results").html(html);
}
});
});
$("input[type=radio]").change(function(){
$("#query").trigger("keyup");
});
$("#query").focus();
</script>
</body>
</html>
instant-search.php (but I guess there's nothing wrong with that. Didn't use PDO here but mysql just to check it out on my localhost)
<?php
class MyDb {
private $db;
public function __construct($host, $username, $password, $dbName) {
$this->db = mysql_connect($host, $username, $password);
mysql_select_db($dbName);
}
public function __destruct() {
mysql_close($this->db);
}
public function select($query) {
return $this->toArray(mysql_query($query));
}
private function toArray($res) {
$arr = array();
while($row = mysql_fetch_array($res)) {
$cols = array();
foreach($row as $key => $val) {
if (is_string($key)) {
$cols[$key] = $val;
}
}
array_push($arr, $cols);
}
return $arr;
}
}
class MatchType {
const BEGINS_WITH = 0;
const ENDS_WITH = 1;
const CONTAINS = 2
}
function processRequest($query, $matchType) {
$db = new MyDb("localhost", "root", "", "search");
$like = "'%{$query}%'";
switch ($matchType) {
case MatchType::BEGINS_WITH:
$like = "'{$query}%'";
break;
case MatchType::ENDS_WITH:
$like = "'%{$query}'";
break;
}
$selectQuery = "SELECT name FROM names WHERE name LIKE {$like} ORDER BY name ASC";
$results = $db->select($selectQuery);
header("content-type: application/json");
echo json_encode(array("names" => $results));
}
$query = $_POST["query"];
$matchType = isset($_POST["match_type"]) ? $_POST["match_type"] : MatchType::CONTAINS;
processRequest($query, $matchType);
Hello guys i am new to both ajax and JSON and i have followed this guide on making a jquery slider and getting some result from DB it is working but right now i can only get one result from the slider range but i want to get all results from that range so i need to pass more then one result variable from my php and cant seem to get it to work i have included my code below
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
<script src="slider.js"></script>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<div>
<span id="deal_min_price"></span>
<span id="deal_max_price" style="float: right"></span>
<br /><br />
<div id="slider_price"></div>
<br />
<span id="number_results"></span> Abonnementer fundet
</div>
</body>
</html>
$(document).ready(function()
{
$( "#slider_price" ).slider({
range: true,
min: 0,
max: 349,
step:1,
values: [ 0, 349 ],
slide: function( event, ui ) {
$( "#deal_min_price" ).text(ui.values[0] + "KR");
$( "#deal_max_price" ).text(ui.values[1] + "KR");
},
stop: function( event, ui ) {
var dealsTotal = getDeals(ui.values[0], ui.values[1]);
$("#number_results").text(dealsTotal);
},
});
$("#deal_min_price").text( $("#slider_price").slider("values", 0) + "KR");
$("#deal_max_price").text( $("#slider_price").slider("values", 1) + "KR");
});
function getDeals(min_price, max_price)
{
var numberOfDeals = 0;
$.ajax(
{
type: "POST",
url: 'deals.php',
dataType: 'json',
data: {'minprice': min_price, 'maxprice':max_price},
async: false,
success: function(data)
{
numberOfDeals = data;
}
});
return numberOfDeals;
}
PHP:
<?php
$result = 0;
define('MYSQL_HOST', 'db564596075.db.1and1.com');
define('MYSQL_USER', 'dbo564596075');
define('MYSQL_PASSWORD', '12345678');
define('MYSQL_DB', 'db564596075');
try
{
$dbh = new PDO('mysql:host='.MYSQL_HOST.';dbname='.MYSQL_DB, MYSQL_USER, MYSQL_PASSWORD);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_PERSISTENT, true);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
$dbh->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
}
catch (PDOException $e)
{
echo 'Fejk: ' . $e->getMessage() . '<br/>';
}
if(isset($_POST['minprice']) && isset($_POST['maxprice']))
{
$minprice = filter_var($_POST['minprice'] , FILTER_VALIDATE_INT);
$maxprice = filter_var($_POST['maxprice'] , FILTER_VALIDATE_INT);
$query = '
SELECT
*
FROM
mobilabonnement
WHERE
Prisprmdr
BETWEEN
:minprice
AND
:maxprice
';
$stmt = $dbh->prepare($query);
try
{
$stmt->bindParam(':minprice', $minprice);
$stmt->bindParam(':maxprice', $maxprice);
$stmt->execute();
}
catch (PDOException $e)
{
print($e->getMessage());
die;
}
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$result = $row['Selskab'];
}
if ($result == true)
{
echo json_encode($result);
}
else{
echo json_encode(0);
}
?>
Here is why You got only Selskab - $result = $row['Selskab'];
Try that:
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$result = $row;
if ($result)
{
echo json_encode($result);
}
else
{
echo json_encode(0);
}
You need to loop over all the results or use PDO::fetchAll, if you want all the columns you also need to use the whole row not just Selskab:
$result = array();
while (false !== ($row = $stmt->fetch(PDO::FETCH_ASSOC))) {
$result[] = $row;
}
if (count($result)
{
echo json_encode($result);
} else{
echo json_encode(0);
}
OR using PDO::fetchAll:
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (count($result)
{
echo json_encode($result);
} else{
echo json_encode(0);
}
However it also seems you really only want Selskab and id as opposed to all of the columns and in that case you should probably adjust your query as well:
SELECT id, Selskab
FROM mobilabonnement
WHERE Prisprmdr BETWEEN :minprice AND :maxprice
I'm trying to do the following:
from a html page, pushing a button will call a php script which query a db and echoes json.
Php page can be found at http://vscreazioni.altervista.org/prova.php and works fine.
What doesn't work is jquery side, because I'm getting parsererror as response.
Here's my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="initial-scale=1, maximum-scale=1" />
<style type="text/css">
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#button_1').click(function(e){
e.preventDefault();
e.stopPropagation();
favfunct();
});
});
function favfunct() {
$.ajax({
type: 'GET',
url: 'prova.php',
dataType: 'json',
success: function (json) {
alert("SUCCESS!!!");
},
error: function (xhr, status) {
alert(status);
},
});
}
</script>
</head>
<body>
<input id="button_1" type="button" value="push" />
</body>
</html>
I'm totally new at this stuff...any help would be appreciated
EDIT:
php code from prova.php
<?php
$conn = mysql_connect("localhost", “username”, “passwd”);
if (!$conn)
{
mysql_close($conn);
die("Problemi nello stabilire la connessione");
}
if (!mysql_select_db("my_vscreazioni"))
{
mysql_close($conn);
die("Errore di accesso al data base utenti");
}
$queryIcostanza = "SELECT SUM(iCostanza) FROM apps";
$resultIcostanza = mysql_query($queryIcostanza) or die(mysql_error());
$rowIcostanza = mysql_fetch_array($resultIcostanza);
$queryIversi = "SELECT SUM(iVersi) FROM apps";
$resultIversi = mysql_query($queryIversi) or die(mysql_error());
$rowIversi = mysql_fetch_array($resultIversi);
$queryI10numeri = "SELECT SUM(i10Numeri) FROM apps";
$resultI10numeri = mysql_query($queryI10numeri) or die(mysql_error());
$rowI10numeri = mysql_fetch_array($resultI10numeri);
$queryIcostanza4x = "SELECT SUM(iCostanza4x) FROM apps";
$resultIcostanza4x = mysql_query($queryIcostanza4x) or die(mysql_error());
$rowIcostanza4x = mysql_fetch_array($resultIcostanza4x);
$queryOndanews = "SELECT SUM(OndaNews) FROM apps";
$resultOndanews = mysql_query($queryOndanews) or die(mysql_error());
$rowOndanews = mysql_fetch_array($resultOndanews);
$queryFarmachimica = "SELECT SUM(FarmaChimica) FROM apps";
$resultFarmachimica = mysql_query($queryFarmachimica) or die(mysql_error());
$rowFarmachimica = mysql_fetch_array($resultFarmachimica);
$queryIcarrano = "SELECT SUM(iCarrano) FROM apps";
$resultIcarrano = mysql_query($queryIcarrano) or die(mysql_error());
$rowIcarrano = mysql_fetch_array($resultIcarrano);
$totale = 0;
$totaleIcostanza = $rowIcostanza['SUM(iCostanza)'];
$totaleIversi = $rowIversi['SUM(iVersi)'];
$totaleI10numeri = $rowI10numeri['SUM(i10Numeri)'];
$totaleIcostanza4x = $rowIcostanza4x['SUM(iCostanza4x)'];
$totaleOndanews = $rowOndanews['SUM(OndaNews)'];
$totaleFarmachimica = $rowFarmachimica['SUM(FarmaChimica)'];
$totaleIcarrano = $rowIcarrano['SUM(iCarrano)'];
$totale = $totaleIcostanza + $totaleIversi + $totaleI10numeri + $totaleIcostanza4x + $totaleOndanews + $totaleFarmachimica + $totaleIcarrano;
$comando = "select * from apps";
$result = mysql_query($comando) or die(mysql_error());
$ultima_data="";
while ( $dati = mysql_fetch_assoc($result) )
{
$ultima_data = $dati['data'];
}
$response = array();
$posts = array('icostanza'=> $totaleIcostanza, 'iversi'=> $totaleIversi, 'i10numeri'=> $totaleI10numeri, 'icostanza4x'=> $totaleIcostanza4x, 'ondanews'=>$totaleOndanews, 'farmachimica'=> $totaleFarmachimica, 'icarrano'=> $totaleIcarrano, 'totale'=>$totale, 'ultimo'=>$ultima_data);
$response['posts'] = $posts;
$json = json_encode($response);
echo $json;
mysql_close($conn);
?>
Edit 2:
I was having a misspelling issue. Now I got SUCCESS!!! as reported in
success: function (json) {
alert("SUCCESS!!!");
}
how can alert json content? I tried with
alert(json);
but i get an alert with [object Object]
In success block do like following to get posts.
success: function (json) {
alert(json.posts.icostanza);
},
this will alert "icostanza" value.