getJSON need help passing values - php

I am trying to use getJSON to load the ids that are stored into a database, i am passing the values from PHP to JavaScript by echoing it out. I am trying to alert the value that i passed through but it didn't work
The PHP and JavaScript are on the same page. Any guidance would be appreciated
I printed the JSON file and it is in this format
Array
(
[0] => 213
[1] => 214
[2] => 215
)
PHP
$result = mysql_query("SELECT * FROM address");
$arra = array();
while ($row = mysql_fetch_array($result)){
$arra[] = $row['id'];
}
Javascript
<script>
var test= <?php echo json_encode($arra); ?>
var url = test;
$.getJSON(url, function(data) {
alert(url);
})
</script>

Make new php file called "Data.php" and make it return your JSON data.
<?php
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('test');
$result = mysql_query("SELECT * FROM address ORDER BY id DESC");
$arra = array();
while ($row = mysql_fetch_array($result)){
$arra[] = $row['id'];
}
echo json_encode($arra);
?>
Then where you call your $.getJSON, Do:
$.getJSON(data.php, function(data) {
alert(data);
})

url is json object in your case. It should be url of a page! something like this should work:
$.getJSON("<?=$_SERVER["PHP_SELF"]?>", test, function(data) {
alert(data);
})

Related

retrieve multiple data from various queries with ajax php mysql

I'm new in Ajax and JSON notation, so I'm trying to get data from differents tables of a Database, data like country names, state names, departament name, job position etc. and I've seen examples how through JSON can get data but just from a single table, can you give me a little help how can I do it with more than one table and keep it in an array.
<?php
$host = "localhost";
$user = "usuer";
$pass = "password";
$databaseName = "jsonExample";
$tableName = "variables";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$result = mysql_query("SELECT * FROM $tableName"); //query
//$array = mysql_fetch_row($result); //fetch result
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array[] = $obj;
}
}
echo json_encode($array);
?>
Html file:
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js"></script>
</head>
<body>-->
<h2> Client example </h2>
<h3>Output: </h3>
<div id="output">this element will be accessed by jquery and this text will be replaced</div>
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
$.ajax({
url: 'api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var id = data[0]; //get id
var vname = data[1]; //get name
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname); //Set output element html
//recommend reading up on jquery selectors they are awesome http://api.jquery.com/category/selectors/
}
});
});
</script>
</body>
</html>
If you want to have the results from multiple queries in one array you can add each result to a key. F.i. if you querying table table1 to tablen ...
// define the array that will contain all result sets
$array = [];
// create an array for the result set coming from table 1
$array['table1']= [];
$result = mysql_query("SELECT * FROM table1");
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array['table1'][] = $obj;
}
}
// create an array for the result set coming from table 2
$array['table2']= [];
$result = mysql_query("SELECT * FROM table2");
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array['table2'][] = $obj;
}
}
::
::
// create an array for the result set coming from table n
$array['tablen']= [];
$result = mysql_query("SELECT * FROM tablen");
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array['tablen'][] = $obj;
}
}
// return the results formatted as json
return json_encode($array);
In javascript you can access the results for table1 with data->table1.
Tip
Use mysqli instead of mysql. It is the improved version of mysql. Check the answers for this question for some background.

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

Get url parameter and query mysql data with ajax

I want to get a parameter from an url. The url looks like this:
www.example.com/?v=12345
I want to get the parameter and query my mysql database to get the right data with ajax.
So i have my ajax call here:
$.ajax({
type:"POST",
url:"ajax2.php",
dataType:"json",
success:function(response){
var id = response['id'];
var url = response['url'];
var name = response['name'];
var image = response['image'];
},
error:function(response){
alert("error occurred");
}
});
As you can see, the data which i want to get are in a json array and will be saved in javascript variables.
This is my php file:
<?php
// Connection stuff right here
$myquery = "SELECT * FROM mytable **WHERE id= **$myurlvariable**;
$result = mysql_query($myquery);
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
$array = array('id'=>$currentid,'url'=>$currenturl, 'name'=>$currentname,'image'=>$currentimage);
echo json_encode($array);
}
?>
The part where i want to query the right variable is bolded. I don't know how to query that. And Furthermore how to even get the url parameter in the proper form.
Can anybody help? Thank you!
You can get the query string using JavaScript and send it in the AJAX request.
Getting the query string(JavaScript) -
function query_string(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
//Getting the parameter-
v = query_string('v'); // Will return '12345' if url is www.example.com/?v=12345
This needs to be passed as data in the AJAX call.
$.ajax(
{
type: "POST",
dataType: "json",
url: "ajax2.php",
data: "v="+v,
success: function(response){
var id = response['id'];
var url = response['url'];
var name = response['name'];
var image = response['image'];
},
error: function(jqXHR,textStatus,errorThrown){
//alert(JSON.stringify(jqXHR));
//alert(textStatus);
//alert(errorThrown);
alert(JSON.stringify(jqXHR)+" "+textStatus+" "+errorThrown);
//alert("error occurred");
}
}
);
This can be accessed as $_POST['v'] in the php form.
if(isset($_POST['v'])){
$myurlvariable = $_POST['v'];
$myquery = "SELECT * FROM mytable WHERE id= $myurlvariable";
...
And in php form, before you echo out the json response, change the content type. Something like this-
header("Content-Type: application/json");
echo json_encode($array);
If there is a database error, then it has to be handled.
So do this -
<?php
// Connection stuff right here
header("Content-Type: application/json");
if(isset($_POST['v'])){
$myurlvariable = $_POST['v'];
$myquery = "SELECT * FROM mytable WHERE id= $myurlvariable";
$result = mysql_query($myquery) or die(json_encode(Array("error": mysql_error()));
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
$array[]= array('id'=>$currentid,'url'=>$currenturl, 'name'=>$currentname,'image'=>$currentimage);
}
echo json_encode($array);
}else{
echo json_encode(Array("error": "No POST values"));
}
?>
So this way, if the query has not executed properly, then you will know what exactly the error is.
Without any error checking, just the important part:
$myquery = "SELECT * FROM mytable WHERE id=" . $_POST['v'];

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']);

workout with the php returned array to jquery

my this php code is working for the $.ajax call which is below this code
$family = mysql_real_escape_string($_REQUEST['send_txt'], $link);
$query = "SELECT imgurl FROM images WHERE family='$family'";
//Query database
$result = mysql_query($query, $link);
//Output result, send back to ajax as var 'response'
$imgurl=array();
//$i=0;
if(mysql_num_rows($result) > 0){
//Fetch rows
while($row = mysql_fetch_array($result)){
$imgurl[]=$row['imgurl'];
}
}
echo $imgurl;
jquery code
$(document).ready(function() {
$('ul.sub_menu a').click(function() {
var txt = $(this).text();
$.ajax({
type: "POST",
url: "thegamer.php",
data:{send_txt: txt},
success: function(data){
$('#main-content').html(data);
}
});
});
});
it outputs just Array written at the #main-content div how to work with that array which are basically image paths
Why you create array from mysql result ? your code can be simpler like this:
<?php
$family = mysql_real_escape_string($_REQUEST['send_txt'], $link);
$query = "SELECT imgurl FROM images WHERE family='$family'";
//Query database
$result = mysql_query($query, $link);
//Output result, send back to ajax as var 'response'
if(mysql_num_rows($result) > 0)
{
//Fetch rows
while($row = mysql_fetch_array($result))
{
echo $row['imgurl'];
}
}
?>
Try you page from the browser directly. Using JSON can help here:
echo json_encode($imgurl);
and using getJSON instead of plain ajax:
$.getJSON('thegamer.php', {send_text:text}, function(data) { … });

Categories