I've got a php file containing.
<?php
$con=mysqli_connect("localhost", "user", "password", "stock");
if (mysqli_connect_errno()){
echo "failed to connect:" mysqli_connect_error();
}
$grabCars = mysqli_query($con, "SELECT * FROM CARS");
while ($row = mysqli_fetch_array($grabCars)){
$name = $row["Name"];
$color = $row["Color"];
$link = $row["Link"];
};
echo json_encode($name);
?>
ok can anyone tell me if there is anything wrong with this code. Any ideas on how this data would be displayed.
I could also do with some help at the other end what sort of jquery could would I use to read this data and how would it look, I'm very new to web design and don't know much jquery or how the ajax command would deal with this information.
Edit:
Current Jquery script
$.ajax({
url: "test.php"'
type: "post",
data: data,
datatype: "json",
success: function(result){
console.log(result["$name"]);
},
error: function(){
alert("error");
}
});
This is the code I've got to display some of the information in console, but I get nothing back, I get a data undefined message in console. Could really do with the help. Very new to json and jquery and php and webdesign as a whole. Thanks.
First of all, there shouldn't be ; after while loop.
$sampleArray = array();
while ($row = mysqli_fetch_array($grabCars)){
$name = $row["Name"];
$color = $row["Color"];
$link = $row["Link"];
array_push($sampleArray, array('name'=> $name, 'color' => $color, 'link'=>$link));
}
echo json_encode($sampleArray);
In your JQUERY/Javascript, something like this, in AJAX success:
response( $.map( data, function( item ) {
return {
name: item.name,
color: item.color,
link: item.link
}
}));
json_encode take one value parameter if you wanna encode multiple value you need to put them in an array
There is an example with your code
<?php
$con=mysqli_connect("localhost", "user", "password", "stock");
if (mysqli_connect_errno()){
echo "failed to connect:" mysqli_connect_error();
}
$grabCars = mysqli_query($con, "SELECT * FROM CARS");
$result = array();
$i = 0;
while ($row = mysqli_fetch_array($grabCars)){
$result[$i]['name'] = $row["Name"];
$result[$i]['color'] = $row["Color"];
$result[$i]['link'] = $row["Link"];
$i++;
}
echo json_encode($result);
?>
Related
Kindly help me with the ajax / jQuery to fetch all the objects of a array.
I am using the following code and it doesn't work
$(window).on("load", GetAllProperties);
function GetAllProperties() {
$.ajax({
url: 'userdetailfetch.php', //the script to call to get data
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
$('#ph').html(data[0]);
$('#email').html(data[1]);
$('#name').html(data[2]);
$('#fname').html(data[3]);
$('#date').html(data[4]);
$('#course').html(data[5]);
$('#branch').html(data[6]);
$('#sem').html(data[7]);
$('#roll').html(data[8]);
}
});
}
fetchuserdetail.php
<?php
$cnx = mysqli_connect("localhost", "root", "", "loginerp");
$result = mysqli_query($cnx, "SELECT * FROM user_info WHERE id='" . $_SESSION['sessuser'] . "'");
$data = array();
while($row = mysqli_fetch_array($result)) {
$data[] =$row;
}
echo json_encode($data);
?>
I want to display all the details when the page loads .
Thanks for your help.
Start session in fetchuserdetail.php file
session_start();
Correct the page name
url: 'fetchuserdetail.php',
Try to adopt JSON in database because i have data not fixed.
i can query well from terminal, and need to write same query to php script.
i have spent a lot of time before ask.
example:
sqlite> select json_extract(events.interni, '$') from events WHERE id='35';
output
[{"student_id":"12","student_name":"Lisa Ochoa"},{"student_id":"21","student_name":"Rafael Royal"}]
where id = 35 will become a variable of $ _POST ['id']
what I tried:
$result2 = $db->query("select json_extract(events.interni, '$') from events WHERE id='35'");
var_dump($result2->fetchAll(PDO::FETCH_ASSOC));
return [] <- empty array
i want instead = [{"student_id":"21","student_name":"Rafael Royal"}]
where did I go wrong?
I followed this answer on SO https://stackoverflow.com/a/33433552/1273715
but i need to move the query in php for an ajax call
possibile another help.
Can the result fron $ajax call can be usable as key value or remain string?
in other hands i can convert string to object like students = new Object()?
eaxaple of what i need in js environment
- count objects in array
- and loop key value
var data = [{"student_id":"12","student_name":"Lisa Ochoa"},{"student_id":"21","student_name":"Rafael Royal"}]
consolle.log(JSON.Stringify(data));
here I would like to avoid the backslash
consolle.log(JSON.Stringify(data.lenght));
in this phase the desired data is = 2
any possible help is largely appreciated
UPDATE
leave json_extract() function i have solved the second problem, so now i can work whit object property, and finally important to count objects in array:
<?php
try {
$db = new PDO('sqlite:eventi.sqlite3');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
echo "I'm sorry, Dave. I'm afraid I can't do that.";
echo $e->getMessage();
}
$risultato = $db->query("SELECT * FROM events WHERE id = '35'", PDO::FETCH_ASSOC);
$result = array();
foreach ($risultato as $row) {
$result[] = $row;
}
// echo "Results: ", json_encode($result), "\n"; this produced backslash
echo $result[0]['interni'];
?>
js part
var num='';
$.ajax({
url: "sqlitedb/test-con.php",
type: 'POST',
dataType: 'json',
success:function(result){
console.log(result[0].student_id+ " - "+ result[0].student_name); // output here is good: 12 - Lisa Ochoa
counter(Object.keys(result).length);
}});
function counter (numero){
console.log("num2: =" + numero);
}
//out put here: 2
perfect!
odd behaviour:
console.log(result[0].student_id+ " - "+ result[0].student_name);
12 - Lisa Ochoa
outup is right but
console.log(result.lenght);
output is null
You can try something like this. and since you said in the comment about approaching it with ajax. I have included that also.
I also include php mysql backend workability for clarity. so Yo have now two options
1.) PHP WITH MYSQL
2.) PHP WITH SQLITE as you requested
index.html
<script src="jquery-3.1.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: 'get',
url: 'data.php',
dataType: 'JSON',
cache:false,
success: function(data){
var length = data.length;
for(var s=0; s<length; s++){
var student_id = data[s].student_id;
var student_name = data[s].student_name;
var res = "<div>" +
"<b>student_id:</b> " + student_id + "<br>" +
"<b>student_name:</b> " + student_name + "<br>" +
"</div><br>";
$("#Result").append(res);
}
}
});
});
</script>
<body>
<div id="Result" ></div>
</body>
In mysql database you can do it this way.
<?php
$host = "localhost";
$user = "ryour username";
$password = "your password";
$dbname = "your bd name";
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
echo "cannot connect to db";
}
$return_arr = array();
$query = "SELECT id, student_id, student_name FROM events where id='35'";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)){
$student_id = $row['student_id'];
$student_name = $row['student_name'];
$return_arr[] = array("student_id" => $student_id,
"student_name" => $student_name);
}
// Encoding array in JSON format
echo json_encode($return_arr);
?>
So with sqlitedb something like this will work for you
$return_arr = array();
$result2 = $db->query("SELECT id, student_id, student_name FROM events where id='35'");
$result2->execute(array());
//$result2 = $db->query("SELECT * FROM events where id='35'");
//$result =$result2->fetchAll(PDO::FETCH_ASSOC));
while($row = $result2->fetch()){
$student_id = $row['student_id'];
$student_name = $row['student_name'];
$return_arr[] = array("student_id" => $student_id,
"student_name" => $student_name);
}
// Encoding array in JSON format
echo json_encode($return_arr);
You are surrounding you query with double quotes but inside the query there is an unescaped $.
Try escaping it:
$result2 = $db->query("SELECT json_extract(events.interni, '\$') FROM events WHERE id='35'");
var_export($result2->fetchAll(PDO::FETCH_ASSOC));
I created a form with two selects and my idea was when the first select is changed, a query is made to the database and the second select is updated with new information.
Since is the first time I'm doing this kind of things, I tried insert some data from that query in a H3 tag instead of using a select tag, but something is not working... The H3 tag starts empty and after changing the select box, the H3 tag remains empty.
This is my code:
<script>
$(document).ready(function(){
$("#show-form-button").click(function(){
$("#show-form-button").hide();
$("#bot-form").show();
});
$("#distrito").on('change', function() {
var selected = $(this).val();
makeAjaxRequest(selected);
});
});
function insertResults(json){
alert("cenas");
$("#teste").val(json["nome"]);
}
function makeAjaxRequest(placeID){
$.ajax({
type: "POST",
data: {placeId: placeID},
dataType: "json",
url: "http://localhost/Paulo%20Cristo%20LDA/insert.php",
success: function(json) {
insertResults(json);
}
});
}
</script>
And this is my PHP script:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "paulocristo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$placeId = $_GET["placeId"];
$query = "SELECT nome from local WHERE id =".$placeId ." AND tipo=0";
$result = $conn -> query($query) or die("Query failed");
if($result -> num_rows > 0)
{
while ($row = $result -> fetch_assoc())
{
echo $row['nome'];
echo json_encode($row);
}
}
?>
Any idea what can be wrong?
I think the problem must be with AJAX because when I run this code, the right information is being displayed in the browser.
Thanks for your patience and sorry for my bad english.
1) Remove echo $row['nome']; if you echo ANYTHING along with the JSON response, the full response will not be valid JSON and the success function will not be called
2) dont echo your JSON for each row like that, that's not valid either. –
Instead do this:
$response = [];
while ( $row = $result->fetch_assoc() ){
$response[] = $row;
}
echo json_encode($response);
3) you're checking $_GET['placeId'] but your ajax is using type: "POST". Change your php to $placeId = $_POST["placeId"];
Additionally, and an error function after your success function in your AJAX like the following to better see what is going wrong:
$.ajax({
type: "POST",
data: {placeId: placeID},
dataType: "json",
url: "http://localhost/Paulo%20Cristo%20LDA/insert.php",
success: function(json) {
insertResults(json);
},
error: function(xhr, status, error){
console.log(xhr);
}
});
4) Remember also that the response will be an array of rows not a single row so you'll need to update your function like so:
function insertResults(json){
alert("cenas");
$("#teste").val(json[0]["nome"]); // grab the 'nome' property from the first row in the response
}
In your PHP do this:
while($row = $result->fetch_assoc()){
$arr[] = $row;
}
echo json_encode($arr);
mysql_close($con);
Also don't forget to do mysql_close($con) at the end. Hope this helps you!
From what I see you are using val() on h3 change your function to the following and use html(), The .val() method is primarily used to get the values of form elements such as input
function insertResults(json){
alert("cenas");
$("#teste").html(json["nome"]);
}
I want to return multiple records instead of just 1 row.
JSON now returns only 1 row and I guess I need to add a while loop but not sure the right way to code it.
.js
function getq() {
var q = $("#q").val();
$.post(
'getq.php',
{q: q},
function(data) {
console.log(data);
}, "json"
);
}
getq.php
$q = $_POST['q'];
include("connect.php");
$sql = ("SELECT xxx FROM yyy WHERE zzz = $q");
if ($results=mysqli_query($db,$sql)) {
$result = $results->fetch_assoc();
echo json_encode($result);
}
EDIT:
I created the same case as yours on my pc, I used this javascript:
$.post('getq.php', {q: q}, function(data) {
console.log(data);
}
);
And this php (getq.php) file:
<?php
// Create connection
$mysqli = new mysqli( "localhost", "user", "passw", "db");
$q = $_POST['q'];
if ($results = $mysqli->query("SELECT xxx FROM yyy WHERE zzz = $q", MYSQLI_USE_RESULT)) {
$result_set = mysqli_fetch_all($results,MYSQLI_ASSOC);
echo json_encode($result_set);
$results->close();
}
?>
source: W3Schools
I'm trying to get a column from mySQL as an array in php, then read this into javascript with jquery/ajax, and finally display the first four of the array within some HTML divs.
I think I have the php working because when I inspect I get a return that has all the elements in the array.
retrieve.php
//Create connection ("Server", "Login name", "Password", "Database name")
$connect = mysql_connect($host, $username , $password);
//Check connection
if (!$connect)
{
die ('could not connect: '. mysql_error());
}
//create connection and select database
mysql_select_db($database, $connect);
//select text column and orders them by most recent postID
$query = "SELECT text FROM $table ORDER BY postID DESC";
$result = mysql_query($query);
//create an array of recent responses
while($row = mysql_fetch_array($result)){
echo json_encode($row['text']);
}
mysql_close($connect);
scripting.js
$(document).ready(function(){ //This performs specified actions when the page fully loads
$.ajax({
type: 'POST',
url: 'retrieve.php',
data: 'data',
dataType: 'json',
success: function(result){
$("#box0").html(result[0])
$("#box1").html(result[1])
$("#box2").html(result[2])
$("#box3").html(result[3]);
}
});
Try replacing
while($row = mysql_fetch_array($result)){
echo json_encode($row['text']);
}
with
$rows = array();
while($row = mysql_fetch_array($result)){
$rows[] = $row['text'];
}
echo json_encode($rows);
to json encode an array of row texts rather than encoding them separately.