Strange behaviour sending data with PHP JSON encode to jQuery getJSON - javascript

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.

Related

Passing php array to javascript then accessing values by key

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'])
}

JSON unable to accept json_encode() arrays

I am sending a simple array from my PHP file,
//example.php
if(0){
return json_encode(['status'=>false, 'message'=>'Please enter a username']);
}
and in my ajax.js I have everything working, including the XHR object, and event handlers. All is find, except this line.
// ...
var x = JSON.parse(xmlhttp.responseText);
console.log(x);
// ...
But, I am getting the following error.
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
I don't understand this. All the code is correct. Before using JSON, I used to pass from values from PHP using echo 'ok' and just do if(xmlhttp.responseText) == 'ok and it worked fine, but not with json
Two problems:
you use return which does not print anything to the output wheras echo actually prints text. Try using:
if(0) will always fail, so you will never print anything. You should use if(1) as trivial test. It is possible that you're PHP code can fail, but in that case you better also return an JSON formatted error message.
Something like:
if(test) { //test means you can do the action
//do action
echo json_encode(['return' => 'ok','result' => 'foobar']);
} else {
echo json_encode(['return' => 'error']);
}

Jquery Post Empty Even though Sent Variable has data

The console.log on the first line returns a large array of values. And the Console.log(Data) at the end is displaying the plain text response from the server, but the $_POST variable on the server is empty.
The JS:
console.log(topost);
$.post(url,topost,function ( data ){
console.log(data);
});
The console.log(topost);
["DiscontentDisciple","illuminatedwax","S2S2S2S2S2","bechus","syncretic","davidreiss666","Skuld","soupyhands","AutoModerator","imluckytometyou","Lord_Arioc","IIdsandsII","Kylnas","alanpugh","langis_on","TheBigDickedBandit","long_wang_big_balls","arnoldlol","SBringer","ExoticCarMan","HaidiMontag","10FootPenis","SupriseRape","AManHasSpoken","ComedicCounterpart","Suddenly_Something","agenthex","GenerallySpecific","WelcomeToTarget","brainswho","Gooflactus","alcakd","Stingray88","TossTime","yolfer","biskits1","Evarg","phishroom","BuccoBruce","LookingForAlaska","getDense","lewisthemusician","tmotom","tha_ape","spankymuffin","Dashing_Pony","RuafaolGaiscioch","BeaverManiac","Careless_Con","Texas_","i_am_sad","The_helpful_idiot","Kon-chezz","bombdailer","frezik","Galifreyan2012","metalshadow","lightpollutionguy","b3mus3d","crazdave","merpes","naked_guy_says","GoodGuyAnusDestroyer","Bibliophobia","Internet_Lynch_Mob","photo","adkoe","ZeitTaicho","movie_man","iamkush","sired_tick","jyjjy","WhipIash","rred82","E_Diddyyy","CYBERPENISATTACK","MJYTR","TheBaconHasLanded","quarktheduck","heroic_trig","sleevieb","Burrow","myhousemateisabitch","promethephile","msm008","daskrip","jonnie123","Legendman3","Makes_Sad_Faces","anxiousalpaca","crankykong","IamDa5id","CocoSavege","iamsofuckedseriously","EvTheSmev","Briscotti","MarkieMarkl","CornishCucumber","BearsStillSuck","government_shill","Ihaveafatcat","gh5046","Sayum","henryponco","bolaxao","mrbriancomputer","PsychicNinja_","poopslooshed","REDDIT-","IVI4tt","spleendor","ngmcs8203","deadbeatbum","vegibowl","workingalot","Black_Apalachi","Incongruity7","rdeari1","ihahp","im_0n_toilet","Andynack","photokeith","Alpha17x","5NL70","AtticusFinch1962","clayvn","anonymau5","coplay","gnarbucketz","BukkRogerrs","teusz16","digital_evolution","theredcheck","empw","OrigamiRock","lumptoast","alphanovember","Nahtanos","som13","rstyknf","jmadden287","patchworkpavements","Computer-Blue","Miltage","bwaxxlo","aussiegolfer","coaltown","ThePickleMan","mpm96","Ilyanep","merreborn","Theemuts","wufoo2","thunderbar","blindado9","ntorotn","CatrickSwayze","HankSinatra","redditbots","Word_Inventor","catbeef","SoLongSidekick","Elefaze","Jinksywinksy","Mordy2011","thatusernameisal","Kanin","inthekeyofbflat","buckygrad","DeaD_bAU5","Toe_Fat","wsright987","Pachi2Sexy","woprdotmil","AmmoBradley","pokelord13","kroutonz","mattoftheD","WipeMyAssWith100s","ShuckBeam","dookyface","XLR8Sam","your_backpack"]
The response I get:
{"postyn":"YES"}
The PHP:
foreach ($_POST as $key => $value){
$data[$key] = $value;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$data['postyn'] = 'YES';
}
I don't understand why the $_POST variable is empty?
$.post(url,{**NAMEME**: topost} ,function ( data ){
console.log(data);
});
You're trying to pass post data as an array it appears. It needs to either be a string or an object.
Description of data property for jQuery.post():
data A map or string that is sent to the server with the request.
From http://api.jquery.com/jQuery.post/
My guess here based on what you're trying to do is an object. Which brings up the next problem, both an object and your PHP script are expecting both keys and values, but you're only passing values.
You data object should look something like:
topost = {
somekey1: "DiscontentDisciple",
somekey2: "illuminatedwax",
somekey3: "S2S2S2S2S2",
// etc etc etc
};

jQuery Fails To Read JSON Response From PHP Script

In my form, I want to do something with two fields:
"website_domain" and "website_ip_address"
I'm trying to use jQuery/JSON to call a PHP script, pass the website_domain to it, and receive JSON including the IP address of that website.
Problem/Symptoms Description:
It's partially working: On blur, it GETs the url of the PHP script. I can see that much in firebug. I get a 200 OK. Output from the PHP script is valid JSON according to JSONLint:
{"field":"website_ip_address","value":"74.125.225.70"}
But in Firebug, I don't have a JSON tab. I only have Params and Headers tabs. Not even a Response tab.
Needless to say, the website_ip_address field is also not being populated with the data I should be getting from the PHP script's JSON output.
My PHP Script:
It may be important to note that for now, this PHP script on a different domain from my application. Maybe my whole problem is cross-domain?
<?php
$domain = $_GET["domain_name"];
$ip = gethostbyname($domain);
// echo $ip;
$json = array(
'field' => 'website_ip_address',
'value' => $ip,
);
header('Content-Type: text/plain');
echo json_encode($json );
?>
My jQuery/JSON script:
Note this is written inside a Ruby On Rails application view.
:javascript
$("#website_domain").bind("blur", function(e){
$.getJSON("http://exampledomain.com/temp_getIP.php?domain_name=" +$("#website_domain").val(),
function(data){
$('#website_ip_address').val(data);
});
});
I really hope this isn't just a syntax error on my part. I've been writing/rewriting this for 2 days, based on answers I've found on StackOverflow, to no avail. I'm just missing something here.
You are currently attempting to output the JS object (that is formed from the parsed JSON response) to the field. You need to output a value from within it. So not:
$('#website_ip_address').val(data); //data is an object, not a string
but
$('#website_ip_address').val(data.someValue); //output a property of the object
With your code as it is, I would expect the field to be populated with the string representation of an object, which is [object Object]. You don't mention this, so I wonder whether a) your success function is even firing (check this - stick a console.log in it); b) your jQ selector is sound.
The problem can be with different domain. I had it like this before. Try in php to add header("Access-Control-Allow-Origin: *")
Put your jQuery code inside document ready, example: $(function(){ });
:javascript
$(function() {
$("#website_domain").bind("blur", function(e){
$.getJSON("http://exampledomain.com/temp_getIP.php?domain_name="+$("#website_domain").val(),
function(data){
$('#website_ip_address').val(data);
});
});
});
});
And you have a missing end })

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