Get json value on any php page - php

I am creating json object but can't access its value in php.I am trying to access json object in php and assign that object to php variable.My js code is
var arr= [];
var data={ "tab" : 'system' };
jObjArr = arr.push(data);
var JSONstr = JSON.stringify(jObjArr);
what i am missing ?
I try to get tab value on that page in php.

Try to pass simple object rather than sending an array:
function send_me() {
//var arr = [];
var data = { "tab": 'system' };
//jObjArr = arr.push(data);
//var JSONstr = JSON.stringify(data);
$.ajax({
url: "a_blank.php",
type:"post",
data: data,
success: function (response) {
alert(response);
}
});
}
On php page side simply get as:
if($_SERVER["REQUEST_METHOD"]=="POST")
{
print_r($_POST['tab']);
die();
}

Related

don't retrieve object on php page which passed from ajax call

Hi i don't get retrieve Ajax Data to PhP page its throwing error. i pass data as json object.
The error i'm getting is
Edit.php
$('#regForm').on('submit', function (e) {
var url = document.URL; // Get current url
var id = url.substring(url.lastIndexOf('=') + 1);
var data1 = $("#regForm").serialize();
data = {data:data1,id:id};
console.log(data)
$.ajax({
method:"POST",
url: 'update.php',
dataType : 'json',
data: data,
success: function () {
alert('form was submitted');
}
});
});
update.php
if(isset($_POST["submit"]))
{
print_r($_POST['data']);
// Error::: Undefined index:data in
pass Id using hidden input field and then form data serialize then after you can use by name wise on php page.
$_POST['name'];
Read my comment, then look at this:
JavaScript may look like this
$('#regForm').on('submit', function(e){
var s = location.search.split('&'), serialId = s[s.length-1], idArray = serialId.split('=');
if(idArray.length === 2 && idArray[1].trim() !== '' && idArray[0].match(/^id$/i)){
var serialData = $(this).serialize()+'&'+serialId;
$.ajax({
method:'POST', url:'update.php', dataType:'json', data:serialData},
success:function(jsonObj){
console.log(jsonObj);
}
});
}
e.preventDefault();
});
PHP may look like this
<?php
if($_POST['id']){
// each property as $_POST[propertyHere]
// sending back to JavaScript
$c = new stdClass; $c->someProp = 'some value';
echo json_encode($c); // dataType is json so you should get Object as result
}
?>

I have arrays stored in a json object, I send them using ajax call to the server side, how to access the data?

$scope.addQunatity = function(){
var url="../php/mainPageFacture.php";
// store data from user in the js arrays
var quan_cls_crt=[$("#quan_cls_crt").val(),$("#quan_cls_crt2").val()];
var quan_piece=[$("#quan_piece").val(),$("#quan_piece2").val()];
var itemName=[$("#designList").val(),$("#designList2").val()];
var dechargementNote=[$("#dechargementNote").val(),$("#dechargementNote2").val()];
var itemIds=[78,75];
var func="addQunatity";
var data = {"function": func,
"quan_cls_crt":quan_cls_crt,
"itemId":itemIds,
"dechargementNote":dechargementNote,
"quan_piece":quan_piece};
data = JSON.stringify(data);
var options = {
type : "get",
url : url,
data: {data:data},
dataType: 'json',
async : false,
cache : false,
success : function(response,status) {
debugger;
$scope.getAllItemNames();
alert("success");
},
error:function(request,response,error){
alert("Error: " + error + ". Please contact developer");
}
};
$.ajax(options);
}
Here is my php code that will receive the Json object
function addQunatity(){
$quan_cls_crt = $_GET["quan_cls_crt"];
$quan_piece = $_GET["quan_piece"];
$itemId=$_GET['itemId'];
$dechargementNote=$_GET['dechargementNote'];
}
I expect to receive the json arrays and store them in php variable in order to use the in the query later on, but i have no idea how to access the arrays in the json object
You don't have to stringify the data, just send it as it is - the json data type causes jQuery to JSON-encode it for you. Don't make another object.
var data = {"function": func,
"quan_cls_crt":quan_cls_crt,
"itemId":itemIds,
"dechargementNote":dechargementNote,
"quan_piece":quan_piece};
var options = {
type : "get",
url : url,
data: data,
dataType: 'json',
async : false,
cache : false,
success : function(response,status) {
debugger;
$scope.getAllItemNames();
alert("success");
},
error:function(request,response,error){
alert("Error: " + error + ". Please contact developer");
}
};
$.ajax(options);
}
<?php
$received_data = file_get_contents('php://input');
$data = json_decode($received_data);
//Here now you can access
$variable_name = $data['keyname']; //this means instead of $_GET or $_POST or $_REQUEST
?>
You can access received json data to php using the file_get_contents('php://input'); method..
Dont stringify the data. Use your same code and remove the stringify line.
var url="../php/mainPageFacture.php";
// store data from user in the js arrays
var quan_cls_crt=[$("#quan_cls_crt").val(),$("#quan_cls_crt2").val()];
var quan_piece=[$("#quan_piece").val(),$("#quan_piece2").val()];
var itemName=[$("#designList").val(),$("#designList2").val()];
var dechargementNote=[$("#dechargementNote").val(),$("#dechargementNote2").val()];
var itemIds=[78,75];
var func="addQunatity";
var data = {"function": func,
"quan_cls_crt":quan_cls_crt,
"itemId":itemIds,
"dechargementNote":dechargementNote,
"quan_piece":quan_piece};
var options = {
type : "get",
url : url,
data: {data:data},
dataType: 'json',
async : false,
cache : false,
success : function(response,status) {
debugger;
$scope.getAllItemNames();
alert("success");
},
error:function(request,response,error){
alert("Error: " + error + ". Please contact developer");
}
};
$.ajax(options);
}
In the PHP side, like you have done -
$quan_cls_crt = $_GET["quan_cls_crt"];
$quan_piece = $_GET["quan_piece"];
$itemId=$_GET['itemId'];
$dechargementNote=$_GET['dechargementNote'];
And to access each of the values from array you can simply do that with $quan_cls_crt[0] or $quan_cls_crt[1]

Display JSON data in a PHP page

I have a PHP page that will return JSON data as output. I get the data as AJAX. I want to display the results from JSON. But when I try to display each value I am getting undefined error.
This is the PHP code for getting data:
if (isset($_POST['dcqid'])) {
$question_id = intval($_POST['dcqid']);
if ($question_id != "") {
$user_id = $session->id;
$questiondetail = getData("dcquestions", "dcqid", "dcqid", $question_id, "", "");
//print_r($questiondetail);
echo json_encode($questiondetail);
?>
}
}
This is the JSON output I am getting
[{"dcqid":"10","current_id":"3","question":"Another Question","answer":"This is another question","description":"This is the description","date":"2017-08-10 11:55:51","active":"1"}]
This is the AJAX code I am using to display data
<script type="text/javascript">
$(".edit-current").on('click', function (e) {
e.preventDefault();
var id = $(this).data('currentid');
alert(id);
var url = "<?php SITE_URL ?>admin/" + "admin_edit_current.php";
var info = 'dcqid=' + id;
$.ajax({
type: "POST",
url: url,
data: info,
success: function (data) {
console.log(data);
console.log(data.dcqid); // undefined
},
error: function (data) {
alert(data.responseText);
alert("Error occured in showing details");
}
})
});
</script>
I am currently getting undefined for the values I want to display.
Its because the data var is an array. it's like this:
data = [
{
dcqid : 123
}
]
so try using
console.log(data[0].dcqid)
1st : Access it like this
console.log(data[0].dcqid);
2nd : Add dataType in ajax
dataType:"json"
Note : your value is inside the 0th index . so you need to access it like above.
var data =[{"dcqid":"10","current_id":"3","question":"Another Question","answer":"This is another question","description":"This is the description","date":"2017-08-10 11:55:51","active":"1"}];
console.log(data[0].dcqid);

How to access AJAX response variables in PHP

I can't access my variables through ajax using php.
AJAX CODE
$("input[name='absent[]'").change(function() {
var obj = $(this); //checkbox
var valueZero = obj.val();
var Code = obj.attr('data-Code');
var value = obj.attr('data-session');
/*var theTR = $(this).parent('tr').children().find('td:eq(0)').addClass('hidden');*/
/* alert( theTR.text());*/
/*$(this).addClass('hidden');*/
$.ajax({
data: "{ code: '"+ Code +"', abt_prt: "+ valueZero +", InOut: "+ value +" }", // need to access these variables in php
type: "post",
dataType:'json',
url: "insertabsent.php",
success: function(){
obj.addClass('hidden');
}
});
});
PHP CODE
<?php
if(isset($_REQUEST))
{
$code = $_POST['code']; //variable
$absent_present = $_POST['abt_prt']; //variable
$session = $_POST['InOut']; //variable
//need this variables to perform a insert query
}
?>
Do try this :
JAVASCRIPT
var mainString = "code="+Code+"&abt_prt="+valueZero+"&InOut="+value;
IN AJAX
data : mainString
PHP
$code = $_POST['code']; //variable
$absent_present = $_POST['abt_prt']; //variable
$session = $_POST['InOut']; //variable
use data like
data: { code:Code , abt_prt : valueZero , InOut : value },
and in php I don't really know what is $_REQUEST is but you can use
if(isset($_POST)){
}
Try changing data variable to:
data: {"code":Code,"abt_prt":valueZero,"InOut":value},
You are misunderstanding how AJAX parameters have to be sent. You do not need to send an index, you can send a simple Javascript object, like this:
$.ajax({
data: { code: Code, abt_prt: valueZero, InOut:value}, // need to access these variables in php
type: "post",
dataType:'json',
url: "insertabsent.php",
success: function(){
obj.addClass('hidden');
}
});
However, if for some reason you want to send a string like you did, then decode it using json_decode.

Send javascript array to php using json

This question might be repetitive but i got confused reading all posts relating to this.(sincere apologies!) Basically, I want to send a javascript array to a php file and inturn write the array to a text file . I learnt the best way to go about it is using JSON and AJAX. My code is displays "success" for the ajax part, and also creates a file (php code),but an empty text file.
$('#tabletomodify').on('change','.street',
function (event)
{
event.preventDefault();
var row=( $(this).closest('tr').prop('rowIndex') );
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
var ideSelected= this.id;
var values = [valueSelected];
for ($i=3;$i<row;$i++)
{
var dv="selectstate"+$i;
var dv1=document.getElementById(dv).value;
var sl="selectstreet"+$i;
var sl1=document.getElementById(sl).value;
var po="selectbuilding"+$i;
var po1=document.getElementById(po).value;
var concat=dv1+sl1+po1;
values.push(concat);
}
JSON = JSON.stringify(values);
$.ajax({
url: "get_buildings.php",
type: 'POST',
data: JSON ,
success: function(){
alert("Success!")
}
});
PHP Code:-
<?php
$json = $_POST['JSON'];
$p = json_decode(JSON);
$file = fopen('test.txt','w+');
fwrite($file, $p);
fclose($file);
echo 'success?';
?>
Two flaws:
a) You're not sending your data correctly - it's lacking a field name:
data: {data: JSON}
^^^^---this will be the key in PHP's $_POSt
b) You're using invalid constants in PHP and not even decoding what MIGHT have been the passed in data. You should have:
$p = json_decode($_POST['data']);
^^^^--matching what you have in the `data` field in Javascript.

Categories