AJAX returning both query result and string? - php

I'm trying to create an ajax search function, where user is to enter the search criteria, then ajax grab those data and send them to php to query the result from the database, then it returns the result along with the pagination link stored in a string.
In the javascript file:
$(document).ready(function(){
$('.song_filter').change(function(){
var url = 'listing/ctrl';
var data {
title: $('#title').val();
author: $('author').val();
}
$.post(url, data)
.success(result) {
var jsonObj = $.parseJSON( result );
output_list(jsonObj); /* fetch out the result */
}
});
});
And in my php listing/ctrl, I have both the query result and the paginated link ready to return. I have no problem returning only the query result on its own, but I don't know how to return both the result and the link.
$result = $this->pagination->get_result();
$page_nav = $this->pagination->page_nav(); // <li class="page">2</li><li class="page">3</li>
echo json_encode($result, JSON_UNESCAPED_UNICODE);

You can append the link to the json object, something like this:
$result = $this->pagination->get_result();
$page_nav = $this->pagination->page_nav();
// create an object to store the result and the link
$json = new stdClass();
$json->link = $page_nav;
$json->data = $result;
echo json_encode($json, JSON_UNESCAPED_UNICODE);
And the in your ajax success
.success(result) {
var jsonObj = $.parseJSON( result );
jsonObj[0].link /* Here comes the link */
jsonObj[0].data;
}

Related

Not being able to use Json data from php page in jquery

I'm trying to parse json data which is sent from a php page using jquery but what I get in result is : {
I don't know how to fix it,
I'm creating json data in php like below code :
$load_op_cm = $DBM -> RunQuery("SELECT * FROM at_ops_cmnts WHERE op_id='$op_id'",true,false);
$row = mysqli_fetch_assoc($load_op_cm);
$j_result = json_encode($row);
echo $j_result;
And I'm trying to parse this data using jquery which I'm using Jquery post method to send data and get response , And I'm trying to get this part of data which is useful for me : cm_1_1 : 1
not just this one but all of cm_ variables with their values.
when I show the response in html format it's like :
this is my jquery code :
$(function(){
var vop_id = localStorage.getItem('op_id');
$.post("Requests/OPS.php", //Required URL of the page on server
{ // Data Sending With Request To Server
Load_OP_CM : true,
op_id : vop_id
},
function(response){ // Required Callback Function
var result = response;
$.each(result, function (i,elem) {
$("#Response").text(elem);
});
});
Any suggestion how to get that data ?
Firstly you would need to parse your JSON string var result = JSON.parse(response);.
Then when you iterate through you would need to filter the results to only include the keys that contain 'cm_'
var filter = "cm_";
$.each(result, function (i,elem) {
if(i.indexOf(filter) !== -1) {
console.log(i, elem);
// Or whatever you need to do…
}
});

webpage content not updated through json function(data)

I am trying to update a webpage on the fly after inserting some data in the db and returning a json object to no avail.
Let's say I have
<div id="try1"> try(<span id="votes1">0</span>)</div>
When loeaded the page displays the current number of votes, (0) at the moment.
then I have a button
<button onclick="vote(1);">+</button>
that calls this function:
function vote(votes_id)
{
var div = 'try' +votes_id;
var url = 'vote.php?id=' +votes_id;
var destination = '#votes' +votes_id;
$.getJSON( url, function(data) {
$(destination).html (data.votes);
});
}
my vote.php returns this json or after correctly updating the db or, at least that is what I think
{"votes":"1"}
However my webpage doesn't get updated from 0 to 1,
I use $data = json_encode($data);
the result of which as var_dump is:
string '{"votes":"1"}'
and
{"votes":"1"}
as echo $data.
What am I possibly missing?
That's because you are putting he success callback in the wrong place.
Use:
function vote(votes_id)
{
var div = 'try' +votes_id;
var url = 'vote.php?id=' +votes_id;
var destination = '#votes' +votes_id;
$.getJSON( url, {}, function(data) {
$(destination).html (data.votes);
});
}

JSON_decode two dimensional array of objects?

I have a two dimensional array of objects like so:
function test(n){
this.id = n;
}
var testArray= new Array(2);
for(i = 0; i < testArray.length; i++){
testArray[i] = new Array(2);
for(j = 0; j < testArray[i].length; j++){
testArray[i][j] = new test((2*i)+j);
}
}
I then stringify it to post using AJAX like so:
var data = {testA: {testB: testArray[0], testC: testArray[1]}}
var text = JSON.stringify(data);
Once I perform the jquery AJAX call:
$.post("test.php",text,function(data){
alert(data);
});
I cannot work out how to decode and use this object on the PHP side, so far i've tried something like this:
<?php
$data = json_decode($_POST);
if($data == null){
echo "fail";
} else {
echo $data;
}
?>
But I get an error that says it expects a string and I'm passing it an array. I've also tried something like
$data = json_decode($_POST['testA']);
and then error doesn't appear but instead it always outputs "fail".
Does anyone know what I need to do on the PHP side so I access the data?
Why would you run stringify on it? If you just send it like this:
$.post("test.php", data, function(data) {
You should be able to retrieve it like this:
$data = $_POST['testA'];

How to end an array of json data, and echo another value?

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..

how to show the "content" from a php variable with jquery? (it shows me the "name" itself, not the content in it)

Hmm... i'm trying to use a php variable in jquery, in my edit.php : i'd like to use jquery to show the php variable, using the "rel" attribute, but it gives me the "name" of the variable, not its content.
i'm using php to retrieve the text from the xml file : (edit : one click on submit does not update the text, but 2 clicks do)
/* READ */
$dom = new DomDocument();
$dom->load('edition.xml');
$_home = $dom->getElementsByTagName('home')->item(0);
$home = $_home->firstChild->nodeValue;
$_rhizo = $dom->getElementsByTagName('rhizo')->item(0);
$rhizo = $_rhizo->firstChild->nodeValue;
$_disco = $dom->getElementsByTagName('disco')->item(0);
$disco = $_disco->firstChild->nodeValue;
/* array */
$rels = array('home' => $home,
'rhizo' =>$rhizo,
'disco' =>$disco);
echo '<script>var rels = ' . json_encode($rels) . '</script>';
/* WRITE */
if ( isset($_POST['cache']) ){
if ( isset($_POST['home']) ){
$home = stripslashes($_POST['home']);
$_home->firstChild->nodeValue = $home;
}
if ( isset($_POST['rhizo']) ){
$rhizo = stripslashes($_POST['rhizo']);
$_rhizo->firstChild->nodeValue = $rhizo;
}
if ( isset($_POST['disco']) ){
$disco = stripslashes($_POST['disco']);
$_disco->firstChild->nodeValue = $disco;
}
$dom->save('edition.xml');
}
?>
(the text is simply shown in a textarea, where i just put the php variable)
then i use jquery to show the content from the php variable : (edit with the array object : )
$('#left a').bind('click', function(){
var text_from_link = $(this).text();
var rel = $(this).attr('rel');
$('#textarea1').attr('name', rel);
$('#textarea1').text(rels[''+rel+'']);//output is "$home" for example, which will retrieve the "home" part from the xml
return false;
})
And this works if i double click on submit, if i just click once, the text is not updated... i'm a bit confused with that
Thanks for your help
You need to do an ajax call to do that.
Or you can write a javascript object in your HTML:
$rels = array('rel23' => 'Hello world');
echo '<script>var rels = ' . json_encode($rels) . '</script>';
Then access them with javascript:
alert(rels.rel23);
like mentioned you will need to use ajax for this.. jQuery provides ajax and it appears you are already using it soooo....
if(isset($_POST["getHome"])) {
$dom = new DomDocument();
$dom->load('edition.xml');
$_home = $dom->getElementsByTagName('home')->item(0);
$home = $_home->firstChild->nodeValue;
echo $home; // anything returned by this page will become 'data'
}
and
$(function(){
$('a').bind('click', function(){
$.post("mypage.php",{getHome : 1}, function(data) {
alert(data);
});
})
});
ok assuming you have an array in your php
if(isset($_POST["varName"])) { // will check if the POST variable with the name 'varName' is set
$arr = array(1,2,3); // your array
echo json_encode($arr); // encode your output as a json string
}
then in your javascript
$(function(){
$('a').bind('click', function(){
$.post("mypage.php",{varName: 1}, function(data) { // the value of 1 is trivial. and is likely not needed, you can post to a page without passing any values. In which case the use if isset() in php is not required.
var json_obj = JSON.parse(data);
console.log(json_obj); // assuming you have a console at your disposal.
});
})
});

Categories