With below function I get data from the database:
public function cargarPaises(){
$modelo = new Conexion();
$conexion = $modelo->get_conexion();
$sql = "select idPais, nombre from paises";
$statement = $conexion->prepare($sql);
$statement->execute();
return $statement;
}
Then in this other file I call the function "cargarPaises":
<?php
require_once('../Modelo/class.conexion.php');
require_once('../Modelo/class.consultas.php');
$consultas = new Consultas();
$datos = $consultas->cargarPaises();
if (count($datos) > 0) {
while ($result = $datos->fetch(PDO::FETCH_ASSOC)) {
//printf ("%s (%s)\n", $result["idPais"], $result["nombre"]);echo"<br>";
//return $result;
//$nombre=$result['nombre'];
//$idPais=$result['idPais'];
//echo "<option value=".$idPais.">".$nombre."</option>\n";
//echo json_encode($result,JSON_HEX_QUOT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS);
echo json_encode($result);
}
}else{
return "No hay opciones en la BD";
}
?>
Now when I try to use the code in a jquery file:
$('#email').click(function(event) {
$.get('Controlador/cargarPaises.php', function(data) {
console.log(data);
});
});
I got the below in console (google chrome), All 427 records from my database (I am showing only 10):
echo json_encode($result); i got in console
{"idPais":"1","nombre":"Mexico"}
{"idPais":"3","nombre":"Albania"}
{"idPais":"4","nombre":"Alemania"}
{"idPais":"5","nombre":"Andorra"}
{"idPais":"6","nombre":"Angola"}
{"idPais":"7","nombre":"Antigua y barbuda"}
{"idPais":"8","nombre":"Antillas holandesas"}
{"idPais":"10","nombre":"Argelia"}
Now the question is how can I "play" with the variable "data" to fill a select HTML element.
First of all, you have a bug in your cargarPaises file. You're echoing a json encoding of the object for each row - you probably actually want to return an array of objects as a single json result. You're also returning a string for an error rather than an object that would let you know that. And finally, you're getting the count of a PDO statement, rather than the rowCount. Something like this would be better:
if ($datos->rowCount() > 0) {
echo json_encode($datos->fetchAll(PDO::FETCH_ASSOC));
} else {
echo json_encode(array());
}
I'd probably also modify your .get call for a start to explicitly state you're fetching json, and then add something like the following to build up the options:
$.get('Controlador/cargarPaises.php', function(data) {
$.each(data, function(idx, opt) {
$('#myselect').append('<option value="' + opt.idPais + '">' + opt.nombre + '</option>');
});
}, 'json');
public function cargarPaises(){
$modelo = new Conexion();
$conexion = $modelo->get_conexion();
$sql = "select idPais, nombre from paises where 1"; //changed
$statement = $conexion->prepare($sql);
return $statement->fetchAll(PDO::FETCH_ASSOC); //changed
}
And the second file
require_once('../Modelo/class.conexion.php');
require_once('../Modelo/class.consultas.php');
$consultas = new Consultas();
$datos = $consultas->cargarPaises();
$results = (count($datos) > 0) ? $datos : array("error"=>"No hay opciones en la BD");
echo json_encode($results);
Related
I am trying to return ajax response in json, but when I print it in log it gives null even tables has rows,
my php code is:
if(isset($_GET['proid'])){
$projid = $_GET['proid'];
include(db.php);
$res = mysqli_query($con, "SELECT * FROM data WHERE project_id LIKE '%$projid%'");
while($row = mysqli_fetch_assoc($res))
{
$dataarray[] = $row;
}
echo json_encode($dataarray);
}
ajax :
$.ajax({
url : 'getRecStudy.php',
type : 'GET',
data : {proid:study},
success : function(data) {
$('#tbody').empty();
$("#tbody").append(data);
console.log(data);
}
});
whats wrong?
I find no issue in your code except varibales. You need to debug the code in php file
if(isset($_GET['proid'])){
echo $_GET['proid'] . " is proid";
$projid = $_GET['proid'];
include(db.php);
echo "db connected";
$res = mysqli_query($con, "SELECT * FROM data WHERE project_id LIKE '%$projid%'");
echo "result fetched";
while($row = mysqli_fetch_assoc($res))
{
$dataarray[] = $row;
echo "inside while";
}
echo json_encode($dataarray);
print_r($dataarray);
exit;
}
after all this hit http://yourdomain.com/yourfile.php?proid=correctvalue
You will get the bug.
use parseJSON method in success function like this
var obj = jQuery.parseJSON( data );
alert( obj.name ); // For example name is a key
I'm trying to get a number from a mysql line then outputting it to ajax. the number can't be a string because I will multiply it in ajax. This is what i have so far. I'm not sure what to do from here.
ajax:
$(document).ready(function()
{
$("#btnCalc").click(function()
{
var user = $("#txtUser").val();
var amount = $("#txtAmount").val();
var category = $("txtCat").val();
var number = $("txtNum").val();
var result = '';
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
if ( user > 0 and user < 30 ){
alert(result);
}
else{
alert( 'invalid user ID');
}
});
});
});
php:
<?php
$userID = $_GET["ID"];
$amount = $_GET["amount"];
$category = $_GET["category"];
$num = $_GET["number"];
require "../code/connection.php";
$SQL = "select userAmount from user where userID= '$userID'";
$reply = $mysqli->query($SQL);
while($row = $reply->fetch_array() )
{
}
if($mysqli->affected_rows > 0){
$msg= "query successful";
}
else{
$msg= "error " . $mysqli->error;
}
$mysqli->close();
echo $msg;
?>
Pretty straightforward - you just grab the value from the row and cast it as a float.
while($row = $result->fetch_array() )
{
$msg = floatval($row['userAmount']);
}
if($msg > 0) {
echo $msg;
} else {
echo "error" . $mysqli->error;
}
$mysqli->close();
And one small change in your ajax call:
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
alert(query);
});
});
You need to add echo $row['userAmount']; inside or after your while loop, and drop the second echo. You should be able to take result within your AJAX code and use it as a number directly.
Here function(query), query is the response from the AJAX call. So your alert should be:
alert(query);
result is empty.
You also should be using prepared statements and outputting the value you want.
Something like:
<?php
$userID = $_GET["ID"];
$amount= $_GET["amount"];
require "../code/connect.php";
$SQL = "SELECT userAmount FROM user WHERE userID= ?";
$reply = $mysqli->prepare($SQL);
if($mysqli->execute(array($userID))) {
$row = $reply->fetch_array();
echo $row['amount'];
}
else
{
$msg = "error" . $mysqli->error;
}
$mysqli->close();
?>
Then JS:
$(document).ready(function()
{
$("#btnCalc").click(function()
{
var user = $("#txtUser").val();
var amount = $("#txtAmount").val();
var result = '';
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
alert(query);
});
});
});
You can use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/parseFloat or https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt to convert the value to an integer/float in JS.
I have a code to make a query over my db, and get back the response and put them in fields over my html. I want to send the response via JSON, then create the fields using that information. But when I echo my json_encode($json_output) I only get a [true].
If anyone can explain me why I'll be appreciated.
Javascritp code:
$($cadView).find('#cadForm').on('submit', function(e){
e.preventDefault();
var str = $('#srBar').val();
if(str == ""){
alert("Campo de busca vazio.");
}else{
$.post($('#cadForm').attr('action'), {q : str}, function(data){
alert(data);
});
}
PHP code:
<?php
$q = $_POST['q'];
require('connect.php');
$i = 0;
$sql="SELECT `_nome`, `_endereco`, `_telefone`, `_imgstring`, `_dtAcesso`, `_descricao`, `_fkIdUser` FROM `tbvisitante` WHERE _nome = ?";
$stmt= $conn->prepare($sql);
$stmt->bind_param('s', $q);
if ($stmt){
$stmt->execute();
$stmt->bind_result($rName, $rEndereco, $rTelefone, $rImgString, $rDtAcesso, $rDescricao, $rFkIdUser);
while ($row = $stmt->fetch()){
$json_output[] = $row;
echo json_encode($json_output);
}
}
mysqli_close($conn);
?>
http://php.net/manual/en/mysqli-stmt.fetch.php
mysqli_stmt::fetch returns null or a boolean. You are binding the result to variables, those are what you're supposed to use.
Otherwise you may look into get_result instead of fetch.
My PHP code should return a json object of a sql query, but it always throws the error "unexpected end of input". I noticed it doesn't fail if I don't use the variable $row. Here is a snippet of the code:
PHP:
require("pw.php");
class homework {
public $fach;
public $datum;
public $aufgabe;
public function __construct($fach, $datum, $aufgabe) {
$this->fach = $fach;
$this->datum = $datum;
$this->aufgabe = $aufgabe;
}
}
$connection = mysqli_connect($adrs, $usr, $pw, $db);
if(mysqli_connect_errno()) {
die(json_encode(mysqli_connect_error()));
}
if($_POST["feed"] == "hausaufgaben") {
$query = "SELECT fach, datum, aufgabe FROM hausaufgaben WHERE fachgruppe != '";
if($_POST["fremdsprache"] == "latein") {
$query .= "französisch";
}
else {
$query .= "latein";
}
$query .= "' AND fachgruppe != '";
if($_POST["englisch"] == "koch") {
$query .= "schopper";
}
else {
$query .= "koch";
}
$query .= "' AND datum > '" . date("Y-m-d") . "' ORDER BY datum ASC;";
$result = $connection->query($query);
$data = [];
while($row = $result->fetch_row()) {
array_push($data, new homework($row[0], $row[1], $row[2]));
}
echo json_encode($data);
$result->close();
}
$connection->close();
?>
Jquery:
$.ajax({
type: "POST",
url: "php/getFeed.php",
cache: false,
dataType: "json",
data: {feed: "hausaufgaben", fremdsprache: this.fremdsprache, englisch: this.englisch}
})
.done(function(data) {
alert(typeof(data));
document.getElementById("temp").innerHTML = data;
if(typeof(data) != "Object") {
console.log("Error: " + data);
alert("iwas?");
this.hausaufgabenError = true;
this.hausaufgaben = [];
alert(this.hausaufgaben + "\n\n" + this.hausaufgaben.length);
}
else {
this.hausaufgabenError = false;
this.hausaufgaben = data;
}
})
.fail(function(jqXHR, textStatus, error) {
console.log("error: " + error);
alert("iwas?");
this.hausaufgabenError = true;
this.hausaufgaben = [];
alert(this.hausaufgaben + "\n\n" + this.hausaufgaben.length);
});
I hope someone can help me out, because I'm completely stuck :(
Edit: In Mozilla, it thows the error SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data.
In jquery, the command $.parseJSON(''); produces the error you are experiencing. Also, parseJSON will fail similarly if it's given something other than JSON to work with. So my guess is that your php page is either displaying an error, returning no output, or returning JSON mixed with other output.
What to do is either:
fetch the php page in a browser, not via ajax, and look at the output.
or
change the datatype to text for debugging, and use console.log to look at what is actually being sent to your javascript code.
I have a jquery save script like :
naam = prompt('Give a name for your file.');
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam });
alert('Your file is save as : '+ naam);
window.location.replace("index.php?id=latest");
}
else
{
alert('Not saved');
}
I save a div in save.php which creates an new id in the database
What I want to achive is were
window.location.replace("index.php?id=latest");
id=latest must become (id=id from last saved file).
I tried
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
window.location.replace("index.php?id="+MBId);
and
var MBID =
<?php
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
echo $MBId ?>
window.location.replace("index.php?id="+MBId);
They both failed.
How can I run the query in the if(naam !=null) statement?
At first place you must fix your jQuery POST... You don't use POST respond which is wrong.. You should wait for it and then continue with other actions
naam = prompt('Give a name for your file.');
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam }, function(responde){
if(responde.id)
window.location.replace("http://yoururl.com/index.php?id="+responde.id);
else
alert("No responde...");
}, "json");
}
else
{
alert('Not saved');
}
For better results I suggest you to use JSON data in that post/respond..
At your PHP code you have to set:
<?php
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
echo json_encode(array('id'=>$MBId));
exit();
?>
P.S. For window.location.replace please set your FULL url: "http://localhost/index.php?id=" OR atleast put slash at start of it "/index.php?id="
Solution
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam });
alert('Uw moodboard is opgeslagen als '+ naam);
window.location.replace("index.php?id=<?php $q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = ($data[0] + 1); echo "$MBId";?>");
}
This Works for me , i didnt need to make a jquery var i could echo the variable in php.
And i had to add 1 cause the sql query is loaded when the page is loaded.
So the file isn't saved yet when i get the highest id.