I'm using php to return an array of data, with the command json_encode(). I want to also send some other data after I send this array. I'm using the jquery library. My php code is as follows:
<?php
//// Query
$sql = "SELECT gtn FROM $table WHERE gid < 10";
//// Open connection
$con = pg_connect("host=12.12.2.2 port=5434 dbname=spatial_data user=postgres password=****");
if (!$con){echo 'error connecting'; die; }
//// Run query
$query = pg_query($con, $sql);
$arrayData = array(); // Store results from query in arrays
//// Parse results
while($r = pg_fetch_row($query)) {
$arrayData[] = $r[0];
}
echo json_encode($arrayData);
//// Return metadata about calculation
//echo "$('#messages').html('Result returned for New York')";
//// close connection
pg_close($con);
?>
This php is responding to a jquery post command:
$.ajax({
type: "POST",
url: "/php/array_test_v3.php",
data:{vertices: pointlist},
success: function(arrayData){
//console.log(arrayData[0])
for(i=0;i<arrayData.length; i++){
setGeoJson(arrayData[i]);
}
},
dataType:'json'
});
This is a spatial database, and when I query the information, I also want to return some other values. For example, if the area is New York, I want to return an array of data and also the string New York. At the moment the line echo "$('#messages').html('Result returned for New York')"; just appends to the array of information. Is there a way that I can escape from the array, or do I need to have a separate post function to get this information.
Instead of echo json_encode($arrayData);, just fetch the meta data and then do:
echo json_encode(array(
'data' => $arrayData,
'meta' => $metaData
));
And then in JQuery:
success: function(result){
for(i=0;i<result.data.length; i++){
setGeoJson(result.data[i]);
}
// do something with result.meta
},
assuming you are using php.
make the array like this below
while($r = pg_fetch_row($query)) {
$arrayData[] = array('gtn'=>$r[0],'someotherkey'=>'someothervalue','anotherkey'=>'anothevalue');
}
echo json_encode($arrayData);
now in jquery you can do this
$.ajax({
type: "POST",
url: "/php/array_test_v3.php",
data:{vertices: pointlist},
success: function(arrayData){
$.each(arrayData,function(index,value){
setGeoJson(value.gtn);
$('#messages').html(value.someotherkey);
})
},
dataType:'json'
});
like this you can append or do any thing you like..
Related
By defaut, when my system loads some data is filtered in my db and shown to the user. But my doubt is how can I call AJAX to filter some new data, and return it, changing the default values that are already set on my variables.
This is my AJAX call:
$("#botao-filtrar").click(function(){
$(".mask-loading").fadeToggle(1000);
$.ajax({
url: 'datacenter/functions/filtraDashboardGeral.php',
type: 'POST',
data: {rede: $("#dropdown-parceria").val()},
})
.done(function(resposta){
console.log(resposta);
})
.always(function(){
$(".mask-loading").fadeToggle(1000);
})
});
And this is what I got from trying to filter some data to return it,
but nothing worked:
<?php
require_once('../../includes/conecta.php');
$rede = $_POST['rede'];
function buscaDados($conexao){
$dados = array();
$resultado = mysqli_query($conexao, "SELECT * FROM evolucao_originacao WHERE rede = {$rede}");
while($valores = mysqli_fetch_assoc($resultado)){
array_push($dados, $valores);
}
}
Any idea?
Thanks!
You should add echo at the end :
echo json_encode($dados);
So the $dados array will be sent back to the ajax request as JSON response.
Parse the response to json uisng $.parseJSON() :
.done(function(resposta){
resposta = $.parseJSON(resposta);
console.log(resposta);
})
Hope this helps.
in your ajax code u add a success.
$("#botao-filtrar").click(function(){
$(".mask-loading").fadeToggle(1000);
$.ajax({
url: 'datacenter/functions/filtraDashboardGeral.php',
type: 'POST',
dataType: 'json',
data: {rede: $("#dropdown-parceria").val()},
success: function (data) {
//You do not need to use $.parseJSON(data). You can immediately process data as array.
console.log(data)
//if you have a array you use the following loop
for (var j =0;j < data.length;j++) {
console.log(data[j]);
// u can use data[j] and write to any fields u want.
// e.g.
$('.somediv').html(data[j].myarraykey);
}
})
.done(function(resposta){
console.log(resposta);
})
.always(function(){
$(".mask-loading").fadeToggle(1000);
})
});
And for the php codes (i did not check whether your code is valid or not), you need to add the echo and a die to end the call.
$rede = $_POST['rede'];
$dados = array();
$resultado = mysqli_query($conexao, "SELECT * FROM evolucao_originacao WHERE rede = {$rede}");
while($valores = mysqli_fetch_assoc($resultado)){
array_push($dados, $valores);
}
echo json_encode($dados);
die();
When call php from jquery via ajax ,have any response .I changed the dataTypeand put jsoninstead html.I´m thinking the issue is that,for the ajax call never trigger the php code,it seems $_POST['retriveForm'] never carries a value.
PHP:
if(isset($_POST["retriveForm"])) {
$data_json =array();
$id = $_POST['retriveForm'];
$sql = "SELECT * FROM mytable WHERE Id = $id";
while ($row = mysqli_fetch_array($db->consulta($sql)) {
$data_json = array('item1' => $row['item1'],'item2' => $row['item2']) ;
}
$data_json['item_array'] = call_a_function_return_array();//this works
echo json_encode($data_json);
}
and jQuery :
$(document.body).on('click', '.edit', function() {
var id = $(this).data('id');
$.ajax({
type: "POST",
url: "is_the_same_page.php",
data: {
retriveForm: id
},
dataType: "json",
success: function(response) {
$('#myForm').find('input').eq(1).val(response.item1);
}
});
});
Code is all in the same page if that may be important.
Since the AJAX code is in the same script, make sure you don't output any of the normal HTML in this case. Your PHP code should be at the very beginning of the script, before any HTML is output. And you should exit the script after echoing the JSON. Otherwise your JSON will be mixed together with HTML, and jQuery won't be able to parse the response.
Also, you're not correctly adding to $data_json in your loop. You're overwriting the variable each time instead of pushing onto it.
<?php
// code here to set up database connection
if(isset($_POST["retriveForm"])) {
$data_json =array();
$id = $_POST['retriveForm'];
$sql = "SELECT * FROM mytable WHERE Id = $id";
while ($row = mysqli_fetch_array($db->consulta($sql)) {
$data_json[] = array('item1' => $row['item1'],'item2' => $row['item2']) ;
}
$data_json['item_array'] = call_a_function_return_array();//this works
echo json_encode($data_json);
exit();
}
?>
<html>
<head>
...
Then in the success function, you'll need to index the elements of response, since it's an array, not a single object.
I am a beginner in Ajax. I want to fetch data row from Subject Table consist of only one column Subject as varchar(100), defined in MySQL DB. Following is my php code.
Data.php
<?php
$con=mysqli_connect("","root","root","DBTemp") or die("</br> Error: " .mysqli_connect_error());
$sql="select * from Subject";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result))
{
echo $row["SUBJECT"];
//I Want This Value to Be received in my Jquery Page
//So that i can take certain action based on each Subject.
//For example creating a select box child elements,options.
}
?>
Jquery.js
$(document).ready(function()
{
var response='';
$("body").ready(function()
{
$.ajax(
{
url: '/Data.php',
type: 'GET'
success: function(text)
{
response=text;
}
});
});
$("body").append("<select> /*Get values here as options*/ </select>");
});
But The Desired action is getting values row by row like:-
1st row value comes-> take certain action in jquery;
2nd row value comes-> take sertain action..;
.
.
so on.
Data.php
<?php
$con=#mysqli_connect("","root","root","DBTemp");
# Instead of that use header 500 to let javascript side know there is a real error.
if (mysqli_connect_errno())
{
echo "Could not connect to database : ". mysqli_connect_error();
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
exit();
}
$sql="select * from Subject";
$result = mysqli_query($con,$sql);
if (mysqli_error($con))
{
echo "Query failed : ".mysqli_error($con);
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
exit();
}
$options = array();
# populate options arrey with using table's id field as key
# and subject field as value.
while($row = mysqli_fetch_assoc($result))
{
$options[$row['id']] = $row['subject'];
}
# return json encoded array to parse from javascript.
echo json_encode($options);
Data.php will output :
{"1":"Subject ID 1","2":"Subject ID 3"}
Jquery.js
$(document).ready(function()
{
$("body").ready(function()
{
$.ajax(
{
url: '/Data.php',
type: 'GET',
dataType: 'json', // Let jQuery know returned data is json.
success: function(result)
{
$.each(result, function(id, subject) {
# Loop through results and add an option to select box.
$("#ajaxpopulate").append( new Option(subject,id) )
});
}
});
});
});
Page.html , inside the body. This select box will populated from ajax request.
<select id="ajaxpopulate"></select>
I would have the php function return a json response. You could do this in two ways either construct the JSON manually through your while statement server side or use the json_encode PHP function and echo that server side. That way when the data is returned client side in your ajax response you can parse the JSON data to a JSON object JSON.parse(json); and then control row by row the data in a structured way.
Hope this helps!
1) You need to use data structure like an array and pass it as a json response to your ajax call.
2) You need to iterate through your json array and that is where you can process each row separately and create nested select options.
UPDATE
$con=mysqli_connect("","root","root","DBTemp") or die("</br> Error: "
.mysqli_connect_error());
$sql="select * from Subject";
$result = mysqli_query($con,$sql);
$jsonResult = [];
while($row = mysqli_fetch_assoc($result))
{
$jsonResult[] = $row["SUBJECT"];
}
echo json_encode($jsonResult);
An jquery should look like this
$(document).ready(function()
{
var response='';
$("body").ready(function()
{
$.ajax(
{
url: '/Data.php',
type: 'GET'
dataType : 'JSON',
success: function(data)
{
//Alert should return an array of your subjects
//If it does then you need to iterate through this array and create options manually.
alert(data);
}
});
});
$("body").append("<select> /*Get values here as options*/ </select>");
});
I'm creating my project using OOP. I need to pass all the values inserted in the database in the form of array. And it's a multidimensional array. SO when I pass now via ajax as a 'text' datatype it displays array in console.log(). But I'm unsure if this is the correct way and how to display the value in a table form in jquery.
Below are the functions where the values returned to the object in another page.
public function selectType()
{
$sql="SELECT * FROM car_type";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
$carType=array();
while($row = $stmt->fetch())
{
array_push($carType,$row['car_type']);
}
return $carType;
}
public function selectMaker()
{
$sql="SELECT * FROM car_maker";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
$carMaker=array();
while($row = $stmt->fetch())
{
array_push($carMaker,$row['car_maker']);
}
return $carMaker;
}
ANd this is how I'm fetching the values to be passed to another page to be displayed to the user.
$setting = new setting($car_type,$car_maker,$rental_type,$rental);
//$setting->connection;
$setting->addCarType();
$setting->addCarMaker();
$setting->addRentalBy();
$carType=$setting->selectType();
$carMaker=$setting->selectMaker();
$json=array();
array_push($json,array("type"=>$carType,"maker"=>$carMaker));
echo $json;
Finally ajax to fetch and display data
$("#submit").on("click",function()
{
$("#set_setting").submit(function(){
data = $(this).serialize()
$.ajax({
type: "POST",
dataType: "html",
url: "submit_setting.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
//hide the form
$("#set_setting").slideUp("slow");
//show the result
for (i = 0; i < data.length; i++) {
console.log(data);//outputs array
$(".the-return").html(data);
}
}
});
return false;
});
});
You need to pass array as JSON and post it using name value pairs.
var data = {a:{'foo':'bar'},b:{'this':'that'}};
$.ajax({ url : '/',
type : 'POST',
data : {'data':JSON.stringify(data)},
success : function(){ }
});
And in backend (PHP):
$data = json_decode($_POST['data']);
print_r($data);
// Result:
// Array( "a" => Array("foo"=> "bar"), "b" => Array("that" => "this"))
Am I on the wrong path here?
I have a ajax call to upload some files.
I then create a array on the PHP side and send it back as JSON. But im not sure if the JSON format is correct.
Problem is I want to populate a dataTable with the returned JSON data, but I having difficulty reading the data. If its a single file then its fine and it works, but as soon as its more than one file
PHP CODE
$stmt = $db->prepare("SELECT * FROM {$table} WHERE uuid = :id");
$stmt->execute(array(":id" => $id));
$row = $stmt->fetch();
$json = array();
$json[] = $row;
echo json_encode($json);
on the JQuery/AJAX call side
$(document).ready(function() {
$('#myfiles').on("change", function() {
var myfiles = document.getElementById("myfiles");
var files = myfiles.files;
var data = new FormData();
for (i = 0; i < files.length; i++) {
data.append('file' + i, files[i]);
}
$.ajax({
url: './inc/MediaScripts.php',
type: 'POST',
contentType: false,
data: data,
processData: false,
cache: false
}).done(function(html) {
var t = $('#vidlib_dtable').DataTable();
var obj = eval(html);
$.each(obj, function(key,value) {
t.row.add( [
value.name,
value.title,
value.path,
value.duration,
value.uploaded_date,
value.uploaded_by,
value.keyword,
value.comment,
] ).draw();
});
});
});
});
The original return has more columns, hence the above columns in the dataTable add.
The return looks like multiple (singular) JSON arrays.
[{"uuid":"236","name":"Koala.jpg"}]
[{"uuid":"237","name":"Lighthouse.jpg"}]
I was wondering if it should not take the shape of something like this
[{"uuid":"236","name":"Koala.jpg"}, {"uuid":"237","name":"Lighthouse.jpg"}]
If the format that I receive the data in is fine, how do I go about looping trhough the multiple arrays on the JQuery side?
That's because you are echo'ing 3 different JSON object arrays.
Each time your loop iterates you echo, the loop then re-creates the array and echo's the new JSON array.
$json = array();
//forloop{ START
$stmt = $db->prepare("SELECT * FROM {$table} WHERE uuid = :id");
$stmt->execute(array(":id" => $id));
$row = $stmt->fetch();
array_push($json, $row);
//} END
echo json_encode($json);
Initialize your array before the loop, and echo it after it's been fully created.