This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript data formatting/pretty printer
I am getting a bit tired of looking at unformatted json blobs in FireBug.
Does anyone know an equivalent to PHP's print_r() for jQuery?
Something that would recursively make a display string from an object or array, that I could display on the page for quick debugging?
Thanks!
console.log is what I most often use when debugging.
I was able to find this jQuery extension though.
You could use very easily reflection to list all properties, methods and values.
For Gecko based browsers you can use the .toSource() method:
var data = new Object();
data["firstname"] = "John";
data["lastname"] = "Smith";
data["age"] = 21;
alert(data.toSource()); //Will return "({firstname:"John", lastname:"Smith", age:21})"
But since you use Firebug, why not just use console.log?
How about something like:
<script src='http://code.jquery.com/jquery-latest.js'></script>
function print_r(o){
return JSON.stringify(o,null,'\t').replace(/\n/g,'<br>').replace(/\t/g,' '); }
You can also do
console.log("a = %o, b = %o", a, b);
where a and b are objects.
$.each(myobject, function(key, element) {
alert('key: ' + key + '\n' + 'value: ' + element);
});
This does the work for me. :)
I've made a jQuery plugin for the equivalent of
<pre>
<?php echo print_r($data) ?>
</pre>
You can download it at https://github.com/tomasvanrijsse/jQuery.dump
Top comment has a broken link to the console.log documentation for Firebug, so here is a link to the wiki article about Console. I started using it and am quite satisfied with it as an alternative to PHP's print_r().
Also of note is that Firebug gives you access to returned JSON objects even without you manually logging them:
In the console you can see the url of
the AJAX response.
Click the triangle to expand the response and see details.
Click the JSON tab in the details.
You will see the response data organized with expansion triangles.
This method take a couple more clicks to get at the data but doesn't require any additions in your actual javascript and doesn't shift your focus in Firebug out of the console (using console.log creates a link to the DOM section of firebug, forcing you to click back to console after).
For my money I'd rather click a couple more times when I want to inspect rather than mess around with the log, especially since keeps the console neat by not adding any additional cruft.
Look at this: http://phpjs.org/functions/index and find for print_r or use console.log() with firebug.
Related
I'm a bit out of depth on this one so I hope someone has some insight. :)
I'm attempting to update a div using AJAX. The AJAX call sends a dropdown selection's value to a PHP file, which will be performing a pgsql query to grab some data. I've read in the RGraph tutorials that this data needs to be formatted to a JSON format so that RGraph can interpret it, and then fed to the JS that runs the RGraph views.
This question might actually be 2 separate questions, but I'll ask anyway:
Is there a standard way to grab the query's results in PHP and output them into a JSON format?
Where would I want to trigger the JS that uses the JSON data? I've tried hardcoding some initial data but the graphs don't seem to show up. However, I know the jQuery is performing the AJAX calls correctly because I see the div update (with an in-between "Loading..." message and then back to blank, indicating to me a null response), so I think I'm just not scoping this properly.
P.S. No, this time I'm not making a $_POST/$_GET mistake.
Any help would be appreciated. Thanks!
EDIT 1: Got this one. It was actually way easier than I thought. Still not scoping properly, however. Any help with how RGraph grabs a JSON object and displays it as a graph, and how to use AJAX to refresh the div with a new graph?
There's some SVG based AJAX demo pages here:
There was a bunch of links to the SVG basic AJAX demos here, but now the demos are no longer online - they are in the download archive. So download it here: https://www.rgraph.net/download.html#stable
There's a JSON documentation page here:
https://www.rgraph.net/svg/docs/the-svg-ajax-functions.html
And the code example from it is this:
<script>
GLOBALS = {};
function draw()
{
RGraph.SVG.AJAX.getJSON('/ajax/getdata.html?json', function (json)
{
if (GLOBALS.bar) {
RGraph.SVG.clear(GLOBALS.bar.svg);
}
GLOBALS.bar = new RGraph.SVG.Bar({
id: 'chart-container',
data: json.data,
options: {
// Add your own options to configure the chart
}
}).draw();
});
}
draw();
</script>
If you follow this example, create a page on your website that gets the data from your database and outputs it like this page does:
https://www.rgraph.net/getdata.html?json
Note that there's no HTML output by that page - just the JSON.
Then you can fetch that page using the RGraph.SVG.AJAX.getJSON() function like the code above does - from your webpage that has the chart on it - eg foo.html
So the foo.html is what would contain that RGraph code above.
And if you wanted it to repeat then you could add a timer so that subsequent fetches update it:
setTimeout(function ()
{
draw();
}, 1000);
I think that covers everything. I've probably left something out though.
I want to call a php script (with args) from HTML and to process the returned data
I tried various flavours of :
<object id=test1 data="object.php" type="text/plain">
where object.php just returns a string, like
<?php print "firstText:Hello World";?>
I can't work out how to retrieve the returned string.
I was hoping to find it in something like
document.getElementById("test1").firstText
But no joy
Why am I doing this, you ask?
I'd like to get the page working interactively between the user and the server, avoiding the repainting of the browser window that comes with re-submitting with POST/GET.
Thanks for your responses.
I'm not happy using JQuery - another layer beyond my control
I have eventually found the returned text in
document.getElementById("test1").contentDocument.body.firstChild.textContent
which I can then work with.
Thanks
Use AJAX. Here's an example using jQuery:
$.get('yourpage.php', function(response){
// response contains the string returned by your PHP page.
});
PaulPros idea is probably your best method. Don't forget to include jQuery.
Is there any reason you could not just make the .HTML a .php file and include your script?
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Server side browser that can execute JavaScript
Execute javascript in PHP
How can I parse HTML that includes JavaScript code, preferably with PHP script if possible.
As an example:
link
should be replaced by the appropriate value the JavaScript function returns, e.g.
link
A more complex example would be a saved facebook html page which is littered with loads of javascript code.
Summarized:
Return a DOM for a page with html+javascript
You could just give this link an ID. Not that this solution is javascript, jQuery.
So give the link an Id, or class.
$('.link').each(function() {
var functionName = 'link';
var start = $(this).attr('href');
remove = start.replace('javascript:', ''),
get = remove.replace(new RegExp('^'+functionName+'\(((.+\,?)+)\)\;?', 'g'), function(a, b, c) {
return c.replace(/[()']/g,'')
}), args = get.split(",");
//read settings
var firstArgument = args[0];
$(this).attr('href', firstArgument)
});
Please note this is just an example.
Usage:
<a class="link" href="javascript:link('http://facebook.com')">Hi</a>
That would make the actual link http://facebook.com.
Adding new arguments this way is difficult though and its not really professional.
But this should do what you want, I just didn't know what your link function actually doesnt so I didnt add the argument with the boolean. Of course this could get far more complex and you could write a function that could do this too but I just wrote this for your really quick.
Check out the example.
You can't. When clicked, javascript: URIs just call the function and let it do whatever it wants (which MIGHT include navigating somewhere); they don't expect or use a return value. In many use cases, the function may not cause any navigation at all.
DomDocument can be used to parse HTML in PHP including JS: http://php.net/manual/en/class.domdocument.php
You can "render" the JS with the HTML by merely echoing out the output of a cURL or wget (or whatever you use) without escaping the HTML characters. For external JS you are going to need to build a crawler which will crawl the DomDocument script tags and fetch the appropiate URL and load it into a position that is accessible unless you use it directly from their servers but I don't think they will be too happy about that.
Edit: My new answer after some comments is: no
I thought this was going to be rather simple but I'm a bit rusty.
I call this javascript/jquery code:
$.get("plugin.php", {up_vote:surl},
function(data){
//alert(data);
document.getElementById('numvotes').innerHTML = data;
});
......
And when it returns I get the value, which is some number that is returned as a string, then right after the number a long text about redirecting is displayed. How do I get rid of that? I just want the value.
Here is what is returned:
8 (if you are not redirected after 10 seconds, please click here)
What is causing this to redirect? Or, how do I just get rid of that '(if you are ....) text?
You could try using
data = data.match(/^\d{1,}/);
$('#numvotes').html(data);
if the result is always going to be in the same format that you gave in your question.
It is actually your plugin.php sending the redirect text (and probably some other html too). Try to browse directly to plugin.php?up_vote=surl and you'll see what happens.
Furthermore, if you are using jquery anyway, why not change document.getElementById() to:
$('#numvotes').html(data);
I have a form in a PHP sending variables to a PHP file which duly inserts them into a MySQL table.
I currently have a div displaying the response from the PHP (which is anything that is printed by the PHP).
All works fine. The problem is I want to use variables that are created/updated during the PHP MySQL insert process. I.e. not only show what is printed in that PHP file, but USE those variables.
I have seen complicated use of the JSON Encoding to possibly cross this divide, but I'd love to know if that's the simplest approach. And if anyone has any good links or examples on the subject.
I assume that you want to be able to have multiple pieces of data sent back via AJAX to your page and manipulate those.
JSON is indeed the simplest way to do this. If you use PHP5, you can use json_encode() from the PHP side to send a complicated data type (such as an object or an array) back to the browser page. Then in the javascript, you use eval() on the data that is sent back (ex: var data = eval(response);) to parse it back into a usable complicated type in javascript.
There are tons of tutorials out there that will show you how to do this and explain it in further detail than a response here ever could.
Use PrototypeJS and do it like this:
Have some PHP like this
$jsonHeader = array();
if($_REQUEST['param1'])
{
echo '<p>You passed ' . $_REQUEST['param1'] . '</p>';
$jsonHeader['status'] = 'Success';
}else
{
$jsonHeader['status'] = 'Failed because the request was invalid';
}
if(is_array($jsonHeader) and sizeof($jsonHeader) > 0)
{
header('X-JSON: (' . json_encode($jsonHeader) . ')');
}
Then make your Ajax call like this
new Ajax.Request('dostuff.php', {
method: 'get',
parameters: {'param1': 'this is param 1'},
onSuccess: function(response, jsonHeader){
if(jsonHeader['status'] == 'Success'){
//Everything is OK, do stuff
}else{
alert(jsonHeader['status']);
}
},
onFailure: function(){
alert('Fail!');
}
});
Prototype grabs the X-JSON header returned by PHP and automatically sets the jsonHeader argument of the onSuccess function to a Javascript array of the values that were originally set in PHP.
The above scenario is good as long as the amount of data you're returning to Javascript fits in the HTTP header.
If you need to pass back lots of data, just have PHP output the JSON encoded result rather than making it part of the header. Then you can use the evalJSON() method of the response object in your Ajax call.
You do not have to just show what's 'printed in that PHP file', your PHP file could print JavaScript commends back to your page. You could then, upon receiving the response, execute those commands. I like to use the eval function for this, but many people here will discourage you from doing so :)
Just use the "echo" function to put put PHP variables to the standard output put.
echo $myVarName;
Or, I prefer the printf(), be sure to check for HTML in the input BEFORE you output to avoid XSS issues.
Use something like this:
printf("Your input was: %s", strip_tags(%myInputVar));
Also, remember to use the %d or %f formatters when outputting number for best security.