Passing php array to javascript then accessing values by key - javascript

I'm using $.post to return an array from a separate php file, and trying to access the values of the array in javascript by the keys, but am having trouble doing so.
Here's the post code:
$(document).ready(function(){
var limRefresh = setInterval(refreshLIM, 10000);
var dbAction = "feedRefresh";
var newestRow = <?php echo $newestRow ?>;
$.post("jsDb.php",{ action: dbAction,lastRow: newestRow },function(status){
console.log(status);
console.log(newArr['status']);
console.log(newArr.status);
console.log(newArr[0]);
});
});
Here's the excerpt of how the response is being formatted in the external php file:
echo json_encode(array("status" => "success","actId" => $newActId));
And here's the respective console logs (just trying different options):
{"status":"success","actId":"585924418"}
undefined
undefined
{
Any ideas where I'm going wrong?

The response you get as status from $.post is a string. You need to parse it order to use it as you intend. Moreover, newArr is undefined because you have not defined it anywhere. This is probably because you have reused someone else's code and missed this part:
newArr = JSON.parse(status)

The response is coming as string, so you need to parse it before you can access it as JSON:
$.post("jsDb.php",{ action: dbAction,lastRow: newestRow },function(status){
var data = JSON.parse(status);
console.log(data['status'])
console.log(data['actId'])
}

Related

JSON stringify converting complete array element to key of an array in PHP

I am trying to attach sendBeacon method to one of the page in my web application. I tried to send request using a simple AJAX method and via sendBeacon() method. Both are giving different results and none is usable. Please suggest.
html.php
<body>
<button onclick="setzero();">
click me
</button>
<script>
function setzero(){
var settings = {
"url":"ttstt.php",
"method":"POST",
"data": JSON.stringify({"val":0})
};
$.ajax(settings).done(function(e){console.log(e);});
}
window.addEventListener("unload", function() {
navigator.sendBeacon("ttstt.php", JSON.stringify({"val":1}));
});
</script>
</body>
ttstt.php
$val = ($_POST);
print_r($val);
When I click the button on html.php I get the following result.
!! Please note that the complete array is in the key portion. !!
Array
(
[{"val":0}] =>
)
When I reload the page to initiate the sendBeacon(), I get [] as a result.
I just changed the following in my PHP code
$val = file_get_contents("php://input");
$json = json_decode($val);
echo $json['val']; //This gives output as 0, which I was looking for.
Also same code works with sendBeacon() data also.

Communicate php and js

I'm trying to create a js that send data to a php.
My first problem is that I get get back a html code if I insert this to the php.
This is only for understand the idea. So the js should send the "param" to the php and the php should return the result6 variable in this case, but I get a html code...
$('#f_field').change (function()
{
var param = 28;
$.post('check_mutet.php', param, function(result6) {
alert(result6);
});
});
while check_mutet.php contains this
<?php
$result6=666;
echo $result6;
Thank you for your help, as you can see I'm rather noob :)
param is a plain string (it starts out as a number, but will be converted to a string by the time it gets through to HTTP).
This will be available as STDIN in PHP, which you can read as described in answers to this question.
However, you should encode the data into a structured format that is easier to use.
The traditional format for this is application/x-www-form-urlencoded, which is the default format sent by HTML forms.
If you pass an object to jQuery post, it will encode the data in that format for you:
var param = 28;
var data = { example: param };
$.post('check_mutet.php', data, function(result6) {
Then you can read it through the POST superglobal in PHP:
<?php
$result = $_POST['example'];

JSON.parse reads "{\"number\":\"7\"}

Hi I have troubles to generate JSON with json_encode() PHP function.
I have a .php file that is doing only following:
<?php
// include_once for a few files here
$address = MyModelClass::getByAtrrId(52);
echo json_encode($address, JSON_HEX_QUOT | JSON_HEX_APOS) ;
result is following:
{"number":"7"}
Then there is jQuery in another file, retrieving this by following code:
$(document).ready(function e() {
let file_path = 'myJson.php';
let json = $.getJSON(file_path);
console.log(json);
let json_obj = JSON.parse(json);
However $.getJSON reads this string as "{\"number\":\"7\"}, therefore JSON.parse ends with following error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
I'm sorry, I'm almost 100% sure this is beginner's mistake, however I have failed with my search for correct answer. Anyone having idea what might be the problem?
I have found plenty of articles taking into account input into jason_encode, but right now I have more feeling real trouble is in fact input to jQuery function, however I'm still unable to resolve.
If your web server sends JSON, it's good practice to set the Content-Type accordingly:
header("Content-Type: application/json; charset=utf-8");
On the client, you need to do:
$(document).ready(function() {
$.getJSON('myJson.php', function(response) {
// the response is already parsed by jQuery
alert(response.number);
});
}
$.getJSON() is asynchronous, so you need to pass a handler function to process the response.

Strange behaviour sending data with PHP JSON encode to jQuery getJSON

I am sending data from PHP to jQuery. Everything works fine except I want to sent the total rows from the DB.
I have stripped a lot of other things to put onlu the essential problem.
PHP code:
header('Content-type: text/json');
header('Content-type: application/json');
$rows = array with the data; That is working fine
$total=mysql_num_rows($RSList);
$total_data=array("total"=>$total);
array_push($data,$total_data,$rows);
echo json_encode($data);
jQuery code:
$.getJSON("..url..", function( data ) {
var data_array = eval(data);
$.each(data_array[0], function(i, item ) {
console.log(item)
});
});
The result showing in the browser is:
[{"total":532},[{"product_id":"1",.... }]]
532 is the correct value from the mysql_num_rows()
Console:
An empty string
I tried the following:
If I set the value manually of total in PHP:
$total=100;
The result showing in the browser is:
[{"total":100},[{"product_id":"1",.... }]]
Console of java:
100
If I convert the value in string in PHP:
$total="(".$totalRows_RSList.")";
The result showing in the browser is:
[{"total":"(532)"},[{"product_id":"1",.... }]]
Console:
()
I have also tried intval, number_format and strval with no success.
Very, very strange or ?
Update:
I have modified as suggested the code and still the same problem:
PHP:
echo json_encode(array('total' => $total, 'rows' => $rows));
javscript:
$.getJSON( "..url..", function( data ) {
console.log( data )
$.each( data.rows, function(i, item ) {...}
})
Browser:
{"total":532,"rows":[{"product_id":"567",...}]}
Console:
Object { rows=[99], total=""}
You don't need to pass the total rows, just get the length of the parsed JSON object.
jQuery code:
$.getJSON('...url...', function(data){
console.log(data.length);
}
PHP Code:
header('Content-type: text/json');
header('Content-type: application/json');
$rows = array_with_the_data; //That is working fine
echo json_encode($rows);
Note: This answer explains what is wrong with your code. Learn from it, then look at #ojovirtual's answer which shows what I think is the best way for you to accomplish what you were intending to do in the first place. End Note
Remove the eval statement from your code. jQuery will have already parsed the incoming JSON (if it is valid) and your success function will receive your array as the data param. Just use that data param instead of data_array.
$.getJSON('..url..', function (data) {
// if your PHP is sending proper JSON in the format you describe, `data` is now
// an array containing two items. The first (`data[0]`) is an object which has
// one property, `total`. The second (`data[1]`) is your array of row data, each
// of which is an object.
// your code in modified form, though I don't understand why you would use `each`
$.each(data[0], function (i, item) {
console.log(item);
});
// just use:
console.log(data[0].total);
});
Be sure to read the comments in the above code.

Strange output in JSON that I make in my PHP after an AJAX call

I am a bit new at this and totally messing something up. I have a PHP result set through which I iterate like this:
$rows = array();
while($r = mysql_fetch_assoc($result))
{
$rows[] = $r;
}
echo json_encode($rows);
and then I output it like this in jQuery code:
success: function(json)
{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
// Here can update the right side of the screen with the newly entered information
alert (json);
var ob = $.parseJSON(json);
alert (ob.creator_member_id);
alert (ob.problem_title);
alert (ob.problem_description);
alert (ob.problem_date);
}
But there is an error on the var ob = $.parseJSON(json); line it seems. My JS console gives this error:
Uncaught TypeError: Object function (D,E){return new n.fn.init(D,E)} has no method 'parseJSON'
What can this mean and how can I fix this?
Thanks!!
If you are getting JSON results via jQuery ajax call you don't need parsing resultant json - jQuery does it for you.
Just specify the
dataType: 'json'
[http://api.jquery.com/jQuery.ajax/], and your success handler will have the already parsed object.
If you want parsing JSON anywhay, try adding json2.js to your project. You'll have to call JSON.parse(json) then.
I'm new to Jquery, too. eval is just plain JS and it suits my needs. I don't see any evil with this code but of course it's possible to inject bad code into a response. Probably it's not very good practise. It can be exploited for a reverse shell for example.

Categories