access json fields in javascript - javascript

I am trying to access field of json respose :
$.ajax({
type: 'POST',
url: './get_data_json.php',
success: function(response) {
console.log(response);
console.log(response['time']);
console.log(response['0']['key'])
}
});
The get_data_json.php file is like this:-
<?php header('Access-Control-Allow-Origin: *');
$str = file_get_contents('./data.json');
echo $str;
?>
and the data.json file is like:-
{"time":"08\/11\/2017 11:10:01 am","0":{"key":"\u3075\u308b\u3055\u3068\u7d0d\u7a0e","doc_count":31626,"old_count":25737},"1":{"key":"\u5b89\u5ba4\u5948\u7f8e\u6075","doc_count":19526,"old_count":13778},"2":{"key":"\u9001\u6599\u7121\u6599","doc_count":18881,"old_count":14411},"3":{"key":"\u3010\u8a33\u3042\u308a\u3011","doc_count":13415,"old_count":7770},"4":{"key":"\u5b89\u5ba4\u5948\u7f8e\u6075 finally","doc_count":12593,"old_count":13778},"5":{"key":"\u30ef\u30f3\u30d4\u30fc\u30b9","doc_count":9516,"old_count":9203},"6":{"key":"\u798f\u888b","doc_count":8998,"old_count":5867},"7":{"key":"\u30cb\u30c3\u30c8","doc_count":8906,"old_count":9443},"8":{"key":"\u30af\u30ea\u30b9\u30de\u30b9","doc_count":8240,"old_count":4913},"9":{"key":"\u3010\u25ce\u3011","doc_count":7245,"old_count":7742},"10":{"key":"\u5317\u6b27","doc_count":7190,"old_count":6844},"11":{"key":"\u30b9\u30cc\u30fc\u30d4\u30fc","doc_count":6971,"old_count":5019},"12":{"key":"\u30c7\u30a3\u30ba\u30cb\u30fc","doc_count":6590,"old_count":5878},"13":{"key":"\u3010\u30d0\u30fc\u30b2\u30f3\u672c\u3011","doc_count":6398,"old_count":4536},"14":{"key":"\u52a0\u6e7f\u5668","doc_count":6393,"old_count":4850},"15":{"key":"\u30af\u30ea\u30b9\u30de\u30b9\u30c4\u30ea\u30fc","doc_count":6346,"old_count":4972},"16":{"key":"\u30d5\u30a1\u30fc","doc_count":6268,"old_count":5487},"17":{"key":"\u30a2\u30a6\u30c8\u30ec\u30c3\u30c8","doc_count":6057,"old_count":5305}}
The response for console.log(response) is:-
{"time":"08\/11\/2017 11:10:01 am","0":{"key":"\u3075\u308b\u3055\u3068\u7d0d\u7a0e","doc_count":31626,"old_count":25737},"1":{"key":"\u5b89\u5ba4\u5948\u7f8e\u6075","doc_count":19526,"old_count":13778},"2":{"key":"\u9001\u6599\u7121\u6599","doc_count":18881,"old_count":14411},"3":{"key":"\u3010\u8a33\u3042\u308a\u3011","doc_count":13415,"old_count":7770},"4":{"key":"\u5b89\u5ba4\u5948\u7f8e\u6075 finally","doc_count":12593,"old_count":13778},"5":{"key":"\u30ef\u30f3\u30d4\u30fc\u30b9","doc_count":9516,"old_count":9203},"6":{"key":"\u798f\u888b","doc_count":8998,"old_count":5867},"7":{"key":"\u30cb\u30c3\u30c8","doc_count":8906,"old_count":9443},"8":{"key":"\u30af\u30ea\u30b9\u30de\u30b9","doc_count":8240,"old_count":4913},"9":{"key":"\u3010\u25ce\u3011","doc_count":7245,"old_count":7742},"10":{"key":"\u5317\u6b27","doc_count":7190,"old_count":6844},"11":{"key":"\u30b9\u30cc\u30fc\u30d4\u30fc","doc_count":6971,"old_count":5019},"12":{"key":"\u30c7\u30a3\u30ba\u30cb\u30fc","doc_count":6590,"old_count":5878},"13":{"key":"\u3010\u30d0\u30fc\u30b2\u30f3\u672c\u3011","doc_count":6398,"old_count":4536},"14":{"key":"\u52a0\u6e7f\u5668","doc_count":6393,"old_count":4850},"15":{"key":"\u30af\u30ea\u30b9\u30de\u30b9\u30c4\u30ea\u30fc","doc_count":6346,"old_count":4972},"16":{"key":"\u30d5\u30a1\u30fc","doc_count":6268,"old_count":5487},"17":{"key":"\u30a2\u30a6\u30c8\u30ec\u30c3\u30c8","doc_count":6057,"old_count":5305}}
and I am getting message for
response['time'] = undefined
response['0']['key'] = undefined

Related

PHP not receiving AJAX POST from js File

I have been trying to work this out for hours now and cannot find any answer that helps me.
This is the code in my javascript file
function sendMovement(cel) {
var name = "test";
$.ajax({
type: 'POST',
url: '../game.php',
data: { 'Name': name },
success: function(response) {
console.log("sent");
}
});
}
This is the code from my PHP file (it is outside the js file)
if($_SERVER["REQUEST_METHOD"] == "POST") {
$data = $_POST['Name'];
console_log($data);
}
When debugging I can see that AJAX is sending a POST and it does print in the console "SENT" but it does not print $data
update: the function console_log() exists in my PHP file and it works
Try getting response in JSON format, for that your js should have dataType:'JSON' as shown below
JS Code:-
function sendMovement(cel) {
var name = "test";
$.ajax({
type: 'POST',
dataType:'JSON', //added this it to expect data response in JSON format
url: '../game.php',
data: { 'Name': name },
success: function(response) {
//logging the name from response
console.log(response.Name);
}
});
}
and in the current server side code you are not echoing or returning anything, so nothing would display in ajax response anyways.
changes in php server code:-
if($_SERVER["REQUEST_METHOD"] == "POST") {
$response = array();
$response['Name'] = $_POST['Name'];
//sending the response in JSON format
echo json_encode($response);
}
I fixed it by doing the following:
To my game.php I added the following HTML code (for debugging purposes)
<p style = "color: white;" id="response"></p>
Also added in my game.php the following
if($_SERVER["REQUEST_METHOD"] == "POST") {
$gameID = $_POST['gameID'];
$coord = $_POST['coord'];
$player = $_POST['player'];
echo "gameID: " . $gameID . "\nCoord: " . $coord . "\nPlayer: " . $player;
}
AND in my custom.js I updated
function sendMovement(cel) {
var handle = document.getElementById('response');
var info = [gameID, cel.id, current_player];
$.ajax({
type: 'POST',
url: '../game.php',
data: {
gameID: info[0],
coord: info[1],
player: info[2]
},
success: function(data) {
handle.innerHTML = data;
},
error: function (jqXHR) {
handle.innerText = 'Error: ' + jqXHR.status;
}
});
}

ajax, variable not defined?

I cant find whats is wrong with my code. When printing the json file from the post_receiver.php, the json is printed accordingly.
The JSON printed from the post_receiver.php
<?php
session_start();
ob_start();
require_once('../../mysqlConnector/mysql_connect.php');
$result_array = array();
$query="SELECT COUNT(initID) AS count, urgency, crime, initID, TIMESTAMPDIFF( minute,dateanalyzed,NOW()) AS minuteDiff FROM initialanalysis WHERE commanderR='0' AND stationID='{$_SESSION['stationID']}';";
$result=mysqli_query($dbc,$query);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push($result_array, $row);
}
}
echo json_encode($result_array);
?>
Result from above:
[{"count":"10","urgency":"Low","crime":"Firearm","initID":"5","minuteDiff":"329"}]
my ajax code:
$.ajax({
method: 'POST',
url: "post_receiver.php",
data: {
'count': count,
'urgency': urgency
},...
the 'count' and 'urgency' variable is not defined, i am not that familiar with JSON format...
In your success callback, you get a data string, which contains the response. To parse it as JSON, use the json dataType setting:
$.ajax({
method: 'POST',
url: 'post_receiver.php',
dataType: 'json',
success: function (data) {
// 'data' contains the parsed JSON
console.log('Count:', data[0].count); // read the values from the JS object and log them to the console
console.log('Urgency:', data[0].urgency);
}
});

Passed the variable through javascript but not getting it in php?

i am passing my variable throught an AJAX request in javascript but not getting it in my php file. NOt sure where i am going wrong.?
JS code
var build = {
m_count : (document.getElementById('count').value),
}
$.ajax({
data: build,
type: "POST",
url: "tabs.php",});
PHP code
<?php
$module_c = $_POST['data'];
echo $module_c;
?>
You have to get the data by the name of the variable you want to get, which is m_count.
<?php
$module_c = $_POST['m_count'];
echo $module_c;
?>
EDIT:
Like suggested in the comments, change your JavaScript code to:
var build = {
m_count : (document.getElementById('count').value)
}
$.ajax({
data: build,
type: "POST",
url: "tabs.php",
success: function(data) {
alert(data);
}
});
PHP:
<?php
$module_c = $_POST['m_count'];
echo $module_c;
?>
JS:
var build = {
m_count : (document.getElementById('count').value),
}
$.ajax({
url: 'php/server.php',
type: 'POST',
data: build,
})
.done(function(msg) {
// JSON.parse turns a string of JSON text into a Javascript object.
var message = JSON.parse(msg);
alert(message);
}
})
.fail(function(err) {
console.log("Error: "+err);
})
.always(function() {
console.log("Complete");
})
;

AJAX call sending JSON data

I am working on a chat system which refreshes automatically using AJAX. First I was using the jQuery $.post function, but since i wanted to return JSON data from my PHP script, i want to use the $.ajax function. My script worked well using the $.post function, but i can not return JSON. This is the relevant code:
Javascript:
$.ajax({
url: "pages/loadmessage.php",
type: "POST",
data: {"c": getUrlParameter("c"), "t": messagetime},
dataType: "json",
success: function(pData){
console.log(pData);
},
error: function(xhr, status, error) {
alert(error + status);
}
});
PHP Code:
<?php
require_once("../init.php");
header('Content-Type: application/json');
if (Input::exists() && Input::get("c") && Input::get("t")) {
$chat = new Chat($user->data()->ID, Input::get("c"));
$messages = $chat->getNewMessages(Input::get("t"), $user->data()->ID);
if ($messages) {
$result = array(
'topic' => $chat->getTopic(),
'messages' => array()
);
foreach($messages as $m) {
array_push($result['messages'], array('source' => 'mine', 'Text' => $m->Text));
}
echo json_encode("string!!!");
}
} else {
echo json_encode("string" . Input::get("c") . Input::get("t") . Input::exists());
}
?>
I already tried to set the contentType of the AJAX call to "application/json" and convert the data to JSON using JSON.stringify, but then no input data gets to the PHP script. The code works if just one parameter (data: {"c": getUrlParameter("c")}) is sent to the PHP script...
I already searched StackOverflow, but i could not find a solution...
Thanks
JSON example:
Index.html
<script type="text/javascript">
$.ajax({
url: "out.php",
type: "POST",
data: {"param1": "test 1", "param2": "test2"},
dataType: "json",
success: function(data){
alert("param1:"+data.param1+" | param2:"+data.param2);
},
error: function(xhr, status, error) {
alert(error + status);
}
});
</script>
out.php
<?php
if(isset($_POST["param1"])){ $param1 = $_POST["param1"];}
if(isset($_POST["param2"])){ $param2 = $_POST["param2"];}
$out = array("param1"=>$param1,"param2"=>$param2);
echo(json_encode($out));
?>

Does ajax need contentType to send to php ? if so why error?

I been trying to figure this one out but i don't seem to find the error but in my script
My script
$('#Bshift').click(function(){
var isValid=false;
isValid = validateForm();
if(isValid)
{
var ArrId= <?php echo json_encode($arrId ); ?>;
var ArrQty= <?php echo json_encode($arrQty ); ?>;
var counter= <?php echo json_encode($i ); ?>;
var productId;
var productQty;
for (i = 0; i < counter; i++) {
productQty = ArrQty[i];
productId= ArrId[i];
var pLocal= document.getElementById(productId).value;
var prodData = 'pLocal=' + pLocal+ '&proId='+productId;
$.ajax ({
url: 'shiftSave.php',
type: 'POST',
data: prodData,
dataType: 'json',
contentType: "application/json; charset=utf-8", // this is where have the error
});
}
var pettyCash= document.getElementById("pettyCash").value;
var comment= document.getElementById("comment").value;
var prodData1 = 'pettyCash=' + pettyCash+ '&comment='+comment;
$.ajax ({
url: 'shiftSave.php',
type: 'POST',
data: prodData1,
dataType: 'json',
contentType: "application/json; charset=utf-8 ", // Error here too
}).done(function(data){
alert("Data Saved. Shift Started.");
document.getElementById("register").reset();
document.getElementById("Bshift").disabled = true;
document.getElementById("StartingB").disabled = true;
}).fail(function(error){
alert("Data error");
});
}
});
Everytime i put the ContentType the script goes to done but if I take it off then my sql on my php executes and gives me a responce
Php code shiftSave.php
<?php
include "connection.php";
session_start();
$data=array();
$location="";
if (isset($_SESSION['location'])) {
$location=$_SESSION['location'];
}
if (isset($_SESSION['eId'])) {
$empId=$_SESSION['eId'];
}
if(#$_POST['pLocal']) {
$proQty = $_POST['pLocal'];
$proid = $_POST['proId'];
try {
$sql = "UPDATE location_product SET productQty='".$proQty."' WHERE productId='".$proid."' and productLocation='".$location."'";
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
echo "Record updated successfully!";
//$data["secion"]=$stmt. " this ";
if ( !$stmt) {
$data["match"]=false;
} else {
//echo "Error updating record: " . $conn->error;
echo "Record updated successfully!";
$data["match"]=true;
}
echo json_encode($data);
} catch (Exception $e) {
$data["match"]=false;
echo json_encode($data);
}
}
if (#$_POST['pettyCash']) {
$pettyCashIn=$_POST['pettyCash'];
$comment= $_POST['comment'];
try {
$sql = "INSERT INTO `customer_service_experts`.`shift` ( `empId`, `pettyCashIn`, `note`) VALUES ( '$empId', '$pettyCashIn', '$comment')";
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
if ( !$stmt) {
$data["match"]=false;
} else {
echo "Record updated successfully!";
$data["match"]=true;
}
echo json_encode($data);
} catch (Exception $e) {
$data["match"]=false;
echo json_encode($data);
}
}
?>
when i execute without the contentType it goes true but it fails and gives me Data error (the alert that i used on the function fail), but if I use the contentType it goes to the function .done and goes trough but the query does not execute.
You also need to stringify the data you send like so
data: JSON.stringify(prodData1),
You could make a helper function which you can use everywhere you want to do a JSON POST
function jsonPost(url, data, success, fail) {
return $.ajax({
url: url,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
success: success,
error: fail
});
}
Does ajax need contentType to send to php ?
And you have a contentType: "application/json; charset=utf-8", which sends data in request payload but if you omit it/remove it from ajax then by default contentType for jquery ajax is application/x-www-form-urlencoded; charset=UTF-8.
Lets see both of them here:
A request with Content-Type: application/json may look like this:
POST /some-path HTTP/1.1
Content-Type: application/json
{ "foo" : "bar", "name" : "John" }
And if you submit a HTML-Form with method="POST" and Content-Type: application/x-www-form-urlencoded (It is default for jquery ajax) or Content-Type: multipart/form-data your request may look like this:
POST /some-path HTTP/1.1
Content-Type: application/x-www-form-urlencoded
foo=bar&name=John
So if you send the data in request payload which can be sent via Content-Type: application/json you just can't take those posted values with php supergloabals like $_POST.
You need to fetch it yourself in raw format with file_get_contents('php://input').
Firstly remove the content-type option. Let jQuery use the default.
Second,
change:
var pLocal= document.getElementById(productId).value;
var prodData = 'pLocal=' + pLocal+ '&proId='+productId;
to:
var pLocal= document.getElementById(productId).value;
var prodData = { pLocal: pLocal, proId: productId };
and:
var pettyCash= document.getElementById("pettyCash").value;
var comment= document.getElementById("comment").value;
var prodData1 = 'pettyCash=' + pettyCash+ '&comment='+comment;
to:
var pettyCash= document.getElementById("pettyCash").value;
var comment= document.getElementById("comment").value;
var prodData1 = { pettyCash: pettyCash, comment: comment };

Categories