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;
}
Related
I have been follow godot documentation to send data to my server. The connection is okay, but the data sent to my php web is always null. Anyone please guides me on this.
my godot codes:
func _make_post_request(url, data_to_send, use_ssl):
var query = JSON.print(data_to_send)
var headers = ["Content-Type: application/json"]
$HTTPRequest.request(url, headers, use_ssl, HTTPClient.METHOD_POST, query)
func _on_Button_pressed():
_make_post_request("http://localhost/buymall/site/test","Hello World",false)
func _on_HTTPRequest_request_completed(result, response_code, headers, body):
var json = JSON.parse(body.get_string_from_utf8())
print(json.result)
print(result)
print(response_code)
print(body.get_string_from_ascii())
my php codes:
public function actiontest()
{
$value = array(
'value'=>$_POST
);
if(isset($_POST) && $_POST!=null)
{
echo json_encode($value);
}else
{
echo "no post value";
}
}
The outcome when i press POST button is always return "no post value" from my php site. What are the things i did wrong?
Allow me to preface this by saying that I looked at multiple SO posts on this and I am still lost.
So in my php code I am fetching data from my database and then I am trying to insert it into an array as follows:
$arrayResult = array();
foreach ($result as $item) {
array_push($arrayResult, array("type" => $item['type'],
"count" => $item['count'])
);
}
echo json_encode($arrayResult);
My problem is as follows, the only time my JS shows any data is when I just print out the data on a successful AJAX call, any attempts at manipulating it fail totally. As in, no data shown at all.
var arrayResult = null;
$.get("../php/displayGraph.php",
function (data) {
arrayResult = (data);
var result = JSON.parse(arrayResult);
$("#results").html(arrayResult);
//$("#results").html(JSON.parse(arrayResult));
}
);
The result of this is:
[{"type":"Entertainment","count":"4"},{"type":"Other","count":"31"},{"type":"Politics","count":"50"},{"type":"Sports","count":"3"},{"type":"Technology","count":"9"}]
I am honestly at a loss in terms of what I even need to do to make it work. And here I thought java was bad with json.
Try like this,
$.get("../php/displayGraph.php",
function (data) {
$.each(data, function (i,item){
console.log(item.type + " === " +item.count);
}
/*arrayResult = (data);
var result = JSON.parse(arrayResult);*/
//$("#results").html(arrayResult);
//$("#results").html(JSON.parse(arrayResult));
}
);
Not sure why, but the following works
$.get("../php/displayGraph.php",
function (data) {
var result = JSON.parse(data);
$("#results").html(data);
console.log(result[1][0].count);
}
);
Certainly is a 2D array the way my php makes it, but i did not think this would be how to do as all the other tutorials i saw never had it like this.
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.
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);
?>
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