JSON object "undefined" error in Javascript - php

I am uploading a file using PHP and want to return the file name and the file status to javascript. In PHP I create the json object by:
$value = array('result' => $result, 'fileName' => $_FILES['myfile']['name']);
print_r ($value);
$uploadData = json_encode($value);
This creates the json object. I then send it to a function in javascript and recieve it as a variable called fileStatus.
alert (fileStatus);
It displays
{"result":"success","fileName":"cake"}
which should be good. But when I try and do
fileStatus.result or fileStatus.fileName
I get an error saying that they are undefined. Please help I'm really stuck on this. Thanks.

The fileStatus is just a string at this point, so it does not have properties such as result and fileName. You need to parse the string into a JSON object, using a method such as Firefox's native JSON.parse or jQuery's jQuery.parseJSON.
Example:
var fileStatusObj = jQuery.parseJSON(fileStatus);

If the alert displays {"result":"success","fileName":"cake"} then you probably still have to turn the string into a JSON object. Depending on the browsers you are developing for you can use the native JSON support or the JSON.org implementation to turn your string into an object. From there on it should work as expected.

When you are setting the variable, do not put quotes around it. Just set the variable like this:
var fileStatus = <?php echo $uploadData; ?>;
or:
var fileStatus = <?=$uploadData?>;
Do not do this:
var fileStatus = '<?php echo $uploadData; ?>';

Related

request json located in a php file from c#

Could someone tell me how i request json from a php file located on another server that gives it to our asp.net?
It includes ~10 variables we want to use again.
I don't want just a string, but an array.
so this wont work:
//We don't actually use the given url of course
string url = "url";
var json = new WebClient().DownloadString(url);
Response.Write(json);
I'd like to use it somewhere like this jsonname[2]
Output a JSON array from your php page like this
$myArr = array("John", "Mary", "Peter", "Sally");
$myJSON = json_encode($myArr);
header('Content-Type: application/json');
echo $myJSON;
In your c# code you then need to deserialize the string returned by DownloadString into a type that matches the format of the JSON data. If your JSON is just an array of strings, then use JsonConvert.DeserializeObject<List<string>>(json) from the Newtonsoft.Json package. Otherwise you need to replace List with something that matches the Json data, for example a new class with all the same property names and types. In this case
string url = "url";
var json = new WebClient().DownloadString(url);
Response.Write(json);
var myArr = JsonConvert.DeserializeObject<List<string>>(json);
Response.Write(myArr[1]); // will output "Mary"
If you don't have Newtonsoft.Json, this question has some options for obtaining it

Using MYSQL query data with jQuery Autocomplete

I'm trying to query data with MYSQL,
then link it to an <input> with jQuery's Autocomplete.
I'm still not used to using PHP inside Javascript, so I'm not sure how to get contents
inside an array. When every I console.log my PHP for debugging, it says Array.
Here is my JS code:
var SOMETHING = ["<?php echo $SOMETHING; ?>"];
//console.log(SOMETHING);
$( "#input_add_album" ).autocomplete({
source: SOMETHING
});
Here is my PHP code:
global $SOMETHING;
$SOMETHING = array();
$sql = "
select B from A
";
$stmt = $dbh->query($sql);
$result = $stmt->fetchAll();
foreach ($result as $SOME_CONTENT) {
array_push($SOMETHING, $SOME_CONTENT["SOME_CONTENT"]);
}
This question is old but I'm going to go over the 2 most likely solutions. The problem your having is that your trying to echo an Array to see it's contents and that isn't possible. It's also not possible for the JavaScript interpreter to interpret PHP. PHP processes .php files on your host and then serves them to the clients machine. The client end should never see any PHP, it would not know what to do with it. So the end result after the PHP files are run from server, must be a well formatted document to fit the guidelines of a file type the browser can handle, in this case html and JavaScript. So then in order to log the contents of a PHP variable to the console with JavaScript, it must be in a form JavaScript understands. Luckily for you, there is a format that JavaScript understands and most other languages support. The way to move any string, number, array or associative array to JS is with JSON. JavaScript Object Notation. Just remember, that associative arrays in PHP become objects in JavaScript.
$regular_array = json_encode(array( 'words', 'to', 'send' ));
$php_assoc = json_encode(array(
'assoc' => 'arrays',
'become' => 'JavaScript',
'objects' => array(
'this','will','be',1,array()
),
));
echo "
<script>
/** Check that window.console.logs isn't undefined, if we were just
* using JavaScript I wouldn't be so verbose. Since our PHP variable is
* traveling so far from home, I want to make sure we get the right address
*/
if (window && 'console' in window ) {
window.console.log({$regular_array});
window.console.log('JS object with array inside', {$php_assoc});
}
</script>";
That will log the values out to the browsers console. It would be the equivalent of logging the following array and object to the console with regular old JavaScript.
var regularArray = [ 'words', 'to', 'send' ];
var phpAssoc = {
assoc : 'arrays',
become : 'JavaScript',
objects : [ 'this', 'will', 'be', 1, [] ]
};
In Google Chrome, the phpAssoc object looks like this in the console. It can be fully expanded, looked through, and used like any other JavaScript object.
Object {assoc: "arrays", become: "JavaScript", objects: Array[5]}
*In this example I didn't save the PHP output into a JavaScript variable, but you can see how to inject the value into console.log so you can do the same exact thing with echo "var something = {$some_other_thing};";

Get Json From php file

I am new to jQuery. I have got an error when I try to get data from fileresult.php.
fileresult.php
$return_arr = array();
$row_array['status'] = 'Ok';
$row_array['message'] = 'good'
array_push($return_arr, $row_array);
echo json_encode($return_arr);
JSON output
[{"date":"2014-03-15","status":"ok","message":"good"}]
get_result.js
$.post('file.php', $("form").serialize(), function(data) {
var status = data['status'];
alert(status);
});
When I alert data, it shows undefined. Somebody please help me. How can I show the correct data.
You have two problems.
You are outputting "HTML"
PHP defaults to claiming that its output is HTML. jQuery will see this claim and treat it as such instead of parsing it as JSON.
Override PHP's default with:
header("Content-Type: application/json");
You have an array
You are accessing data.status but the top level data structure you are outputting is an array so you need data[0].status with that data.
You don't have multiple objects though, so (unless you plan to add more in the future) it would make more sense to return
{"date":"2014-03-15","status":"ok","message":"good"}
instead of
[{"date":"2014-03-15","status":"ok","message":"good"}]
So remove everything to do with $return_arr and:
echo json_encode($row_array);

How to get a value of a second level JSON node using PHP from a Ajax request?

How can I get a value of a second level JSON node using PHP from a Ajax request?
If I have the next JSON data in client:
var Data = {idJS: "1", dataToSet: "example", another:{ field1: "example2"} };
When the Ajax request is done, in PHP, dataToSet is get as follows: $_POST['dataToSet'], in particular, I use Codeigniter, then I use $this->input->post('dataToSet'). But, How can I get another->field1?
[Solved]:
$postdata = $this->input->post();
$postdata['another']['field1'];
I don't know how you do it with codeigniter, but you have to decode the json. Afterwards you can acces the field. This might look something like this:
$postdata = json_decode($this->input->post);
$postdata['another']['field1];
This should do it:
$data = $this->input->post('another');
print_r($data->field1);
// or you can do it in one line:
$this->input->post('another')->field1;
Try this:
$ata = json_decode($this->input->post('dataToSet'), true);
$field1 = $data['another']['field1'];

Why isn't json_encode working?

I'm trying to encode some user input I'm fetching from a database and then insert it into a textarea on click. Here's my code for encoding the data, sending the user to the textarea anchor, and then triggering my function.
$quote = "[url]" . $quote . "[/url]";
$quote = htmlspecialchars($quote, ENT_QUOTES);
$quote = json_encode($quote, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
echo "
<a href='#quickpost' value='quote'
onClick=\"quote(" . $quote . ")\" name='quote'>Quote</a>
Here's the quote() function:
function quote(originalpost){
oFormObject = document.forms['id1'];
oFormObject.elements['post'].value = originalpost;
};
I'm getting this error in firebug when I click it: SyntaxError: syntax error
Line 1
I'm a complete novice when it comes to JavaScript, so I could be missing something totally obvious.
I've looked and tried a lot of different encoding options and things for this, but I'm not getting anywhere.
Since JSON is native Javascript, you shouldn't quote it when declaring it in JS code or passing it around.
Try:
echo "
<a href='#quickpost' value='quote'
onClick='quote($quote)' name='quote'>Quote</a>";
Then inside your function, you may need to stringify the JSON:
oFormObject.elements['post'].value = JSON.stringify(originalpost);
For sanity's sake, get a copy of the JSON produced by json_encode and run it through the JSON lint utility to make sure it is valid.
See if that works. For browsers that don't have native stringify support, you can get the code for the function here.
Maybe you need to make sure you are sending a string to the quote function. For what I see you might be sending quote([url]... while you should be sending quote("[url]..." (note the quotation chars)
Since the data is from database, just output it as an array before you json encode it.
//array from database
$array = array();
//set the header
header("content-type:json/application");
return json_encode($array);
Then retrieve the encoded json as responseText.
var data = $.ajax({
url:"",
type:"json",
cache:false,
async:false
}).responseText;
var encodedData = JSON.parse(data);
Now you have a valid json object which is encodedData

Categories