Reading php array with jquery and appending to a div? - php

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.

Related

How do I decode json array

I am using ajax to send data to a php page that queries mysql and returns the results. I have in my page, a variable that holds the dept value. However, if I var_dump($_POST) I see that the var is an array.
If I manually enter a value in the query, then data is returned. However, just not using my $dept var.
How do I decode this array to make the variable available for my query. Thanks
ajax code
$.ajax({
url: 'deptdata.php',
type: "POST",
contentType: "application/json; charset=utf-8",
data: {dept: depts},
dataType: "json",
success: function (data) {
console.log(data);
},
error: function (data) {
alert('error');
}
});
post in firebug tab
dept=DEMOBILL
deptdata.php
<?php
$dept = $_POST['dept']; <--- array?
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","sample") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select custref from boxes where department = '".$dept."' and status = 1";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while($row = mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
//close the db connection
mysqli_close($connection);
?>
$myArray = json_decode($data, true);
echo $myArray[0]['id']; // Fetches the first ID
echo $myArray[0]['c_name']; // Fetches the first c_name
// ...
echo $myArray[2]['id']; // Fetches the third ID
// etc..
If you do NOT pass true as the second parameter to json_decode it would instead return it as an object:
echo $myArray[0]->id;

PHP parsererror ajax get returns array of strings

I am having a problem trying to get around a "parsererror" that is returned from my ajax request, despite a response in devtools which is an array of strings. I have a click event that makes an ajax request to pull in information from a database. The result in dev tools is:
1["1","admin","admin#admin.com","test","2017-01-11 00:00:00"]
I was expecting it to be a json object { }.
The code I wrote for the click event is:
$('#viewProfile').on('click', function() {
$.ajax({
type: 'GET',
url: 'api.php',
data: "",
cache: false,
dataType: 'json',
success: function(data) {
var id = data[0];
var name = data[1];
$('#userDetails').html("<p>ID: " + id + " Name: " + name + "</p>");
},
error: function(request, error) {
$('#userDetails').html("<p>There was a problem: " + error + "</p>");
}
});
});
The php I wrote for api.php
session_start();
echo $_SESSION['user_session'];
//DECLARE VARS FOR DB
$db_host = "localhost";
$db_name = "dbregistration";
$db_user = "root";
$db_pass = "";
$db_tablename = "tbl_users";
//CONNECT TO DB
include 'dbconfig.php';
$db_con = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
$dbs = mysqli_select_db($db_con, $db_name);
//QUERY DB FOR DATA
$result = mysqli_query($db_con, "SELECT * FROM $db_tablename where user_id = '".$_SESSION['user_session']."' ");
$array = mysqli_fetch_row($result);
//RETURN RESULT
echo json_encode($array);
I have tried in api.php to use json_encode($array, JSON_FORCE_OBJECT) along with changing the datatype to HTML, which obviously did not work. In short, my goal was to be able to fire the click event, send an ajax request to retrieve information from the database, based on the user id then return that to the #userDetails id on the page. I am stuck trying to get around the array of strings that seems to be the roadblock for me.
Remove this line:
echo $_SESSION['user_session'];
and change this:
$array = mysqli_fetch_row($result);
to this:
$array = mysqli_fetch_assoc($result);
EDIT: you should also be checking for success/failure of your various db-related statements:
$db_con = mysqli_connect($db_host,$db_user,$db_pass,$db_name) or die("there was a problem connecting to the db");
$dbs = mysqli_select_db($db_con, $db_name) or die("Could not select db");
and also
$result = mysqli_query($db_con, "SELECT * FROM $db_tablename where user_id = '".$_SESSION['user_session']."' ");
if (!$result) {
die("query failed");
}
This needs to be removed echo $_SESSION['user_session'] it is getting returned to ajax call and because it is on json the return is incorrect.

Ajax request not changing HTML

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"]);
}

Transfering arrays from php with json to browser

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

Mysql TEXT defined field not read

I have a MYSQL table that has a column defined as TEXT, when i reading the contents into PHP the result is that the data is not being pulled through.
my php code
SELECT establishments.name AS estName,
establishments.address AS estAddr,
establishments.telephone_num AS estTel,
establishments.description AS estDesc,
establishments.Logo AS estLogo,
establishments.title AS estTitle
FROM bucurestideals1.establishments
WHERE establishments.establishment_id ="'.$est_id.'"';
The table row has data so this is not an issue, i am reading the data using php as below:
$.ajax({
type: 'GET',
url: pass_url,
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function (data, status) {
// Assign the returned data to the page
$.each(data, function(i,item)
{
alert(item.estDesc);
});
},
Update: PHP Code
<?php
header('Content-type: application/json');
$est_id = $_GET['id'];
$server = "*";
$username = "*";
$password = "*";
$database = "";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result))
{
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
You can probably remove the quotes from your where statement. If that is not the issue, can you post the php code that you use to execute the sql?

Categories