ajax load mysql data into multiple divs - php

at first I apologise for creating this topic. I did try to search the answer but I couldnt find the right solution.
I am reading data from mysql with ajax and everything is working with one div. The thing I can't get working is to load each variable into separate div.
I use this api.php for fetching the data from mysql.
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "skuska";
$tableName = "hodnoty";
//--------------------------------------------------------------------------
// 1) Connect to mysql database
//--------------------------------------------------------------------------
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
//--------------------------------------------------------------------------
// 2) Query database for data
//--------------------------------------------------------------------------
$result = mysql_query('SELECT t.hodnota FROM hodnoty t ORDER BY t.id DESC LIMIT 1') or die('Invalid query: ' . mysql_error()); //query
while ($row = mysql_fetch_assoc($result)) {
echo $row['hodnota'];
}
?>
This is the ajax script for updating the data.
$(document).ready(function() {
$("#gettable").load("api.php");
var refreshId = setInterval(function() {
$("#gettable").load('api.php?randval='+ Math.random());
}, 9000);
$.ajaxSetup({ cache: false });
});
Then in html I am using div for showing the data
<div id="gettable"></div>
I would like to use this but with more variables like data1, data2, data3
and then used div for each data so I could use more divs.
For example:
<div id="data1"></div>
<div id="data2"></div>
I understand html, a little bit of php but I am totally new in java.
Thank you for your help.

do this
take as many variables as you have div and store content in variables inside loops
/******* a short example **************/
$div1cnt="";
$div2cnt="";
while($SRC=mysqlii_fetch_object($link)){
$divid=$SRC->id;
if($divid==1){
$div1cnt.="add more stuff that you want here";
}
else if($divid==2){
$div2cnt.="add stuff to second div";
}
echo "<div id=\"div1\">{$div1cnt}</div>";
/************and so on ******************/
There is no JS requirement means it is mobile friendly and no double connection required to load second page.

Here is how you can solve the problem in Javascript ( watch out, not JAVA :) )
$(document).ready(function() {
var i = 1;
$.get("api.php", function(result) {
$("#gettable").append("<div id='data"+i+"'>"+result+"</div>");
i++;
});
var refreshId = setInterval(function() {
$.get("api.php?randval="+ Math.random(), function(result) {
$("#gettable").append("<div id='data"+i+"'>"+result+"</div>");
i++;
});
}, 9000);
$.ajaxSetup({ cache: false });
});

Related

ajax returns [object object]

i am making a quiz webapp with php and ajax where on click of radio button it triggers a function to get the new row in a database using ajax and php however it outputs object object inside the specified div element whenever the ajax success is called.
here is the ajax side of the code:
<script>
$(document).ready(function(){
$('input[type="radio"]').click(function(){
var answer = $(this).val();
var question_id = $('#dataContainer').data('value');
$.ajax({
url:"quizengine.php",
method:"POST",
data:{
answer:answer,
question_id:question_id
},
dataType: 'json',
success:function(response){
console.info(response);
$('#question').text(response);
$('#answer_one').text(response);
$('#answer_two').text(response);
$('#answer_three').text(response);
}
});
});
});
</script>
and here is the php side of the code
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "rubiqube";
$connection = new mysqli($servername, $username, $password, $dbname);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
?>
<?php
if (isset($_POST['answer'])) {
global $connection;
$answer = $_POST['answer'];
$question_id = $_POST['question_id'];
$result = mysqli_query($connection, "SELECT is_right FROM answers WHERE question_id='$question_id'");
$row = mysqli_fetch_assoc($result);
if (isset($row)) {
$correct = $row['is_right'];
if ($answer === $correct) {
$next = mysqli_query($connection, "SELECT Questions.question_id,Questions.lesson,Questions.instruction,Questions.question,Questions.image,Questions.option_type,Questions.question_value,Answers.answer_one,Answers.answer_two,Answers.answer_three,Answers.is_right FROM Questions LEFT JOIN Answers ON Questions.question_id = Answers.question_id WHERE Questions.question_id>'$question_id' ORDER BY Questions.question_id ASC LIMIT 1");
$nextrow = mysqli_fetch_assoc($next);
echo json_encode($nextrow);
exit();
}else{
echo "error";
exit();
}
}
}
?>
here is an image of what i am talking about
enter image description here
When the response comes back in the success callback, dataType: 'json' will convert it from json to an object (thus why you're seeing [object object]). You can't use the .text() method on it directly as that requires it to be a string. You may be able to do $('#question').text(response.key) depending on the data structure.
You need to simply either loop through the object and use the data, or access the properties directly (i.e. console.log(response.key)).
Here is some documentation from MDN on what to do with an object. Working with objects
Create an object of the Question on the server'side, then in your ajax response do this:
success:function(response){
$('#question').text(response.propertyName);
//propertyNamerefers to the one you made on the serverside
}

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

MySql data using JSON and AJAX in PHP

I want to get searched data from mysql database using JSON and show in my php page. I was write this code but it not retrieve any data.please help me
Client page
$(function () {
var roll = document.getElementById("roll").value;
$.ajax({
type: "POST",
url: 'api.php',
data: "roll=" + roll,
dataType: 'json',
success: function (data) {
var id = data[0];
var vname = data[1];`$` ('#output').html("id: " + id + " name: " + vname);
}
});
});
api.php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "ajax";
$tableName = "stud";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
if(isset($_POST['roll'])){
$data = $_POST['roll'];
$result = mysql_query("SELECT * FROM $tableName WHERE roll = '".$data."'");
$array = mysql_fetch_row($result);
}
echo json_encode($array);
log this value before sending,
var roll = document.getElementById("roll").value;
console.log(roll);
Use object to send the params in ajax call like this data: {'roll':roll} for best practice
use firebug to check if the value 'roll' passed properly
In your php dump the post variable print_r($_POST) and check the firebug response console whether you got what you sent.
If you got it in $_POST then probably you have some issue with sql connection/query

HTML output through JSON, activated by ajax

Background:
I have a page which dynamically pulls up a modal window, which displays extended information on a row (with multiple columns) through mySQL. I am having issues where my JSON code will not populate the information correctly so that it can be outputted. I have tried multiple nested arrays, while loops and for loops. However, I only need to return one full row of information from the database. After scratching my head, I am asking the help of all the SO experts. Any pointers are much appreciated.
Ajax Code For Div Population (Works)
var data_id = $(this).data('id');
$.ajax({
url: 'view_agency_info.php',
type: 'POST',
data: {id: data_id},
dataType: 'json',
success: function(data){
$('.view_modal_content').html(data.html); // LOAD THE DATA INTO THIS DIV
},
error: function(jqXHR, textStatus, errorThrown){
$('.view_modal_content').html(''); // LOAD THE DATA INTO THIS DIV
alert('Error Loading Information');
}
});
JSON Code To Pull Information and return HTML
<?php
$customer_id=$_SESSION['customer']['customer_id'];
$id = (int)$_POST['id'];
$query = "SELECT * FROM collections_list WHERE id={$id} && customer_id=$customer_id LIMIT 1"; //expecting one row
$result = mysql_query( $query );
//$message = mysql_fetch_assoc( $result ); //expecting just one row
$message=array();
while ($row = mysql_fetch_assoc($result)) {
$message[]=$row['agency_name'];
$message[]=$row['account_number'];
$message[]=$row['phone'];
}
$json = array();
$json['html'] = '<p><pre><code>id:'.$id.'.<br>Agency Name: '.$message[0].'<br>Account Number:'.$message[1]."<br>Phone:".$message[2].'</code></pre></p>'.'<br><br>test';
header('Content-Type: application/json');
echo json_encode( $json );
?>
Additional Question:
Is it possible to reference the headers in the array using " $message['agency_name'] "inside the html that gets returned?
After solving this problem, I will need to turn the outputted html into a structure to allow my users to view the information in a properly understandable format. I know how to do this in html, but I am unfamiliar with JSON... Is there a way to output the information without having to manually code the structure?
Thank you in advance.
$con = mysql_connect("localhost","user","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db(db_nname", $con);
$result = mysql_query("SELECT phone,agency_name FROM '''' ");
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows['results'][] = $r;
}
print json_encode($rows);
?>
and in your html
<table id ="listtable"></table>
var listdiv = $("#listtable");
$.getJSON("whatever.php",function(json){
$.each(json.results,function(i,data){
listdiv.append("<tr><th>" + data.phone + "</th><th>" + data.agency_name + "</th></tr>");
});
});
and in the append use data. and whatever your fields are
data.agency_name
data.phone
etc....

AJAX does not recognize json array

Ajax does not want to recognize my $google['cities'] when called as data.cities.
The output is: 12 undefined undefined.
It works well (output are database records) if i remove $google['number']=12, and define database array just as $google[]=$row.
Any ideas?
PHP:
<?php
$con = mysql_connect("localhost","root","");
if(!$con) {
die("Connection Error: ".mysql_error());
}
mysql_select_db("avtost", $con);
$pasteta = $_POST["white"];
$places = mysql_query("SELECT sDo FROM bstop WHERE sOd='$pasteta'");
mysql_close($con);
$google=array();
while ($row=mysql_fetch_array($places)) {
$google["cities"]=$row;
}
$google['number']=12;
if (mysql_num_rows($places)>0) {
echo json_encode($google);
} else { echo 'Ni rezultatov';}
?>
JQuery:
<script type="text/javascript">
$(document).ready(function(){
$('#submit').click(function(){
var white = $('#white').val();
$.ajax({
type:"POST",
url:"page.php",
dataType:'json',
data:{white:white},
success: function(data){
var result='';
$.each(data.cities, function(i,e) {
result += '<div>'+e.sDo+'</div>';
});
$("#res").append(data.number);
$("#res").append(result);
}
});
});
});
</script>
you are overwriting the cities key in $google every time you loop for a row in $places.
you can use:
while ($row=mysql_fetch_array($places)) {
$google[]=$row;
}
$google[]=12;
and then simply grab the last value value of the array if you want to get the number key, or just pass the number as a separate variable $number.
Some tips:
1) you should be using prepared statements to secure your code (mysqli prepared). This will give you something like:
// connect to database and check it
// ...
$stmt = $mysqli->prepare('SELECT sDo FROM bstop WHERE sOd=?');
$stmt->bind_param('s',$pasteta);
$stmt->bind_result($sDo);
$stmt->execute();
while($stmt->fetch())
$google['cities'][] = $sDo;
$google['number'] = 12;
$stmt->close();
$mysqli->close();
// ...
2) Improve your variable, table and column names. They are a bit confusing.
3) Instead of returning 'Ni rezultatov', you should return JSON. Such as, {"status":"FAILED"}, subsequently returning {"status":"OK", ... } for successful requests.
I solved it myself:
PHP:
while($row=mysql_fetch_array($places)){
$google['cities'][]=$row;
}
$google['number']=12;
echo json_encode($google);

Categories