I have been given one php file with multiple functions that are echoed. On the client end, $.getJSON has no problem processing a JSON object if only echo is allowed and the other two are commented out. However if the others are uncommented than get JSON breaks, I'm still all of the objects echo in the response. For JSON to process, does every php function need to be in a separate file? Or can JSON parse the different arrays separately from one response string? i.e
$.getJSON(samefilename,function(array 1) {
--- process here
}
$.getJSON(samefilename,function(array 2) {
}
Sorry if this a complete newbie question. I'm a bit confused on the process of parsing the response string. I would of thought it would be $_get['array1'] and $_get['array2']being echoed from php - yet if I have more than one echo in the php file my jquery breaks and shows blank in html.
Instead of:
<?php
echo $var1;
echo $var2;
do like this:
<?php
echo json_encode(Array(
'var1' => $var1,
'var2' => $var2
));
and in jQuery:
$.getJSON('file.php',function(response) {
alert(response.var1);
alert(response.var2);
}
Related
I am a newbie in php and rest and I'm trying to understand what is going on in my API when using echo vs return....
I've tried to get down to the simplest possible scenario to isolate an issue of my rest API not returning any value, so here is goes:
I have a test.php file on my server with following content:
<?php
if(function_exists($_GET['t1'])) {
echo $_GET['t1']();
}
else if(function_exists($_GET['t2'])) {
return $_GET['t2']();
}
function test() {
return json_encode("test...");
}
?>
I then make a simple request using, as unique header 'Content-Type: application/json`
https://www.eswys.ch/tmp/test.php?t1=test
https://www.eswys.ch/tmp/test.php?t2=test
And results are, respectively
"test..."
""
I really struggle to understand this, why is my returned value somehow "lost" - is there any explanation to this?!
Returning from a function does not actually render any content to the response. You may have seen people returning data in different frameworks but the framework is actually echoing the data for you behind the scenes.
return assigns a value to a function call (like a variable) and echo is simply output to the html page or possibly a terminal window.
I am trying to use echo in php for populating data twice as per user different action using ajax.
But it seems that I am unable to use echo twice to populate data from php server to my html page.
here is the code for php:
<?php
// Receive the Data from Client
$data = $_REQUEST;
$fileName = $data['fileList'];
$files = glob( "*.txt");
//it will pass data while the html page load (and working fine)
echo json_encode($files);
//set the file path for text files
$file_Content = file_get_contents("temp.text");
//this will pass while user click a button, but while using it is not working, even the first echo also
echo json_encode($file_Content);
?>
Is there any way to do it? or any suggestion pleas..Thanks
To form and respond with a valid json object, you can only call json_encode once. You're currently responding with two encoded json objects, which is invalid, so I'm guessing only the first one is being interpreted.
Remove the first json_encode echo, and encode an array of both properties in your second (now only) echo. I've taken the liberty to guess at what might be sensical properties for your response object here:
echo json_encode(['files' => $files, 'content' => $file_Content]);
I have a Windows Desktop Gadget that, for a small number of my users, suddenly stopped working a few months back. Seemed to be that they suddenly didn't like cross-domain requests (even though all servers are on our intranet here). So, I'm rewriting the thing so that it goes to a single backend server that I have a lot of control over... and its Ajax queries to the backend are set to use data Type: jsonp. Meanwhile, the php script that the gadget queries a la Ajax calls a SOAP service, gets the data back, turns it into an array, and then uses json_encode to turn it into a string and add a reference to a callback function on the Gadget / javascript side.
My problem seems to be with json_encode. If the SOAP response includes a single data record, it sends it as an object. If the SOAP response contains multiple records, it's slapping brackets around it, like an array.
Examples:
Single record:
`{
"SmeDetail": {
"SipAddress": "jane.smith#whatever.com",
"SubjectExpert": "Smith,Jane",
"SubjectMatter": "Unix"
}
}`
Multiple records:
`{
"SmeDetail": [
{
"SipAddress": "fred.flintstone#whatever.com",
"SubjectExpert": "Flintstone,Fred",
"SubjectMatter": "Bedrock"
},
{
"SipAddress": "barney.rubble#whatever.com",
"SubjectExpert": "Rubble,Barney",
"SubjectMatter": "Bedrock"
},
{
"SipAddress": "wilma.flintstone#whatever.com",
"SubjectExpert": "Flintsone,Wilma",
"SubjectMatter": "Bedrock"
}
]
}`
In the php script, a typical SOAP call goes like this:
$Service_URL = 'http://server/PROD/OurWcfService/WcfService.svc?wsdl';
$client = new SoapClient($Service_URL);
$res= $client->GetSMEDetails($params)->GetSMEDetailsResult;
and then $res is fed to this routine:
$json_data = json_encode((array)$res);
echo $_GET['callback_name'].'('.$json_data.');';
And that echo is what's fed back as the Ajax response.
I'm not sure where I even read about using this json_encode((array)$res) to do the conversion from the Soap response into an array, then the json encoded string. But I'm wondering if I'm doing something wrong here? I guess I need to make sure that single records are pushed through as an array. And I'd rather fix that the "right way" rather than do some sort of hack on the string.
Any thoughts?
I think the problem occurs cause GetSMEDetailsResult returns not array(singlerecord) but singlerecord itself.
What about checking "is SmeDetail associative"?
hint: How to check if PHP array is associative or sequential?
function isAssoc($arr)
{
return array_keys($arr) !== range(0, count($arr) - 1);
}
if(isAssoc($res['SmeDetail'])) $res['SmeDetail'] = array($res['SmeDetail']);
This solution is ugly but it should work.
Another way is to check "is SipAddress set":
if(isset($res['SmeDetail']['SipAddress'])) $res['SmeDetail'] = array($res['SmeDetail']);
I have a function that creates an array that contains the return value from the HTML DOM method : window.document.getElementById()
function makearray1(){
var array1=[1,window.document.getElementById('divID'),['a','b'],[1,2]];
}
then I pass the array into another function
use(array1)
function use(xxx){
xxx[1].innerHTML=xxx[2][0];
}
and 'a' is written in the appropriate div
later I decided to put the array in a form and post it to a txt file on the server using php and:
JSON.stringify(array)
So now I use AJAX to call the data from the txt file after the rest of the page has loaded etc... and the original function used to make the array is not included at all.
so my php is basically this:
$a1='use(';
$data1 =file_get_contents("text_file.txt") ;
$a2=')';
echo $a1.$data1.$a2;
and the response text:
var n= XMLHttpRequestObject.responseText;
eval(n);
which pretty much means this:
use(text_file)
function use(xxx){
xxx[1].innerHTML=xxx[2][0];
}
the problem is that the array in the text file looks like this:
[1,null,['a','b'],[1,2]]
instead of:
[1,window.document.getElementById('divID'),['a','b'],[1,2]]
My question: Is there any way that I can do the equivalent of what I'm trying to do here, which is immediately replicate the return value of the HTML/DOM method in an array using AJAX/php?
To clarify: this is a simple example. I actually have a huge, multidimensional array that already has established pointers, or prefetched DOM nodes in it. Now I'm trying to replicate the array when a text version is loaded using ajax. I'm looking for a recursive approach to changing all of the null assignments with something that will immediately fetch the appropriate DOM node. Most likely I will need to do it with the response text, but was hoping I could do it with the php portion.
You're trying to stringify a reference to a javascript object in the memory of whatever computer is evaluating getElementById first, and that has no chance to represent something on the end client's computer.
Send the id instead:
function makearray1(){
array1=[1,'divID',['a','b'],[1,2]];
}
then, in the client:
function use(xxx){
window.document.getElementById(xxx[1]).innerHTML=xxx[2][0];
}
If you really want to eval it at the end, you can use this, I guess
function makearray1(){
array1=[1,"window.document.getElementById(\"divID\")",['a','b'],[1,2]];
}
I've no idea why you would want to do that though
Assuming the dom element exists in the second page, it should look something like this.
JS:
function packDomData(){
return {
"MySpecificYetBriefProperty0":1,
"DomID":"divID",
"MySpecificYetBriefProperty1":['a','b'],
"MySpecificYetBriefProperty2":[1,2]
};
}
function useDomData(domData){
document.getElementByID(domData.DomID).innerHTML=domData.MySpecificYetBriefProperty1[0];
}
PHP:
//Make sure the contents of this file is the json from packDomData. use json_encode in php or JSON.stringify in js
echo file_get_contents("text_file.txt");
var myData = JSON.parse(XMLHttpRequestObject.responseText);
useDomData(myData);
I used to code like you. Here are some tips that have helped turn my coding horror into a fun job:
Use objects with descriptive properties instead of arrays whenever you aren't actually looping through the array - I promise it will save you and others headache! "DomID" is much more flexible than 1, and if you change the order in the array, javascript gods help you that array is everywhere - including however many random text files on your server!
Also use descriptive names for functions
Always return a value from a function instead of using globals whenever possible, even where the result is then used as a nasty global. Trust me.
Never put javascript function names in an ajax call. Use JSON instead and keep the functions and other script in the javascript file where it belongs.
Mysql will save your life!!
Disclaimer - I didn't run this code but it should basically work when you get everything hooked up right.
I am using JSON to run some PHP functions and 1 of them is not working and is returning null. How can i return a php output e.g. an echo of variable/array from the php function and view in firebug/on screen? I'm sure i have done this before but cant remember how!?
Thanks
Paul
echo json_encode(array("hello" => "world"))
Will output a JSON encoded array, you can then access this script via an Ajax call, Firebug can view this and you can debug from there?
I used this to pass POST and GET arrays into json, so:
$var = <?php json_encode($_POST); ?>
So if i have $_POST['test'] = 'what'
to access it i do $var.test which is equal to 'what'