Assign multiple column values to JSON php array using mysql - php

I have to make a JSON ajax request and have an array in return.
i found this code on multiple other questions (edited to my problem):
var hej[];
function ajax_search(){
$.getJSON('test.php',function(response){
var data = response.get_response;
for (i in data){
hej.push([i,data[i]]);
}
alert(hej[0]);
}
In the php part, i have a database from which i need the data i have have 5 columns pr. row. I only have one row, and i need all five columns in the array.
$sql = "SELECT * FROM 'table'
LIMIT 1 OFFSET $i"; //random offset
$result = mysql_query($sql);
$storeArray = Array();
while($row = mysql_fetch_array($result))
{
$storeArray[0]=$row['column1'];
$storeArray[1]=$row['column2'];
$storeArray[2]=$row['column3'];
$storeArray[3]=$row['column4'];
$storeArray[4]=$row['column5'];
}
$json = json_encode($storeArray);
echo $json;
I know im doing something wrong, and i am new to programming. I need to be able to access all column values in my javascript after the call and use them in other functions, but i cant get it to return.
I would really appriciate help, with both the javascript and the php if there are errors in either.

It should be:
function ajax_search(){
$.getJSON('test2.php',function(response){
// response.column1
// response.column2
// response.column3
// for array push:
var hej = [];
$.each(response, function(key, val) {
hej.push(val);
});
alert(hej[0]); // it will alert column1
});
}
and MySQL:
$sql = "SELECT `column1`, `column2`, `column3`, `column4`, `column5` FROM `table` LIMIT 1 OFFSET $i"; //random offset
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$json = json_encode($row);
echo $json;

Try this:
Javascript Code:
var hej[];
function ajax_search(){
$.getJSON('test.php',function(response){
$.each(response.results, function(key, val) {
hej.push(val);
});
alert(hej[0]);
});
}
PHP Code:
<?php
$sql = "SELECT * FROM 'table' LIMIT 1 OFFSET $i"; //random offset
$result = mysql_query($sql);
$storeArray = array();
while($row = mysql_fetch_array($result)) {
$storeArray[0]= $row['column1'];
$storeArray[1]=$row['column2'];
$storeArray[2]=$row['column3'];
$storeArray[3]=$row['column4'];
$storeArray[4]=$row['column5'];
}
$json = json_encode( array('results' => $storeArray ) );
echo $json;
?>
Hope this helps.

Why use response.get_response?
var hej[];
function ajax_search(){
$.getJSON('test.php',function(data){
$.each(data, function (i,item) {
hej.push([i,item]);
}
alert(hej[0]);
}

Related

return tables rows in json and print

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

POST variable from SELECT into sql query to output to an INPUT

Using Chain SELECT works great from SELECT to SELECT, I'm trying to do SELECT to INPUT.
My mainpage.php
<label>Manufacturer</label>
<select>My Select statement is here</select>
<label>Model</label>
<select name="modelname">My Select statement is fed from the select above</select>
<label>Rating</label>
<input name="rating"></input>
This is the jQuery I have in the <head> section on the mainpage.php
<script>
$(document).ready(function(){
$("select#modelname").change(function(){
var id = $("select#modelname option:selected").attr('value');
$.post("assets/configs/getdata.php", {id:id}, function(data){
$("input[name='rating']").html(data);
console.log(data);
});
});
});
</script>
and finally the getdata.php
<?php
include "db.php";
$modelid = $_POST[id];
$sql = "SELECT EfficiencyRating FROM AllModels WHERE ModelID = '$modelid' ";
$res = odbc_exec($cnn, $sql);
while ($row = odbc_fetch_array($res)) {
$row_array[] = $row['EfficiencyRating'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
?>
Using the console log when this message is returned, how can I fix this?
HP Warning: array_push() expects parameter 1 to be array, null given in assets\configs\getdata.php on line 12
Try with this.
$res = odbc_exec($cnn, $sql);
$return_arr = array();
while ($row = odbc_fetch_array($res)) {
$return_arr[] = $row['EfficiencyRating'];
}
echo json_encode($return_arr);
JS Part
// Slightly modify the Request
$.post("assets/configs/getdata.php", {id:id}, function(data){
// JSON Object
console.log(data);
$("input[name='rating']").val(data);
}, 'json');
You need to declare $return_arr before the while statement. Also, I personally feel what you are doing is just not right. The proper way would be this...
$res = odbc_exec($cnn, $sql);
$return_arr = array(); //<----------- Here
while ($row = odbc_fetch_array($res)) {
array_push($return_arr,$row['EfficiencyRating']);
}
echo json_encode($return_arr);

Run php from jquery click, return array from php file which calls another file

yesterday i managed to get my data from a database outputting and storing to a java array. However that was on load, now that code wont work for on click.
So I have read about ajax and have this function:
var infArray = new Array();
var country;
$('#australia').click(function() {
//console.log("you clicked"+txt);
country = 'Australia';
$.ajax({
type: 'POST',
url: 'php/Maps.php',
data: {country: country},
success: function(data){
alert("success"+data); // this will hold your $result value
infArray = JSON.parse(data)
console.log( 'Return:' + data );
}
});
});
By my understanding this opens the php file containing the function and allows you to use the variable "country" by using $_POST.
So my php file looks like this :
<?php
require '../classes/Mysql.php';
function get_Stockist(){ // if su = 0 then stockist if = 1 then member
$mysql = new Mysql();
$result = $mysql->getInfo($_POST['country']);
echo json_encode($result);
}
so again in my eyes, $result is set to the result of the method :
in Mysql.php :
function getinfo($country){
$rows = array();
$query = "SELECT Name,add1 FROM stockistsWorld WHERE Country = '". mysql_escape_string($country) ."' LIMIT 5";
//$query = "SELECT Name,add1 FROM stockistsUK LIMIT 10";
$result = mysqli_query($this->conn, $query);
/* numeric array */
while($row = mysqli_fetch_array($result, MYSQLI_NUM)){
$rows[] = $row;
}
return $rows;
}
However the result in my html is null
You never call your function get_Stockist() in your PHP file that gets called by AJAX.
Add get_Stockist() to your PHP file to call your function.
And your other function is getinfo, without capital i.
So it would be $mysql->getinfo($_POST['country']); instead of $mysql->getInfo($_POST['country']);

Query in Jquery IF statement

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.

Get Data from Mysql instead XML?

hey i have this javascript for a bubble up... this script gets InfoID and InfoData tags from an xml file...
<script type="text/javascript">
$(document).ready( function ( ) {
// Get the XML data from your file
$.get('scores.xml', function( data ) {
// Because we've given jQuery the XML datatype, we can jump straight to finding the element.
$(data).find('Game').each( function ( ) {
// The current object now holds a single "GAME" - find the elements we need
var game_id = $(this).find('InfoID').text( );
var game_info = $(this).find('InfoData').text( );
// Create the popup.
$('.'+game_id).CreateBubblePopup({
position : 'left', align : 'center',
innerHtml: game_info,
innerHtmlStyle: { color:'#FFFFFF', 'text align':'center' },
themeName: 'all-black',
themePath: 'images/jquerybubblepopup-themes'
});
}); // end of each
}, 'xml'); // The 'xml' tells jQuery to expect XML back from the request
});
</script>
i need to make this script get data from Database table instead of xml.
i have the same InfoID and InfoData rows in a table in my database...
i use this php script to get data from db:
<?php
// Connect to database server
mysql_connect("localhost", "root", "asnaeb") or die (mysql_error ());
// Select database
mysql_select_db("scores") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM latest";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)?>
<?php echo $row['Header'].""; ?>
<?php echo $row['Row'].""; ?>
<?php echo $row['Date'].""; ?>
<?php echo $row['Time'].""; ?>
<?php echo $row['AwayTeam'].""; ?>
<?php echo $row['Score'].""; ?>
<?php echo $row['HomeTeam'].""; ?>
<?php echo $row['Other'].""; ?>
<?php echo $row['InfoID'].""; ?>
<?php echo $row['InfoData'].""; ?>
<?php } mysql_close(); ?>
any idea how i can do that? so i can remove my xml file and use database :)
Thanks in advance.
You could use an ajax post with a seperate callback function and return json data from your php script.
Give this a shot:
// try this for your javascript
<script type="text/javascript">
$(document).ready( function ( ) {
function getGameInfo() {
$.post("path/to/phpScript.php",
// this is the success callback
function (json) {
// this calls the function with the returned data
parseReturnedData(json);
});
return false;
};
// process json data to set your game_id and game_info vars
function parseReturnedData(data) {
var obj = jQuery.parseJSON(data);
var game_id = obj.InfoID;
var game_info = obj.InfoData;
}
// Create the popup.
$('.'+game_id).CreateBubblePopup({
position : 'left', align : 'center',
innerHtml: game_info,
innerHtmlStyle: { color:'#FFFFFF', 'text align':'center' },
themeName: 'all-black',
themePath: 'images/jquerybubblepopup-themes'
});
</script>
// try this for your php file
<?php
// declare vars
$response = array();
// Connect to database server
mysql_connect("localhost", "root", "asnaeb") or die (mysql_error ());
// Select database
mysql_select_db("scores") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM latest";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)?>
$response['Header'] = $Header;
$response['Row'] = $Row;
$response['Date'] = $Date;
$response['Time'] = $Time;
$response['AwayTeam'] = $AwayTeam;
$response['Score'] = $Score;
$response['HomeTeam'] = $HomeTeam;
$response['Other'] = $Other;
$response['InfoID'] = $InfoID;
$response['InfoData'] = $InfoData;
}
echo json_encode($response);
mysql_close();
?>

Categories