ajax, variable not defined? - javascript

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);
}
});

Related

access json fields in 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

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));
?>

Jquery ,PHP Post Json data to an external url

I have the following jquery function which is supposed to post data to a php function which in the process it passes it to the external script for processing.
Below is my jquery function :
function order_confirmation(json) {
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>home/confirm_order_received/",
data: json,
contentType: 'application/json',
dataType: 'json',
success: function (data) {
console.log(data);
},
failure: function (errMsg) {
console.log(errMsg);
}
});
}
This function is supposed to pass the json data to my php function which is below here :
function confirm_order_received() {
$json = $this->input->post('json');
// Initialize curl
$curl = curl_init();
$externalscriptaddress = "http://197.237.132.178/api/order/order_upsert";
// Configure curl options
$opts = array(
CURLOPT_URL => $externalscriptaddress,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $json
);
// Set curl options
curl_setopt_array($curl, $opts);
// Get the results
$result = curl_exec($curl);
// Close resource
curl_close($curl);
echo $result;
}
I have a problem of how I am supposed to access the data from the php side, I have tried accessing it through the post : $json = $this->input->post('json'); and passed it to the CURLOPT_POSTFIELDS => $json but I get an error since nothing has been passed. Please advise how can i pass the json data to an external script?
For getting raw post data (in your case) use file_get_contents("php://input")
Instead of data: json, you should use data: "json:json",
Using just data: json, will post the data, but it will not be assigned to a key. To access the data ou need to assign it to a key. By using data: "json:json",, you can access it with $json = $this->input->post('json');

AJAX jquery json sending array to php

I'm trying to send a associative array via AJAX $.post to php. Here's my code:
var request = {
action: "add",
requestor: req_id,
...
}
var reqDetails = $("#request_details").val();
switch(reqDetails){
case 1:
request[note] = $("#note").val();
break;
...
}
if(oldRequest()){
request[previousID] = $("old_id").val();
}
$('#req_button').toggleClass('active');
$.post("scripts/add_request.php", {
request_arr: JSON.stringify(request)
}, function(data){
console.log(data);
$('#req_button').toggleClass('active');
}, 'json');
And i'm simply trying to read the received data in my php script:
echo json_decode($_POST["request_arr"]);
But it's not working. I'm a newbie to js, I can't figure out what I'm doing wrong.
Check below link for your reference
Sending an array to php from JavaScript/jQuery
Step 1
$.ajax({
type: "POST",
url: "parse_array.php",
data:{ array : JSON.stringify(array) },
dataType: "json",
success: function(data) {
alert(data.reply);
}
});
Step 2
You php file looks like this:
<?php
$array = json_decode($_POST['array']);
print_r($array); //for debugging purposes only
$response = array();
if(isset($array[$blah]))
$response['reply']="Success";
else
$response['reply']="Failure";
echo json_encode($response);
Step 3
The success function
success: function(data) {
console.log(data.reply);
alert(data.reply);
}
You are already using "json" as dataType, so you shouldn't apply 'stringify' operation on your data.
Instead of request_arr: JSON.stringify(request), can you try request_arr: request directly?

Send array with ajax request to php

I created array like this ["9", "ques_5", "19", "ques_4"]. Now I want to send it from JS to PHP but I'm not getting proper results. My JS code is:
$(".button").click(function(e) {
e.preventDefault();
$.ajax({
type : 'post',
cache : false,
url : 'test/result.php',
data : {result : stuff},
success: function(resp) {
alert(resp);
}
});
});
In the above code stuff is an array which contains records. How can I send this array with above code and then in PHP I want to process this array like ques_5 is the key and 9 become the value for that key.
You can pass the data to the PHP script as a JSON object. Assume your JSON object is like:
var stuff ={'key1':'value1','key2':'value2'};
You can pass this object to the php code in two ways:
1. Pass the object as a string:
AJAX call:
$.ajax({
type : 'POST',
url : 'result.php',
data : {result:JSON.stringify(stuff)},
success : function(response) {
alert(response);
}
});
You can handle the data passed to the result.php as :
$data = $_POST["result"];
$data = json_decode("$data", true);
//just echo an item in the array
echo "key1 : ".$data["key1"];
2. Pass the object directly:
AJAX call:
$.ajax({
type : 'POST',
url : 'result.php',
data : stuff,
success : function(response) {
alert(response);
}
});
Handle the data directly in result.php from $_POST array as :
//just echo an item in the array
echo "key1 : ".$_POST["key1"];
Here I suggest the second method. But you should try both :-)
If you want to send key value pairs, which is what I am seeing, it would be better to use a PHP JSON library (like this one... http://php.net/manual/en/book.json.php)
Then you can send actual key value pairs, using JSON format like...
{"ques_5" : "19", "ques_4": "19"}
Try this
var array = ["9", "ques_5", "19", "ques_4"];
console.log(array.join(","));
above code will output string with comma separated like 9,ques_5,19,ques_4then paste it to ajax call.
And then in php explode that string.
Other possible solutions.
First
var obj = { 'item1': 'value1', 'item2': 'value2' };
$.ajax(
{
type: 'post',
cache: false ,
url: 'test/result.php',
data: { result : JSON.stringify(obj) },
success: function(resp)
{
alert(resp);
}
});
Second
var a = $.JSON.encode(obj);
$.ajax(
{
type: 'post',
cache: false ,
url: 'test/result.php',
data: { result : a },
success: function(resp)
{
alert(resp);
}
});
In PHP File
<?php
$json = $_POST["data"]
var_dump(json_decode($json));
?>
You can send the array in json format to the php and then use json_decode function to get back the array like
In ajax call you have to send json for that you need to first make array of the values so that you get it in right form
so that you json look like {"ques_5":"9","ques_4":19}
and use in ajax call
data: JSON.stringify(`your created json`),
contentType: "application/json; charset=utf-8",
dataType: "json",
IN PHP it look like
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
?>
I would like to share a complete example that works for me in order to avoid making each JavaScript function for each PHP function
// on the HTML side a simple JavaScript call from a link
<a href="javascript:CargaZona('democonllamada', 'tituloprin', {'key1':'value1','key2':'value2'})" >test</a>
<div id='tituloprin' >php function response here!</div>
// on JavaScript side
function CargaZona(fc, div, params) {
var destino = "#" + div;
var request = $.ajax({
url : "inc/phpfunc.php",
type : "POST",
data : {
fc : fc,
params : JSON.stringify(params)
},
dataType : "html"
});
request.done(function (msg) {
$(destino).html(msg);
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
}
// on phpfunc.php page
<?php
$params = "{'key1':'value1','key2':'value2'}";
$fc = 'def';
if (isset($_POST['fc'])) { $fc = $_POST['fc']; }
if (isset($_POST['params'])) { $params = $_POST['params']; }
switch ($fc) {
default:
call_user_func($fc,$params);
}
function democonllamada($params) {
$params = json_decode("$params", true);
echo "ok llegaron".$params['key1'];
}
?>

Categories