AngularJS Post data to PHP - trying to get property of non-object - javascript

I've been trying to post data from AngularJS to a PHP script and I'm having a little problem.
$scope.submitRecipe = function () {
$http({
url: "../assets/php/scripts/create-recipe.php",
method: "POST",
data: {
"recipeName" : $scope.recipeName
}
}).then(function (response) {
alert(response.data);
});
}
PHP Code:
<?php
$request = json_decode(file_get_contents("php://input"));
echo $request->recipeName;
?>
When I submit (call the function submitRecipe()) it does return the recipeName but it then continues to my PHP Script and I get the error:
Notice: Trying to get property of non-object in..
Any help and pointers are greatly appreciated.

My guess is that json_decode returned null, causing this line to throw the error.
echo $request->recipeName;
Check that the data return by
json_decode(file_get_contents("php://input"))
is infact not null and the Content-Type is application/json

Related

Controller function call from JS- JSON parse error - only in firefox

I have a button, which on click should insert the users into table.
Basically im stuck in calling the controller function from my javascript.
HTML button.
<div class="continue_btton">
<input type="submit" name="submit" id="SaveSettings" value="<?php echo $this->translate('Update'); ?>" class="update bdr_rds2" onclick="if($('input[name=target_criteria]:checked').val() == 'optedin_users')
{
return someFun()
} else
{
return validateForm()
}
">
</div>
UPDATED:
Javascript
function someFun(){
var urlInsert = '#Url.Action("myFunAction")';
$.get(urlInsert, function () {
});
}
Also tried below, but the controller func not calling
function myFunAction(){
var formData = $("#Preference").serialize();
$.ajax({
type: 'POST',
url: '/advertiser/campaign/myFun',
data: formData,
dataType: 'html',
success: function (data) {
$('span.targetCount').text($.trim(data));
},
error: function (jqXHR, textStatus, errorThrown) {
var error = $.parseJSON(jqXHR.responseText);
var content = error.content;
console.log(content.message);
if (content.display_exceptions)
console.log(content.exception.xdebug_message);
},
});
}
Controller.php - Doesnt seem to be called
public function myFunAction(){
echo '+++myFUN---';exit;
}
Error:
JSON.parse: unexpected character at line 1 column 1 of the JSON data
Tried dataType as html, json and text. Still same error.
My guess is either your post data or your response object is not considered valid json and that is why Firefox throws an error (maybe Chrome is more forgiving). What you could check is whether the request is send correctly and whether the response from the server actually arrives and whether it is valid json. You should consider returning valid json from your myFunAction method in your controller (instead of just printing a string like you do right now):
public function myFunAction(){
$data = '+++myFUN---';
return new JsonModel([
'data' => $data
]);
}
Check more on how to properly return Json in Zend for example on this blog post here: https://akrabat.com/returning-json-from-a-zf2-controller-action/
Valid json response should have a content-type header set to application/json and have a valid json string in the response body. Zend JsonModel will help you with this.
When you post data you should also set the content-type of the request to application-json, like that the server understands that you are sending a json object with data.
I never use JQuery but I think it is done like this if I am not mistaken:
$.ajax({
type: 'POST',
url: '/advertiser/campaign/myFun',
data: formData,
contentType: "application/json",
});

Unable to get response from php return in ajax request

I am trying to access the output from php code to jquery ajax. But I donot know why It is returning me whole page html including the result. can anybody please tell me about it. In firefox console Its show me response of page html including php result. But In jquery code console.log does not hit.
Here is jquery code
function getprofile()
{
$.ajax({
url: 'Userpage/get_profile',
//data: {'title': title}, change this to send js object
type: "post",
dataType: 'json',
data: {'userid': 1},
success: function(data) {
console.log(data);
}
});
}
My php code
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Userpage extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->helper('form');
$this->load->library("session");
$this->load->model("Userpage_model");
$this->load->view('Userpage_view');
}
public function index()
{
}
public function get_profile()
{
$data = array();
$post_id = $this->input->post('userid');
$data['comments'] = $this->Userpage_model->get_profile($post_id);
echo json_encode($data['comments']);
exit;
}
}
?>
Please review the code and tell me where I am going wrong
Thanks
Use exit
public function get_profile()
{
$data = array();
$post_id = $this->input->post('userid');
$data['comments'] = $this->Userpage_model->get_profile($post_id);
echo json_encode($data['comments']);
exit; // use exit here
}
EDIT
PHP uses a special function called header() for setting properties of the page during rendering.
you need to return from your function, using exit is fine but it's not a good practice
public function get_profile()
{
$data = array();
$post_id = $this->input->post('userid');
$data['comments'] = $this->Userpage_model->get_profile($post_id);
return json_encode($data['comments']);
}
You are using CI. From this ajax call:
$.ajax({
url: 'Userpage/get_profile',
success: function(data) {
console.log(data);
}
});
you expect an ajax call is being made to get_profile action inside Userpage controller, that probably will return:
{
"comments": [
{ ... },
{ ... },
{ ... },
...
]
}
which will be logged in browser console.
But you get unexpected result, right?
I think, your ajax call results in error. To prove this, modify your ajax call:
$.ajax({
url: 'Userpage/get_profile',
success: function(data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
// add this function to logs error
console.log(textStatus + ': ' + errorThrown);
}
});
Now, if the ajax call results in error, you can see the error in browser console. I am pretty sure you will get error: Not Found in browser console.
You are using CI, the URL will be something like:
http://<something>/index.php/site/index
In this page, if you make ajax call with url Userpage/get_profile, what the browser really does is make ajax call to:
http://<something>/index.php/site/index/Userpage/get_profile
instead of what you expect:
http://<something>/index.php/Userpage/get_profile
To solve this, you must change the value of url in your ajax call, to point the correct URL above.
By using CI, the absoulte URL above can be generated with the help of site_url() function:
site_url('Userpage/get_profile')
I usually print this URL somewhere in HTML, and retrieve it from javascript during ajax call.

Cant read php JSON encoded data in js

I'm calling a php script via AJAX which returns a json encoded object.
$.post("php/getCamera.php", {
cam_id: identifier
}, function(data){
console.log(data);
//var camera = JSON.parse(data);
var camera = $.parseJSON(data);
console.log(camera.name);
console.log(data['name']);
console.log(camera['name']);
});
}
Here's my php script:
<?php
require 'Camera.php';
$camera = new Camera();
if(isset($_POST["cam_id"])) {
$cam_obj = $camera->getCamera($_POST['cam_id']);
$cam_obj_array = get_object_vars($cam_obj);
echo json_encode($cam_obj_array);
}
?>
And here's my camera class:
class Camera
{
public $id;
public $name;
...
}
In the js console, I see the encoded data, but I can't access its elements:
{"id":"6","name":"camera 1"}
undefined
undefined
undefined
undefined
add 'json' at the end of your post request :
$.post("php/getCamera.php", {
cam_id: identifier
}, function(data){
console.log(data);
console.log(camera.name);
console.log(data['name']);
console.log(camera['name']);
}, 'json');
}
It's a shorthand for full ajax syntax dataType: "json".
Better, use getJSON instead of post (but then, remove 'json' :)
Try this:
console.log(data.name);
It appears, from your log, that the data is already a JSON object, and so needs no further parsing.

how to create correct PHP json response

Hello i have a page can calla an ajax page in json with jquery.
i just set
dataType: "json"
in ajax call and i set header in php
header("Content-type: application/json; charset=utf-8");
but when i try read my response in a client i have this error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
var o = JSON.parse(jsonString);
For more information
PHP file function:
function _addToWishlist($v,$db){
$ris = array();
$data = array();
$data[0]=20;
$data[1]=25;
$data[2]=30;
$ris['stato']="1";
$ris['mex']="DA IMPLEMENTARE!!!";
$ris['data']=$data;
$ris['action']="";
ob_clean();
echo json_encode($ris);
}
and thi is a php response:
{"status":"success","stato":"1","mex":"DA IMPLEMENTARE!!!","data":[20,25,30],"action":""}
in client i use this javascript:
$.ajax({
url: "common/function/include/dataLoad.php",
type: "POST",
data: datas,
async:false,
//dataType: "text",
dataType: "json",
success: function(ris) {
// Run the code here that needs
// to access the data returned
//$(this).parent
//alert (ris);
risp=ris;
//var a = JSON.parse(ris);
tryParseJSON(ris);
//return ris;
},
error: function() {
alert('Errore di rete');
}
}).done(function(){
if(divwhere!=""){
$(divwhere).html(risp);
}
if(actionAfter!=""){
eval(actionAfter);
}
});
the function for test json is here: stackoverflow
how can i do for create a correct call json? thank you very much
jQuery will automatically parse a JSON response for you - you don't need to do it again. The returned ris object is ready for you to work with as-is. Assuming the request works, there is no problem with the format of your PHP response.
success: function(ris) {
console.log(ris.status); // = 'success'
console.log(ris.mex); // = 'DA IMPLEMENTARE!!!'
},

Saving ajax POST data with PHP

I've been trying to save some data to a .json file with ajax and php.
At the moment I'm receiving an error and my data is not being saved and can't figure out why.
This is my .js file:
var data = {
"test": "helloworld"
}
$.ajax({
url: "save.php",
data: data,
dataType: 'json',
type: 'POST',
success: function (data) {
$("#saved").text("Data has been saved.");},
error: function (data){
$("#saved").text("Failed to save data !");}
});
And here is my php file:
$json = $_POST['data'];
if(json_decode($json) != null){
$file = fopen('web/js/data_save.json', 'w+');
fwrite($file, json_encode($json));
fclose($file);
}else{
print("<pre>Error saving data !</pre>");
}
When I'm trying to save the ajax error is getting triggered:
error: function (data){
$("#saved").text("Failed to save data !");
}
I hope someone can guide me in the right direction :)
this works fine for me
.js:
$(document).ready(function() {
var json_object = {"data": "helloworld"};
$.ajax({
url: "../tests/save.php",
data: json_object,
dataType: 'json',
type: 'POST',
success: function(json_object) {
console.log(json_object);
$("#saved").text("Data has been saved.");
},
error: function(json_object) {
console.log(json_object);
$("#saved").text("Failed to save data !");
}
});
});
.php
$post_data = $_POST['data'];
if (!empty($post_data)) {
$file = fopen('data_save.json', 'w+');
fwrite($file, json_encode($post_data));
fclose($file);
echo json_encode('success');
}
if you do a var_dump on the $_POST you ll see that your variable is sent as an array in php. also you need to echo a json string for the callback success
You do not have any key data in your request.
You need to parse the whole request body as JSON with http_get_request_body or something to get the raw body in order to get the result you want.
EDIT: As it seems that there has been some confusion, here are some further explanations.
When sending a JSON POST request to PHP, you cannot use the $_POST variable as you would with a normal request.
curl -H 'Content-Type: application/json' -d '{"foo": "bar"}' myhost/foo.php
with foo.php defined as bellow will print an empty array, try it yourself if you want.
<?php
print_r($_POST);
When you need to get JSON from the body of the POST request, you need to get all the body, and then parse it from JSON.
You can do this in several ways, one of which being the one I wrote before editing.
You can also get the whole body without using any extension by using
file_get_contents('php://input')
The result should be the same.
So with the code bellow you should get what you want.
<?php
$json = json_decode(file_get_contents('php://input'), true);
print_r($json);

Categories

Resources