I am trying to generate generate Alternate JSON code for jstree in my PHP controller.
I am creating what looks like the correct data, however, jstree does not display it.
My javascript looks like this:
$this->registerJs("
$(function() {
$('#statustree').jstree({
'core' :
{
'data' :
{
'datatype' : 'json',
'url' : '/myaccount/buildstatustree',
}
}
});
$('#statustree').on('loaded.jstree', function()
{
$('#statustree').jstree('open_all');
});
})
", \yii\web\VIEW::POS_READY);
and my php looks like this:
// convert to JSON format for jstree
$tree = array();
$parent = new stdClass();
$parent->id = 'P1';
$parent->parent = '#';
$parent->text = $username;
$tree[] = $parent;
$student1 = new stdClass();
$student1->id = 'S1';
$student1->parent = 'P1';
$student1->text = 'Poly';
$tree[] = $student1;
$student1 = new stdClass();
$student1->id = 'S2';
$student1->parent = 'P1';
$student1->text = 'Bob';
$tree[] = $student1;
// convert to json and send
header('Content-type: application/json');
return json_encode( $tree );
My controller is getting called and is returning a string that looks like this:
[
{"id":"P1","parent":"#","text":"user2"},
{"id":"S1","parent":"P1","text":"Poly"},
{"id":"S2","parent":"P1","text":"Bob"}
]
The spinner spins while the call is made, but the spinner disappears, and my tree is not displayed...
I suspect that I am not forming my Alternate JSON response correctly, but nothing I try works....
Thanks
-John
The data you are generating looks fine (provided that is what you see in your dev tools as the response to the AJAX call that jsTree makes).
You might want to check if all the headers are OK - is it really served as JSON? You can also try adding the charset just in case:
header('Content-Type: application/json; charset=UTF-8');
I see you are already trying to force jQuery to treat the response as JSON regardless of headers, but use "dataType" instead of "datatype".
If this does not work - please share what you see in the net panel of your developer console - the headers and the response to the AJAX call jsTree makes.
Related
I tried to ask this question yesterday but my question was of bad quality.
I have a wordpress Site that I have integrated with react. I am sending a post request from a react form to the wp api.
The request from react Looks Like this.
axios.post('/wp-admin/admin-ajax.php', new URLSearchParams({
action: 'report',
report: JSON.stringify(props.data),
nonce : document.getElementById("my-react-app").getAttribute("data_id")
}), config)
.then(response => console.log(response))
.catch((err) => {
let message = typeof err.response !== "undefined" ? err.response.data.message : err.message;
console.log("error", message);
});
}
I am Able to receive the request on the server but I cannot target the json string of data in php.
$data
{"success":true,"data":{"action":"report","report":"{\\\"firstName\\\":\\\"rrt\\\",\\\"lastName\\\":\\\"trtr\\\",\\\"phone\\\":\\\"rt\\\",\\\"email\\\":\\\"rtrt\\\",\\\"placedata\\\":{\\\"Street\\\":\\\"tr\\\",\\\"City\\\":\\\"tr\\\",\\\"State\\\":\\\"tr\\\",\\\"zip\\\":\\\"tr\\\"},\\\"dateData\\\":{\\\"Start\\\":\\\"00:21\\\",\\\"End\\\":\\\"00:12\\\",\\\"Date\\\":\\\"2022-08-31\\\"},\\\"foodData\\\":{\\\"Food\\\":\\\"df\\\"},\\\"peopleData\\\":{\\\"People\\\":\\\"32\\\"}}","nonce":"f2331f42d4"}}
I have Tried ($data is an Array)
function report() {
global $wpdb;
$data = $_POST;
$test_One = json_decode($data['report']->firstName; //Response Nothing. Not even Null
$Test_two = json_decode($data['report']); //Response (The Json String)--- {\\\"firstName\\\":\\\"rrt\\\",\\\"lastName\\\":\\\"trtr\\\",\\\"phone\\\":\\\"rt\\\",\\\"email\\\":\\\"rtrt\\\",\\\"placedata\\\":{\\\"Street\\\":\\\"tr\\\",\\\"City\\\":\\\"tr\\\",\\\"State\\\":\\\"tr\\\",\\\"zip\\\":\\\"tr\\\"},\\\"dateData\\\":{\\\"Start\\\":\\\"00:21\\\",\\\"End\\\":\\\"00:12\\\",\\\"Date\\\":\\\"2022-08-31\\\"},\\\"foodData\\\":{\\\"Food\\\":\\\"df\\\"},\\\"peopleData\\\":{\\\"People\\\":\\\"32\\\"}
//The above examples have all been placed in print_r
echo "<xmp>";
(Test 3) print_r(json_decode($data['report'])['lastName']); // Response --- {
echo "</xmp>";
}
I am new to PHP and have looked at many Answers On Here. Have yet to find a similar Issue. That tells me it's probably not much of an issue, yet I cant seem to figure it out. Any Help Would be Appreciated. Thank you!
try this solution
function report() {
global $wpdb;
$data = $_POST;
$test_One = json_decode($data);
$test_One = $test_One->data->report->first_name;
echo $test_One;
}
Trying to be able to have my website so that I can update a JSON file when I edit a cell using BackgridJS (backgridjs.com). In order to save the file to the server, this is the code I am using:
var MyModel = Backbone.Model.extend({
initialize: function () {
Backbone.Model.prototype.initialize.apply(this, arguments);
this.on("change", function (model, options) {
if (options && options.save === false) return;
model.save();
});
}
});
I want it to apply the change to the JSON file, but I figured it would be easier to use PHP. I read about how to do this on this StackOverflow Question but since I am just beginning to learn PHP, I'm very confused. I keep trying to implement that code into my file, but nothing happens when I save the cell. I'm using MAMP as a localhost.
Any and all help is appreciated.
Thanks to the help of #Ingro, this is the solution. In the HTML with Backbone embedded:
var data1 = JSON.stringify(this);
obj = JSON.parse(data1);
$.ajax({url:"update.php",type:"POST",data:{
"data3":obj
}});
and in the PHP file:
<?php $jsonString = file_get_contents('examples/olympics.json');
$data = json_decode($jsonString,true);
$data3 = $_REQUEST ["data3"];
$data = $data3;
$newJsonString = json_encode($data);
file_put_contents('examples/olympics.json', $newJsonString);
?>
Does anyone have experience with ajax in drupal 7?
I'm a little stuck.
So, with my module, I output a link and map the path to a callback function with hook_menu()
In the callback function I used ajax_command_replace() and ajax_deliver() to update content.
Well, so far, so good. It all works. But turns out, for complicated reasons, that using links won't work.
So instead I decided to try the jQuery ajax way. So I attach a click event to a div so when it gets clicked something like this runs in a JavaScript file that I load:
jQuery.ajax({
type: 'POST',
url: 'http://path/etc',
});
Then, in my module, I use hook menu to map the path to a callback function that looks like this:
function the_callback($var) {
// a lot of code that gets the right nid to load. This all works...
// and eventually I end up here:
$node = node_load($nid, NULL, false);
if ($node) {
$node_view = node_view($node);
$output = theme("node",$node_view);
$commands = array();
$commands = ajax_command_replace('#content','<div id = "content">' . $output . '</div>';
$page = array('#type' => 'ajax', '#commands' => $commands);
ajax_deliver($page);
}
This is the exact same code that was sucessfully replacing content when I had the links. But for some reason this doesn't work when I try to invoke the ajax call with jQuery. The callback function gets called, the correct stuff gets loaded in $output, but the page isn't updating.
Does anyone know what is going on here?
Are you missing a closing parenthesis?
$c = ajax_command_replace('#content','<div id = "content">' .$output. '</div>';
Should be:
$c = ajax_command_replace('#content','<div id = "content">' .$output. '</div>');
probably there is some javascript code inside the $output returned by theme('node', $node_view) , which you need to strip(remove).
here's some code from my ajax function returning the node rendered content:
$n = node_load($nid, NULL, FALSE);
$output = drupal_render(node_view($n));
$output = preg_replace('~<script\s+type="text/javascript">.+</script>~is', '', $output);
I'm working on a jQuery .get that will send a value to the server to compare against an array which will then get encoded into a json format as the responses. Below is the code (jQuery and PHP zend). I'm not sure if my problem is with identifying the keys and values or if it is the syntax. Is there away to view the raw json data echoed by my php controller?
$.get(
"/ed/macro",
{value: singleValues},
function(data) {
$.each(data, function(key,value1){
$.each(data.value1[0], function(key,value2){
$('#stage').html("data");;
});
});
},"json");
$select = $this->getDbTable()->select();
$select->from('sub');
$resultSet = $this->getDbTable()->fetchall($select);
$data = array();
foreach ($resultSet as $row) {
$entry = new Application_Model_Subdiscipline();
$entry->setIdSub($row->idsubdiscipline)
->setSub($row->subdiscipline)
->setDescription($row->description);
$data[] = $entry;
}
return $data;
}
public function macAction()
{
$request = $this->getRequest()->getParam('value');
// acti
$sub = new Application_Model_Sub();
$fetch = $sub->fetchAll($request);
$jsonObject = Zend_Json::encode($fetch);
echo $jsonObject;
// action body
}
To view the object print_rin PHP and console.log in Javascript. Or as Sam said, after the JS has called it, look in Net to see what was sent.
Assuming that you are echoing a json string after telling your server to tell the browser it is json with header("Content-type: application/json"); your problem is probably here
$.each(data, function(key,value1){
$.each(data.value1[0], function(key,value2){
data.value1 isn't what you're dealing with there, it's value1. I'm assuming value1 IS an array, and you're picking the first element in it value1[0] to then iterate?
$.each(data, function(key,value1){
$.each(value1[0], function(key,value2){
Or maybe you're after
$.each(data, function(key,value1){
$.each(value1, function(key,value2){
Please echo the object and show it to us.
I am trying to create a little ajax chat system (just for the heck of it) and I am using prototype.js to handle the ajax part.
One thing I have read in the help is that if you return json data, the callback function will fill that json data in the second parameter.
So in my php file that gets called I have:
header('Content-type: application/json');
if (($response = $acs_ajch_sql->postmsg($acs_ajch_msg,$acs_ajch_username,$acs_ajch_channel,$acs_ajch_ts_client)) === true)
echo json_encode(array('lastid' => $acs_ajch_sql->msgid));
else
echo json_encode(array('error' => $response));
On the ajax request I have:
onSuccess: function (response,json) {
alert(response.responseText);
alert(json);
}
The alert of the response.responseText gives me {"lastid": 8 } but the json gives me null.
Anyone know how I can make this work?
This is the correct syntax for retrieving JSON with Prototype
onSuccess: function(response){
var json = response.responseText.evalJSON();
}
There is a property of Response: Response.responseJSON which is filled with a JSON objects only if the backend returns Content-Type: application/json, i.e. if you do something like this in your backend code:
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($answer));
//this is within a Codeigniter controller
in this case Response.responseJSON != undefined which you can check on the receiving end, in your onSuccess(t) handler:
onSuccess:function(t) {
if (t.responseJSON != undefined)
{
// backend sent some JSON content (maybe with error messages?)
}
else
{
// backend sent some text/html, let's say content for my target DIV
}
}
I am not really answering the question about the second parameter of the handler, but if it does exist, for sure Prototype will only provide it in case of proper content type of the response.
This comes from Prototype official :
Evaluating a JavaScript response
Sometimes the application is designed
to send JavaScript code as a response.
If the content type of the response
matches the MIME type of JavaScript
then this is true and Prototype will
automatically eval() returned code.
You don't need to handle the response
explicitly if you don't need to.
Alternatively, if the response holds a
X-JSON header, its content will be
parsed, saved as an object and sent to
the callbacks as the second argument:
new Ajax.Request('/some_url', {
method:'get', onSuccess:
function(transport, json){
alert(json ? Object.inspect(json) : "no JSON object");
}
});
Use this functionality when you want to fetch non-trivial
data with Ajax but want to avoid the
overhead of parsing XML responses.
JSON is much faster (and lighter) than
XML.
You could also just skip the framework. Here's a cross-browser compatible way to do ajax, used in a comments widget:
//fetches comments from the server
CommentWidget.prototype.getComments = function() {
var commentURL = this.getCommentsURL + this.obj.type + '/' + this.obj.id;
this.asyncRequest('GET', commentURL, null);
}
//initiates an XHR request
CommentWidget.prototype.asyncRequest = function(method, uri, form) {
var o = createXhrObject()
if(!o) { return null; }
o.open(method, uri, true);
o.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
var self = this;
o.onreadystatechange = function () {self.callback(o)};
if (form) {
o.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
o.send(makePostData(form));
} else {
o.send('');
}
}
//after a comment is posted, this rewrites the comments on the page
CommentWidget.prototype.callback = function(o) {
if (o.readyState != 4) { return }
//turns the JSON string into a JavaScript object.
var response_obj = eval('(' + o.responseText + ')');
this.comments = response_obj.comments;
this.refresh()
}
I open-sourced this code here http://www.trailbehind.com/comment_widget