API callback response - php

I'm using an API to send sms in my codeigniter project. After sending, it will return a response array in the form of json to a callback url in my project. And i need to update this response in my database. Here is my code :
the response array will be similar as follows :
{"req_id":"809ff62f-74a9-45a5-9cb5-5e60763289af","status":"0" ,"comment":"OK"}
my callback url redirects to following function in my controller
public function templateCallback() {
$json = file_get_contents('php://input');
$json = urldecode($json);
$obj = json_decode($json, TRUE);
$reqID = $obj->req_id;
$status = $obj->status;
print_r($obj);
$this->db->where('TemplateRequestID', $reqID);
$this->db->set('TemplateApproved', $status);
$this->db->update('templatemaster_tbl');
}
But its never get updated. What is wrong in my code ? I'm not good in json. So i'm not sure is this the correct way to fetch and decode json array in php. Someone please help me.
To test this i have created a view in my project and send this same array through an ajax function like :
var base_url = '<?php echo base_url()?>';
$('#test').click(function() {
var val = $('#testvalue').text();
$.ajax({
type: 'post',
url: base_url + 'API/templateCallback',
data: {
val
},
success: function (response) { console.log(response);
}
});
});
and try to print both $json and $obj in controller function.
$json displays a string like : val=%7B%22req_id%22%3A%228b3eef97-330a-4271-8450-0676fbac8885%22%2C%22status%22%3A%220%22%2C%22comment%22%3A%22OK%22%7D
and $obj displays nothing

If your $json contains encoded value (%7B%22req_id%22%3A%228b3eef97-330a-4271-8450-0676fbac8885%22%2C%22status%22%3A%220%22%2C%22comment%22%3A%22OK%22%7D) you should decode it first with urldecode.
So proper code would be:
...
$jsonEncoded = file_get_contents('php://input');
$json = urldecode($jsonEncoded);
$obj = json_decode($json, TRUE);
...

Related

Trying to extract information throught a PHP file Undefined

I'm trying to extract the information with a XHR request (AJAX) to a php file (this php file gets the information throught json file with Get request too) so when I try to do console.log(Checker) on the console, it returns Undefined and if I put alert(Checker) it returns [object Object]. How can I solve it?
PHP:
<?php
headers('Content-Type', 'application/json')
$jsonContents = file_get_contents('../data/data.json');
echo $jsonContents
?>
JS:
function start() {
$.ajax({
type: 'GET',
url: 'api/domain/showall.php',
dataType: 'json',
success: function(data) {
alert(data)
displayTheData(data)
}
});
}
function displayTheData(data) {
Checker = data;
JSON.stringify(Checker)
console.log(Checker)
window.Checker = Checker;
}
JSON:
[{"name":"Google","url":"google.es","id":1}]
Here you are strigify data but not store value i any var.
function displayTheData(data) {
Checker = data;
var displayChecker = JSON.stringify(Checker) /// add displayChecker
console.log(displayChecker ) // print it
window.Checker = Checker;
}
There is not displayTheData() function so first call it and pass response params.
You need to echo the JSON Response ! Change return $jsonContents; to echo $jsonContents; it will work !!!
You must parse data into body (not returning it which has no meaning outside a function) and, optionnaly but much better, fill some headers. A very minimalistic approach could be :
<?php
headers('Content-Type', 'application/json');
$jsonContents = file_get_contents('../data/data.json');
echo $jsonContents // echo JSON string
?>

Codeigniter Post data using AngularJS

I've built CRUD application using Codeigniter + AngularJS
how to post data in code-igniter controller
I am using this function get all POST data
$data = json_decode($this->input->raw_input_stream , TRUE);
But I want specific value using this function but response is NULL
$x = $this->input->input_stream('email', TRUE);
and one more question is how to apply code-igniter form validation
for this $data
Thank You
Please help me
Try following way.
I've assumed your code and provided an example, do the necessary changes as per your need.
Angular Js
console.log("posting data....");
$http({
method: 'POST',
url: '<?php echo base_url(); ?>user/add',
headers: {'Content-Type': 'application/json'},
data: JSON.stringify({name: $scope.name,city:$scope.city})
}).success(function (data) {
console.log(data);
$scope.message = data.status;
});
Controller action
public function add()
{
// Here you will get data from angular ajax request in json format so you have to decode that json data you will get object array in $request variable
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$name = $request->name;
$city = $request->city;
$id = $this->user_model->AddUser($name,$city);
if($id)
{
echo $result = '{"status" : "success"}';
}else{
echo $result = '{"status" : "failure"}';
}
}

Ajax + PHP: null instead of an array

Ajax call is made in the background
var signupValidate = function(elementID){
var value = $('#' + elementID).val();
if (value !== ''){
$('#'+elementID+'-status').css("background-image", "url(img/signup/spinner.gif)");
var data = {elementID: value};
var json = JSON.stringify(data);
$.ajax({
url: 'php/validator_signup.php',
dataType: 'json',
type: 'post',
data: json,
success: function(data){
var parsedResponse = JSON.parse(data);
console.log(parsedResponse);
/*
if(data.response === 1){
$('#'+elementID+'-status').css("background-image", "url(img/signup/no.png)");
}else if(data.response === 0){
$('#'+elementID+'-status').css("background-image", "url(img/signup/yes.png)"); }
*/
}
});
}
}
validator_signup.php received the call. So far in test mode PHP will receive the string, parse it and encode again to return to JS:
$post = $_POST['data'];
$data = json_decode($post, true); //decode as associative array
$details = $data[0];
echo json_encode($details);
JS then needs to print this in console.
I get this:
null
instead of the value which I expect back.
Result is same whether I parse returned data or not.
If I understand it correctly, the problem is on PHP side?
There does not appear to be any value in converting to json when your data is so simple, you can just use a regular js object that jquery will convert to form data.
Also, as both the key and value you send are unknown, i would suggest sending the data in a different structure so its easy to retrieve:
var signupValidate = function(elementID){
var value = $('#' + elementID).val();
if (value !== ''){
$('#'+elementID+'-status').css("background-image", "url(img/signup/spinner.gif)");
$.ajax({
url: 'php/validator_signup.php',
type: 'post',
// ▼key ▼value ▼key ▼value
data: { id: elementID, val: value},
success: function(response){
console.log(response.message);
}
});
}
}
In php you can access the data via $_POST, and as you know the keys, its simple:
<?php
$id = $_POST['id'];
$val = $_POST['val'];
//set correct header, jquery will parse the json for you
header('Content-Type: application/json');
echo json_encode([
'message'=>'Request received with the id of: ' . $id . 'and the value of: ' . $val,
]);
die();
Change:
data: json,
To:
data: { data: json},
This is because you aren't giving the sent data a POST parameter to then be used server side to retrieve it.
Then, you can simply fetch the code server-side like this:
$data = json_decode($_POST['data']);
Hope this helps!
Here, since you are checking whether data is being post, if you see in Network, no data is being posted. To fix it, change this part:
var data = {elementID: value};
To this:
var data = {data: {elementID: value}};
Consider removing conversion of Data
PHP automatically handles the $_POST as an array! So you don't need to use the reconversion. Please eliminate this part:
var json = JSON.stringify(data); // Remove this.
And in the server side:
$data = json_decode($post, true); // Remove this
$data = $_POST['data']; // Change this
Update
OP said data[elementID]:gh is sent to the PHP file.
If this is the case, then if the data needs to be "gh" in JSON, then:
$res = $_POST["elementID"];
die(json_encode(array("response" => $res)));
This will send:
{
"response": "gh"
}
And in the client side, you don't need anything other than this:
$.post('php/validator_signup.php', function (data) {
var parsedResponse = JSON.parse(data);
console.log(data);
});
JSON data is sent to the server as a raw http input it is not associated with query name like $_POST['data'] or anything like that which means you must access the input string not a data post value to do so you need to use
$rawInput = json_decode(file_get_contents('php://input'), true);
$elementValue = $rawInput['elementId'];
thats it
$_POST = json_decode(file_get_contents('php://input'), true);
$data = $_POST['data'];

How to get data from json_encode?How to get respone by using AJAX?

I want to get use and its status in php from this json_encode response.How do I get it? Request Like json_encode(array('online' => $status))
{"online":[{"user":"1004","status":"Unmonitored"},
{"user":"1005","status":"Unmonitored"},
{"user":"1006","status":"Unmonitored"},
{"user":"2501","status":"Unmonitored"},
{"user":"2502","status":"Unmonitored"},
{"user":"2503","status":"Unmonitored"},
{"user":"2504","status":"Unmonitored"}]}
Seems json_decode is the function you are looking for.
<?php
$data = '{"online":[
{"user":"1004","status":"Unmonitored"},
{"user":"1005","status":"Unmonitored"},
{"user":"1006","status":"Unmonitored"},
{"user":"2501","status":"Unmonitored"},
{"user":"2502","status":"Unmonitored"},
{"user":"2503","status":"Unmonitored"},
{"user":"2504","status":"Unmonitored"}
]}';
// json_decode produces stdClass object
$decoded_std = json_decode($data);
var_dump($decoded_std->online[0]->status); // "Unmonitored"
// json_decode produces associative array
$decoded_array = json_decode($data, true); // note the second param
var_dump($decoded_array['online'][0]['status']); // "Unmonitored"
Check the hosted working example here http://ideone.com/xaCx4E.
PHP 5.4 offers the JSON_PRETTY_PRINT option for use with the json_encode() call.
http://php.net/manual/en/function.json-encode.php
<?php
$json_string = json_encode($data, JSON_PRETTY_PRINT);
?>
You can decode JSON using the json_decode() function like so:
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
(json_decode($json);
?>
Another Example (read a specific object):
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$obj = json_decode($json); //read a specific object
print $obj->{'a'}; // 1
?>
UPDATE I see you updated your question to 'How to get response by using AJAX?'
//start ajax request
$.ajax({
url: "data.json",
success: function(data) {
//data downloaded so we call parseJSON function
//and pass downloaded data
var json = $.parseJSON(data);
//do what you want to do here
}
});

send datas to php with ajax - Internal Server Error(500)

i try to send my datas to php with ajax but there's strange mistake.
this is my ajax script,
function deleteData2()
{
var artistIds = new Array();
$(".p16 input:checked").each(function(){
artistIds.push($(this).attr('id'));
});
$.post('/json/crewonly/deleteDataAjax2',
{ json: JSON.stringify({'artistIds': artistIds}) },
function(response){
alert(response);
});
}
i think this works correctly but in php side, i face 500 internal server error(500).
public function deleteDataAjax2() {
$json = $_POST['json'];
$data = json_decode($json);
$artistIds = $data['artistIds'];
$this->sendJSONResponse($artistIds);
}
Above code is my php. For example, when i try to send $data to ajax,
i print my ids in json mode:
However, when i try to send $artistIds to ajax side, i gives 500 error why?
Selam :)
Right should be:
public function deleteDataAjax2() {
$json = $_POST['json'];
$data = json_decode($json, true);
$artistIds = $data['artistIds'];
$this->sendJSONResponse($artistIds);
}
look at json_decode(). If you wanna use this as an array, you have to set the second parameter to true, otherwise use $data->{'artistIds'}; :)
try something like this and see if you get a response.
$.getJSON('/json/crewonly/deleteDataAjax2',
{ 'artistIds' : artistIds },
function(response){
alert(response);
});
public function deleteDataAjax2() {
$json = $_REQUEST['artistIds'];
$data = json_decode($json);
var_dump($data);die(null);
}

Categories