Why can't I access the data in my JSON? - javascript

My PHP is:
if(!empty($_POST)&&($_POST['action']=='edit'))
{
foreach ($_POST['selected'] as $edit_id)
{
$query = "SELECT * FROM grocery WHERE id = $edit_id";
$result = dbQuery($query);
break;
}
$rowArr=array();
$inRow = mysqli_fetch_array($result);
$id = $inRow['id'];
$shop = $inRow['shop'];
$category = $inRow['category'];
$item = $inRow['item'];
$qnty = $inRow['quantity'];
$unit = $inRow['unit'];
$price_based_on = $inRow['price_based_on'];
$mrp = $inRow['MRP'];
$sellers_price = $inRow['sellers_price'];
$last_updated_on = $inRow['last_updated_on'];
array_push($rowArr, array('id' => $id, 'shop' => $shop, 'category' =>$category, 'item' => $item, 'qnty' => $qnty, 'unit' => $unit, 'price_based_on' => $price_based_on, 'mrp' => $mrp, 'sellers_price' => $sellers_price, 'last_updated_on' => $last_updated_on));
echo json_encode(array('rowArr' => $rowArr));
}
The output (JSON) produced by the above script is: (I've ensured this is produced in the Chrome's console)
{
"rowArr": [
{
"id": "30",
"shop": "Subhash",
"category": "Spices",
"item": "Duta Corriander Powder",
"qnty": "50",
"unit": "gm",
"price_based_on": "Packet",
"mrp": "15.00",
"sellers_price": "12.00",
"last_updated_on": "2016-12-03"
}
]
}
My jQuery is:
$('#edit').click(function(){
var data = $("#list :input").serialize();
$.post($("#list").attr('action'), data, function(json)
{
if(json.rowArr.length>0)
console.log("Data Exists");
else
console.log("Empty");
currentRow = json.rowArr[0];
console.log(json.rowArr[0].id);
$("#id").val(currentRow.id);
$("#id_disp").val(currentRow.id);
});
});
Strangely enough, neither Data Exists or Empty is produced by the above loop. And when I try to access the JSON data, json.rowArr[0].id I get the following error:
Uncaught TypeError: Cannot read property 'length' of undefined
Why is this happening? How do I fix it?

You should explicitly tell jQuery that your response has JSON format. You should pass 'json' as fourth argument of $.post, according to docs.
$('#edit').click(function(){
var data = $("#list :input").serialize();
$.post($("#list").attr('action'), data, function(json) {
if(json.rowArr.length>0)
console.log("Data Exists");
else
console.log("Empty");
currentRow = json.rowArr[0];
console.log(json.rowArr[0].id);
$("#id").val(currentRow.id);
$("#id_disp").val(currentRow.id);
}, 'json');
});

Related

Javascript/PHP - Reordering JSON array randomly causes null value and deletes everything

I have a random issue while trying to reorder items in a JSON array via JS/PHP, this occurs when the array has more than 1000 items.
Example of my Users.json file:
[
{
"ID_id": "123abc",
"ST_username": "johndoe",
"ST_email": "j#example.com",
"ST_fullname": "John Doe",
},
{
"ID_id": "def345",
"ST_username": "sarahdoe",
"ST_email": "s#example.com",
"ST_fullname": "Sarah Doe",
},
{
"ID_id": "fgh567g",
"ST_username": "markdoe",
"ST_email": "mark#example.com",
"ST_fullname": "Mark Doe",
}
// + additional 1000 similar items in this array
]
So, first of all, I get the JSON file's data and decode it into a PHP array:
$tableName = $_GET['tableName']; // Lets' say $tableName is 'Users'
// fetch data from 'Users.json'
$data = file_get_contents($tableName. '.json');
$data_array = json_decode($data, true);
Then I call this function in JS:
function reorderTableData() {
var newOrderArray = [];
var data_arrayStr = JSON.stringify(<?php echo json_encode($data_array) ?>);
var jsonData = JSON.parse(data_arrayStr);
var reorderedData = JSON.stringify(jsonData, newOrderArray);
$.ajax({
url : "reorder-table-data.php",
type: 'POST',
data: 'tableName='+'<?php echo $tableName ?>'+'&reorderedData='+encodeURIComponent(reorderedData),
success: function(data) {
location.reload();
// error
}, error: function(e) {
}});
}
}
My reorder-table-data.php code:
$tableName = $_POST['tableName'];
$reorderedData = $_POST['reorderedData'];
$data_array = json_decode($reorderedData, true);
// Encode back to JSON
$data = json_encode(array_values($data_array), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
file_put_contents($tableName. '.json', $data);
// echo JSON object
echo json_encode($data);
?>
Sometimes this code erases everything and all you see is null in the Users.json file, all data got lost.
What am I doing wrong?

How to get Facebook Share Count and Comment Count on Version 2.7

What is my Issued?
Im not getting result/output, using my php code?(first issued)
How to input my Access Token on my php code? (Second Issued)
When i enter this URL from browser: https://graph.facebook.com/v2.1/?id=http://google.com
Im getting result JSON:
{
"share": {
"comment_count": 0,
"share_count": 44100483
},
"og_object": {
"id": "1485280808235339",
"description": "Honoring our veterans #GoogleDoodle",
"title": "Google",
"type": "website",
"updated_time": "2017-11-11T21:40:44+0000"
},
"id": "http://google.com"
}
However, When I used my php code I'm not getting any result.
My complete php code below:
public function getFacebookData($domain)
{
try
{
$facebook_app_id = "666987483466439";
$facebook_app_secret = "b3e1a0948513223b0bc51b32a735e2cf";
$access_token = $facebook_app_id . '|' . $facebook_app_secret;
$curl_response = $this->curl->get("http://graph.facebook.com/v2.7/?id=" . $domain . '&fields=share&access_token=' . $access_token); //$curl_response = $this->curl->get("http://graph.facebook.com/v2.1/?id=" . $domain);
$curl_response = $this->curl->get($callback_url . http_build_query($data, '', '&'));
if ($curl_response->headers['Status-Code'] == "200") {
$parse_response = json_decode($curl_response, true);
$fb_share_count = $parse_response['data'][0]['share_count'];
$fb_like_count = $parse_response['data'][0]['like_count'];
$fb_comment_count = $parse_response['data'][0]['comment_count'];
} else {
$fb_share_count = 0;
$fb_like_count = 0;
$fb_comment_count = 0;
}
$response = array(
'status' => 'success',
'data' => array(
'fb_share_count' => filter_var($fb_share_count, FILTER_SANITIZE_NUMBER_INT),
'fb_like_count' => filter_var($fb_like_count, FILTER_SANITIZE_NUMBER_INT),
'fb_comment_count' => filter_var($fb_comment_count, FILTER_SANITIZE_NUMBER_INT)
)
);
}
catch (Exception $e)
{
$response = array(
'status' => 'error',
'msg' => $e->getMessage()
);
}
return $response;
}
Is there any problem with my code or something i missed?Thanks in advance for your help guys!
From Facebook Developer Site Doc: I need to input an Access Token on my code: Application ID|App Secret another Issue. The Application ID|App Secret i input here is working and tested.
How to input my token on my php code?
I found a solution, but not in php ruther is js
Here is the working Code:
$(function() {
var url = "http://facebook.com";
var apiUrl = "https://graph.facebook.com/?ids=" + url;
$.ajax({
url: apiUrl,
success: function(result) {
$.each(result, function(key, val) {
console.log(key + " - " + val["share"]["share_count"]);
console.log(key + " - " + val["share"]["comment_count"]);
var commentCount = val["share"]["comment_count"];
var shareCount = val["share"]["share_count"];
$("#fb-like-div").html(shareCount);
$("#fb-comment-div").html(commentCount);
});
}
});
});
#fb-like-div,#fb-comment-div{color:red;}
<script type="text/javascript" src="//code.jquery.com/jquery-1.12.4.js"></script>
<div id="fb-like-div">0</div>
<div id="fb-comment-div">0</div>

How to add an AJAX action - Elgg

I'm trying to create an AJAX action in elgg. I have followed this Elgg tutorial: Ajax: Performing actions, but I'm getting nothing so far, apart from the fail error:
Sorry, Ajax only!
The other error is that the page reloads, instead of persisting the data asynchronously.
What am I getting wrong? Thank you all in advance.
Below is my code:
form: views/default/forms/service_comments/add.php
<?php
$url_confirm = elgg_add_action_tokens_to_url("action/service_comments/add?guid={$guid}");
$params_confirm = array(
'href' => $url_confirm,
'text' => elgg_view_icon('upload'),
'is_action' => true,
'is_trusted' => true,
'class' => 'upload-media-update',
);
$confirm = elgg_view('output/url', $params_confirm);
?>
<div class="update-options">
<?= $confirm ?>
</div>
start.php
elgg_register_action("service_comments/add", __DIR__ . "/actions/service_comments/add.php");
action file: actions/service_comments/add.php
<?php
elgg_ajax_gatekeeper();
$arg1 = (int)get_input('arg1');
$arg2 = (int)get_input('arg2');
// will be rendered client-side
system_message('We did it!');
echo json_encode([
'sum' => $arg1 + $arg2,
'product' => $arg1 * $arg2,
]);
Javascript : views/js/service_comments/add.js
var Ajax = require('elgg/Ajax');
var ajax = new Ajax();
ajax.action('service_comments/add', {
data: {
arg1: 1,
arg2: 2
},
}).done(function (output, statusText, jqXHR) {
if (jqXHR.AjaxData.status == -1) {
return;
}
alert(output.sum);
alert(output.product);
});
You have written ajax procedure but not invoking it. Instead you are directly calling it . by making it link.
$params_confirm = array(
'href' => '#',
'text' => elgg_view_icon('upload'),
'onclick' => "myajax_function()",
'class' => 'upload-media-update',
);
$confirm = elgg_view('output/url', $params_confirm);
Then move your JS code inside a function.
function myajax_function(){
var Ajax = require('elgg/Ajax');
var ajax = new Ajax();
ajax.action('service_comments/add', {
data: {
arg1: 1,
arg2: 2
},
}).done(function (output, statusText, jqXHR) {
if (jqXHR.AjaxData.status == -1) {
return;
}
alert(output.sum);
alert(output.product);
});
}

Autocompleting a form in PHP/Javascript

I have been trying to make an autocomplete script for the whole day but I can't seem to figure it out.
<form method="POST">
<input type="number" id="firstfield">
<input type="text" id="text_first">
<input type="text" id="text_sec">
<input type="text" id="text_third">
</form>
This is my html.
what I am trying to do is to use ajax to autocomplete the first field
like this:
and when there are 9 numbers in the first input it fills the other inputs as well with the correct linked data
the script on the ajax.php sends a mysqli_query to the server and asks for all the
data(table: fields || rows: number, first, sec, third)
https://github.com/ivaynberg/select2
PHP Integration Example:
<?php
/* add your db connector in bootstrap.php */
require 'bootstrap.php';
/*
$('#categories').select2({
placeholder: 'Search for a category',
ajax: {
url: "/ajax/select2_sample.php",
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
term: term, //search term
page_limit: 10 // page size
};
},
results: function (data, page) {
return { results: data.results };
}
},
initSelection: function(element, callback) {
return $.getJSON("/ajax/select2_sample.php?id=" + (element.val()), null, function(data) {
return callback(data);
});
}
});
*/
$row = array();
$return_arr = array();
$row_array = array();
if((isset($_GET['term']) && strlen($_GET['term']) > 0) || (isset($_GET['id']) && is_numeric($_GET['id'])))
{
if(isset($_GET['term']))
{
$getVar = $db->real_escape_string($_GET['term']);
$whereClause = " label LIKE '%" . $getVar ."%' ";
}
elseif(isset($_GET['id']))
{
$whereClause = " categoryId = $getVar ";
}
/* limit with page_limit get */
$limit = intval($_GET['page_limit']);
$sql = "SELECT id, text FROM mytable WHERE $whereClause ORDER BY text LIMIT $limit";
/** #var $result MySQLi_result */
$result = $db->query($sql);
if($result->num_rows > 0)
{
while($row = $result->fetch_array())
{
$row_array['id'] = $row['id'];
$row_array['text'] = utf8_encode($row['text']);
array_push($return_arr,$row_array);
}
}
}
else
{
$row_array['id'] = 0;
$row_array['text'] = utf8_encode('Start Typing....');
array_push($return_arr,$row_array);
}
$ret = array();
/* this is the return for a single result needed by select2 for initSelection */
if(isset($_GET['id']))
{
$ret = $row_array;
}
/* this is the return for a multiple results needed by select2
* Your results in select2 options needs to be data.result
*/
else
{
$ret['results'] = $return_arr;
}
echo json_encode($ret);
$db->close();
Legacy Version:
In my example i'm using an old Yii project, but you can easily edit it to your demands.
The request encodes in JSON. (You don't need yii for this tho)
public function actionSearchUser($query) {
$this->check();
if ($query === '' || strlen($query) < 3) {
echo CJSON::encode(array('id' => -1));
} else {
$users = User::model()->findAll(array('order' => 'userID',
'condition' => 'username LIKE :username',
'limit' => '5',
'params' => array(':username' => $query . '%')
));
$data = array();
foreach ($users as $user) {
$data[] = array(
'id' => $user->userID,
'text' => $user->username,
);
}
echo CJSON::encode($data);
}
Yii::app()->end();
}
Using this in the View:
$this->widget('ext.ESelect2.ESelect2', array(
'name' => 'userID',
'options' => array(
'minimumInputLength' => '3',
'width' => '348px',
'placeholder' => 'Select Person',
'ajax' => array(
'url' => Yii::app()->controller->createUrl('API/searchUser'),
'dataType' => 'json',
'data' => 'js:function(term, page) { return {q: term }; }',
'results' => 'js:function(data) { return {results: data}; }',
),
),
));
The following Script is taken from the official documentation, may be easier to adopt to:
$("#e6").select2({
placeholder: {title: "Search for a movie", id: ""},
minimumInputLength: 1,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json",
dataType: 'jsonp',
data: function (term, page) {
return {
q: term, // search term
page_limit: 10,
apikey: "ju6z9mjyajq2djue3gbvv26t" // please do not use so this example keeps working
};
},
results: function (data, page) { // parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter remote JSON data
return {results: data.movies};
}
},
formatResult: movieFormatResult, // omitted for brevity, see the source of this page
formatSelection: movieFormatSelection // omitted for brevity, see the source of this page
});
This may be found here: http://ivaynberg.github.io/select2/select-2.1.html
You can optain a copy of select2 on the github repository above.

JSON can't be parsed using Javascript

I have the following JSON reply from a PHP file:
[
{
"color": "black",
"product_name": "Prod2",
"revision": "apps/"
},
{
"color": "green",
"product_name": "Prod1",
"revision": "dev/"
}
]
(tested OK on JSONLint)
And Javascript:
$(document).ready(function(){
$('.target').keyup(function() {
var package_name = "name";
var package_version = "version";
var filter_results = "filter";
$.post('includes/package_filter.php', { package_name: package_name, package_version: package_version, filter_results: filter_results }, function(return_result) {
obj = JSON.parse(return_result);
alert(obj.product_name);
var existingDiv = document.getElementById('other');
existingDiv.innerHTML = CreateTable(return_result);
});
});
});
The return_result doesn't seem to be correct since I get Error: SyntaxError: JSON.parse: unexpected end of data when doing the JSON.parse
I also don't go further to the alrt...
What could be wrong?
My PHP file is similar to:
<?php
function package_filter($package_name, $package_version, $filter_results){
foreach ($descriptions as $descriptions_display) {
...
$array_to_return[] = array('color' => $color , 'product_name' => $descriptions_display['product_name'] , 'revision' => $descriptions_display['revision']);
}
return json_encode($array_to_return);
}
?>
My goal is to create a table with my CreateTable function but there is something wrong before.
When dealing with JSON just set fourth parameter in post() method to json:
$.post('includes/package_filter.php', { /* params */ }, function(return_result) {
// return_result[0].product_name;
}, 'json');
Check the encoding of the response UTF-8 ASCII you may have Characters that are messing up with the parser.

Categories

Resources