Trouble getting getJSON to work with codeigniter - javascript

I am trying to use getJSON so I can grab the latest information from my database. What I have done so far is store it into a array and json_encode(the array). That works because I can see the information on the view, but the issue is the ajax method does not pick it up. Maybe i am missing something really stupid.
Controller:
public function insertJSON()
{
$this->load->model("values");
$queryresults = $this->values->getDb();
$arr = array();
foreach($queryresults as $row)
{
$arr[] = $row->postcode;
}
$data['arr'] = $arr;
echo json_encode($arr);
$this->load->view('answer', $data);
}
View:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
<script>
$.post('/localhost/codeigniter/index.php/welcome/insertJSON', function(data) {
alert(data);
});
</script>
</script>
</head>
<body>
</body>
</html>
Var Dump of the $arr variable:
array(4) {
[0]=>
string(5) "test1"
[1]=>
string(5) "test2."
[2]=>
string(5) "test3"
[3]=>
string(5) "test4"
}

You are sending the $data array (which contains the $arr) to the view by calling it ( $this->load->view('answer', $data); ) and just right before it you echo the JSON data.
So what you do is call a view which on the top of it, before any html or javascript has a plain text containing the json encoded $arr.
This is obviously wrong and not what you are looking for.
You should do either of these options:
echo the $arr at the view, at the <head> section inside <script>
tags. You would not have to use AJAX call though.
just echo the
$arr at the controller but do not call a view after it. You should
probably make another Controller for this. One to echo the $arr and
one to call the View. This way you can do an AJAX call to the first
Controller.
pass the $arr to a view which will just echo the JSON encoded data.
This is like option #2 but it uses the View in order to show the
data and not the Controller, which is the most appropriate way to follow the MVC pattern.
Controllers should not echo anything.
I suggest to follow option #3.

So. if you want to echo out a JSON obj that can be pick it up using ajax, then u need to make sure that the output mime-type of your page can serve JSON data.
also notice that u cannt echo anything else with the json data that u want out of ur function. as i can see in your code u echo json then load a view ! u need to split that into 2 separate pages
Fix:
public function _JSON()
{
$this->load->model("values");
$queryresults = $this->values->getDb();
$arr = array();
foreach($queryresults as $row)
{
$arr[] = $row->postcode;
}
return $arr;
}
public function json_body(){
$this->load->view('answer',array('data'=>$this->_JSON()));
}
public function getJSON(){
$this->output
->set_content_type('application/json')
->set_output(json_encode($this->_JSON()));
}
///note that $this->_JSON() now return ur $arr so u can use it in many methods.
now to load page u can go to /json_body 'rename it as u want'
and js should be
<script>
$.post('<?=base_url('welcome/getJSON')?>', function(data) {
alert(data);
});
</script>
<!--notice that base_url show echo out ur url base on ur config.php file-->
NOTE:
function getJson get use the power of CI Output class to set the mime-type of page and make sure this array is the only output. this is not a must but its just best practice. if u want u can relapce all 3 lines with simple echo json_encode($this->_JSON()); and it will work too !

I guess the problem is your post URL:
$.post('//localhost/codeigniter/index.php/welcome/insertJSON', function(data) {
alert(data);
});
you missed double slash (//)

Related

JSON from localstorage not able to decode in php

I am fetching values from localstorage as JSON and trying to decode.
But its not working.
This my code to fetch JSON from localstorage:
$items = "<script> document.write(JSON.parse(JSON.stringify(localStorage.getItem('itemList')))); </script>";
When i echoed above $items it resulted like this:
{"items":[{"name":"Guitar","id":"1"}]}
Decoding above json like this:
$decoded = json_decode($items, true);
When i am trying to echo $decoded not displaying anything. When i did var_dump($decoded) its showing NULL
Any help is appreciated. Thank you.
The situation is that you're not able to combine JS/PHP "in one line".
$items = "<script> document.write(JSON.parse(JSON.stringify(localStorage.getItem('itemList')))); </script>";
json_decode from $items will give you directly the code that you've put in (check json_last_error())... without any JS execution (or you have to use PhantomJS; but it's not your case).
How it has to be:
JS part (sample.js):
jQuery.post('sample.php', {
'item': JSON.stringify(localStorage.getItem('itemList'))
});
PHP part (sample.php)
$items = filter_input(INPUT_POST, 'item');
$decoded = json_decode($items, true);
var_dump($decoded);
localStorage only stores strings. The JSON.stringify() is wrong since it expects a JSON object, not a string, as input.

covert a php array to json object , then back to array in javascript [duplicate]

I need to get an array generated from a script php. I have Latitude and Longitude for each user in a database.
I take the values from the db with this code (file.php):
$query = "SELECT Latitude, Longitude FROM USERS";
$result=mysql_query($query);
$array=array();
while ($data = mysql_fetch_array($result)) {
$array[]=$data['Latitude'];
$array[]=$data['Longitude'];
}
echo $array;
and I call with ajax with this code:
$.post('./file.php',
function( result ){
alert(result);
});
but even if in the script php the array is correct (if I echo array[25] I obtain the right value) in Javascript I obtain "Undefined".
How can I get the array in correct way??
thanks!
edit: after encoded with json_encode($array); in php and JSON.parse(result) in javascript seems not working.
In the console I have the array, but I can't access to its values. (Array[0] gave me "undefined").
use this
echo json_encode($array);
on server side
and
var arr=JSON.parse(result);
on client side
As Ruslan Polutsygan mentioned, you cen use
echo json_encode($array);
on the PHP Side.
On the Javascript-Side you can simply add the DataType to the $.post()-Function:
$.post(
'./file.php',
function( result ){
console.log(result);
},
'json'
);
and the result-Parameter is the parsed JSON-Data.
You can also set the correct Content-Type in your PHP Script. Then jQuery should automaticly parse the JSON Data returned from your PHP Script:
header('Content-type: application/json');
See
http://api.jquery.com/jQuery.post/
http://de3.php.net/json_encode
You need to convert the php array to json, try:
echo json_encode($array);
jQuery should be able to see it's json being returned and create a javascript object out of it automatically.
$.post('./file.php', function(result)
{
$.each(result, function()
{
console.log(this.Latitude + ":" + this.Longitude);
});
});

Undefined Index in php: transfering variables from Ajax to php

Hello I tried to transfer variable from ajax to php, but php file keeps throwing me the following:
Undefined index: vals in /Applications/XAMPP/xamppfiles/htdocs/fang_sophie/project/sign in-out/bin/readall2.php
Ajax reads like this:
<script>
var var_data = "Hello World";
$.ajax({ url: 'bin/readall2.php',
data: {'vals' : var_data},
type: 'post',
dataType:'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: Could not delete");
}
});
</script>
Php reads like this:
<?php
session_start();
$hello = '';
$_SESSION['hello'] = $_POST['vals'];
echo($hello);
?>
Why doesn't it work? Please help :)
One problem here is that you're trying to output JSON dataType:'json', where you don't have JSON to start with. Consult my footnotes also.
You need to use a text data type.
dataType:'text',
By the way, this won't echo anything at all (in the alert), since $hello is empty:
session_start();
$hello = '';
$_SESSION['hello'] = $_POST['vals'];
echo($hello);
You (may) want to echo the session array taken from the POST array, which is the logical thing to do:
echo($_SESSION['hello']);
Reference:
http://api.jquery.com/jquery.ajax/
Foonotes:
If by any chance you may be trying to access that (PHP) file directly, or your entire code is in the same file, then you need to use a conditional statement for it.
I.e.:
session_start();
if(!empty($_POST['vals'])){
$hello = '';
$_SESSION['hello'] = $_POST['vals'];
echo($_SESSION['hello']);
}
That, and/or use two separate files.
In regards to JSON; if you really want/need to use it, then set it back to dataType:'json', but use json_encode() for it and replacing echo($_SESSION['hello']); with and assigning the $hello variable to the session array:
$hello = $_SESSION['hello'];
echo(json_encode($hello));
<?php
//first start session
session_start();
//set header to json and UTF-8 encoding
header('Content-Type: application/json;charset=utf-8');
//check if $_POST['vals'] is set first using isset() to prevent notice
//undefined index
if(isset($_POST['vals'])){
echo "value of vals is: ".$_POST['vals'];
}else{
echo "vals not set";
}
?>
In your ajax request, the format of return is expect to be JSON. and you are returning a string.
You just need to add json_encode in your return line of php:
session_start();
$hello = '';
$_SESSION['hello'] = $_POST['vals'];
echo(json_encode($hello));
The correct answer is you are reading the wrong variable:
$hello = '';
$_SESSION['hello'] = $_POST['vals'];
echo($hello);
It should be:
echo $_SESSION['hello'];
If you want the session data. For the undefined index, var_dump out your $_POST variable: var_dump($_POST);
If the $_POST variables do not match, or you get back an empty array, it was never transmitted to the server.
Original wrong answer:
When JQuery has "processData" flag set to false, it doesn't encode the data and requires the user reads it from the php://input stream.
Unencoded JSON is not sent into POST requests. For the quickest fix, try this:
parse_str(file_get_contents("php://input"), $vars);
// This will fill $vars with any data sent over to PHP.
var_dump($vars);
$vars should now be populated with the data you want. If $vars is empty, you are not transmitting the data.

Pass data from mysqli to javascript

I want to pass the results of a query to javascript (I want to make an interactive quiz about fish species). This seems to be easy with json_encode, but the structure of my php array makes it difficult to access? Even console.log does not work, so there is probably an error, though I have been checking this code more than i would like to admit. I am pretty sure the error is in the small javascript part though. The code (this is all in a .php file):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<?php
$con = new mysqli("localhost", "root", "", "marinefish");
$query = "SELECT Commonname, Scientificname FROM allseafish";
$result = $con->query($query);
while ($row = $result->fetch_array()){
$rows[] = $row;
}
/*
Structure rows:
array(544) {
[0]=>
array(4) {
[0]=>
string(7) "Allfish"
["Commonname"]=>
string(7) "Allfish"
[1]=>
string(11) "Omni pisces"
["Scientificname"]=>
string(11) "Omni pisces"
}
*/
mysqli_free_result($result);
mysqli_close($con);
?>
<title>Untitled</title>
</head>
<body>
<script type="text/javascript">
var ars = <?php echo json_encode($rows) ?>;
console.log(ars);
alert(ars[0][0]);
</script>
</body>
</html>
Any suggestions, or easy-to-understand links/ tutorials are very welcome!
I tried: http://www.dyn-web.com/tutorials/php-js/json/multidim-arrays.php which seems very clearly explained, but couldn't help me. I also have tried to simplify the structure of the php array, but without success.
And I tried to change the echo json_encode($rows) into print(json_encode($rows)).
As you may have noticed, I am new with this, so all basic tips will be a great help.
Thank you!
A better solution would be to separate your javascript from PHP through post/get requests by creating a new PHP page (e.g. Query.php) that is specific for Database response:
... MYSQL CODE ...
echo json_encode($rows); // Echo everything into body
And Using jQuery (or equivalent Ajax request):
$.ajax({
type: "GET",
url: 'query.php',
dataType: "json",
success: function(your_php_reponse_as_json){
console.log(your_php_reponse_as_json);
}
});
Note that this code will be essentially asynchronous as the request for the MYSQL Query is sent in another page using async JavaScript. Additionally you can customize your query reponse with $_POST & $_GET:
PHP Code:
$get1 = $_GET['js_sent'];
// Alternatively
$post1 = $_POST['js_sent'];
Edit: You'll need to serialized data before sending.
For the complete jQuery solution refer here jQuery Ajax POST example with PHP
$.post("checkproduct.php", {"useremail" : emailVal}, function(data) {
//use data returned from checkproduct.php.the value returned from checkemail.php is retrieved as data.
});
The above code post method to post variable to checkproduct.php here we are passing useremail and the value is emailVal and this is also a variable. and in checkproduct.php you need to echo/return your result. and resultant data can be use in the function as data

How to use AJAX and JSON to get data returned from a PHP file

For starters this website is being run on a Debian machine.
I have a SQLite3 database that has current news articles in it. I am trying to use PHP to query the database for these articles, and pass it as JSON to AJAX, so it can be displayed on my webpage. Right now nothing is being shown and I don't know where the error is.
Here is the PHP code to get the information from the database:
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('website.db');
}
}
$db = new MyDB();
$result = $db->query('SELECT * FROM news');
echo json_encode($result);
?>
Here is the JavaScript where the AJAX is located:
<script type="text/javascript">
function getNews()
{
console.log("firstStep");
$(document).ready(function()
{
console.log("secondStep");
$.getJSON("http://localhost/getNews.php",function(result){
console.log("thirdStep");
$('news').append(result); // display result
});
});
}
I think the error is occurring around $.getJSON("http://localhost/getNews.php",function(result), as in the console, thirdStep is never being outputted.
This is the HTML it should be appending to:
<div id = "newsEntry"> <news> test </news> </div>
Any help would be appreciated.
To find out what's going on, you might want to add an error handler:
$(document).ready(function() {
$.ajax({
url: "http://localhost/getNews.php",
dataType: "json",
success: function(result) {
console.log("thirdStep");
},
error: function(err) {
alert(err);
}
});
})
By default, the web server serves content as application/html. So when you simply echo a JSON string, it's treated like text on a html page. To really return JSON from your server, you need to specifically set it.
Include this line before your echo:
header('Content-Type: application/json; charset=utf-8');
Edit
On inspection of you PHP code, you are missing one line. Note that $db->query() returns you an SQLite3Result. You need to call:
$array = $result->fetchArray(SQLITE3_ASSOC); // get an associative array first
$json = json_encode($array);
header('Content-Type: application/json; charset=utf-8');
echo $json

Categories

Resources