I'm making a dynamic csv to array formatter, and part of it displays the formatted array, and the other part is suppose to display the code for it. I can't get it to display the code without it just showing the array again, what do I do?
-Javascript
$.post('csv.php', {names : names, fp : fp}, function(data){
$('#arrayDisp > center > textarea').html(data);
$.ajax({
url: "csv.php",
context: document.body,
success: function(){
$('#codeDisp > center > textarea').html(data);
}
});
});
-Php
$file = file(_FILE_PATH, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$data = array();
$line_number = 0;
foreach($file as $f) {
$line = explode(',', $f);
$i = 0;
foreach($line as $l) {
$data[$line_number][$names[$i]] = $l;
$i++;
}
$line_number++;
}
json_encode($data);
print_r($data);
?>
You can try
foreach($data as $key => $value)
{
echo $key." has the value". $value;
}
This might work for you
I'd modify the script to accept a GET param. so it reads like this
if($_GET['showSource'])
highlight_file ($_SERVER['PHP_SELF']);
else
//do stuff
So your JS call would actually be two calls, first you call the script without the ?showSource=1 so you will get the parsed csv thingy, then you do the call with the ?showSource=1 and get the source displayed.
Thanks to Emissary's helpful hint I found the answer to my problem -
I added a request variable to my post requests and renamed them when each was over -
var request = 'array';
$.post('csv.php', {names : names, fp : fp, request : request}, function(data){
$('#arrayDisp > center > textarea').html(data);
request = 'code';
$.post('csv.php', {names : names, fp : fp, request : request}, function(data){
$('#codeDisp > center > textarea').html(data);
});
});
Then in my php code I did this -
if ($_POST['request'] === "array") {
json_encode($data);
print_r($data);
}
else if ($_POST['request'] === "code") {
echo file_get_contents('csv.php');
}
Related
I ideally want the Ajax result to be converted from Jsonstring to OBJ Thank You in advance.
I know the AJAX GET script is working becuase when I alert the Ajax Post result I see the Contents in json string format as below.
alert(JSON.stringify(data));
[{"id":"1","username":"jiten","name":"Jitensingh\t","email":"jiten93mail”},{“id":"2","username":"kuldeep","name":"Kuldeep","email":"kuldeemail”}]
I want the AJAX GET result data converted to look like this in OBJ format like below.
{id:31,name:"Mary",username:"R8344",email:"wemail}];
PHP/SQL CODE with the Json encoded Array
<?php
include "../mytest/config.php";
$return_arr = array();
$sql = "SELECT * FROM users ORDER BY NAME";
$result = $conn->query($sql);
//Check database connection first
if ($conn->query($sql) === FALSE) {
echo 'database connection failed';
die();
} else {
while($row = $result->fetch_array()) {
$id = $row['id'];
$username = $row['username'];
$name = $row['name'];
$email = $row['email'];
$return_arr[] = array(
"id" => $id,
"username" => $username,
"name" => $name,
"email" => $email);
}
// Encoding array in JSON format
echo json_encode($return_arr);
}
?>
php echo _encode array above returns below Json string format
[{"id":"1","username":"jiten","name":"Jitensingh\t","email":"jiten93mail”},{“id":"2","username":"kuldeep","name":"Kuldeep","email":"kuldeemail”}]
I am looking for something like below.( top half of the script)
<script>
$(document).ready(function(){
$.ajax({
url: 'ajaxfile.php',
type: 'get',
dataType: 'JSON',
success: function(result){
var data =(JSONstring convert to OBJ(result);
//-----The top half of script -------------
$.each(data, function( i, person ) {
if(i == 0) {
$('.card').find('.person_id').text(person.id);
$('.card').find('.person_name').text(person.name);
$('.card').find('.person_username').text(person.username);
$('.card').find('.person_email').text(person.email);
} else {
var personDetailCloned = $('.card').first().clone();
personDetailCloned.find('.person_id').text(person.id);
personDetailCloned.find('.person_name').text(person.name);
personDetailCloned.find('.person_username').text(person.username);
personDetailCloned.find('.person_email').text(person.email);
$('.card-container').append(personDetailCloned);
}
});
});
</script>
I will need help with the closing tags as above is just an example
The solution is:
success: function(result){
data =(result);
There was no need o convert the data to OBJ or anything ( blush). Then the code on the 2nd half of the Ajax script will receive the data and populate. Thanks to all contributors.
I am trying to use the getJSON function with a PHP file that echo some JSON. If I save the JSON expected from the PHP file as a JSON file, it works perfect but if I use the PHP file as URL it doesn't work because it fails when parsing the PHP at line 1 column 1.
PHP file:
<?php
$jsondata = array();
if( isset($_GET['param']) ) {
if( $_GET['param'] == 'valor' ) {
$jsondata['success'] = true;
$jsondata['message'] = 'Correct.';
} else {
$jsondata['success'] = false;
$jsondata['message'] = 'Incorrect.';
}
header('Content-type: application/json; charset=utf-8');
echo json_encode($jsondata);
exit();
}
?>
And this is what I am using in the Javascript file:
$.getJSON('test.php', {format: "json"}, function(data) {
window.alert("Loaded");
}).fail( function(data, textStatus, error) {
console.error("getJSON failed, status: " + textStatus + ", error: "+error)
});
If I change from test.php to test.json it works.
EDIT: I was using mysql instead of mysqli and the server outputted a table and then my JSON and thats why I had the JSON Error parse ...
Fixed just changing from mysql to mysqli.
Thanks everyone.
Try this:
if( $_GET['param'] == 'valor' ) {
$row = array('success'=> true,'message'=>'Correct');
array_push($jsondata,$row);
} else {
$row = array('success'=> false,'message'=>'Incorrect');
array_push($jsondata,$row);
}
And the echo remains the same:
echo json_encode($jsondata);
I've coded like this when I had to work with JSON and PHP with JQuery.I hope it works for you too.
I have a jquery method which puts an ajax call like this -
function getAppointmentTime(){
//$data = getUserData();
$docId = parseInt($( "#docSelect option:selected" ).val());
$date = $('#patDateVal').val();
$.ajax({
type: "POST",
url: 'func.php',
async: false,
data: {action: 'getDocFreeTime', docId:$docId, date:$date},
success: function(data){
data = JSON.parse(data);
if(data != 0){
$row = '';
for(var i=0; i<data.length; i++){
$row += '<option value="'+data[i]['Patient_ID']+'">'+data[i]['Patient_First_Name']+' '+data[i]['Patient_Middle_Name']+' '+data[i]['Patient_Last_Name']+'</option>'
}
$('#patSelect').html($row);
$('#selectedPatId').val(data[0]['Patient_ID']);
}else{
}
}
});
}
This function call goes to my func.php where this code is there -
$action = $_POST['action'];
switch($action) {
case 'getDocFreeTime':
getDocFreeTime($_POST['docId'], $_POST['date'], $role);
break;
}
function getDocFreeTime($docId,$date, $roles){
return $roles->_getAppointmentTime($docId,$date);
}
PS - $role is a PHP object of member class which I am creating already.
The _getAppointmentTime(...) method is in my PHP class called member, which is defined like this -
function _getAppointmentTime($docId,$date){
$date = date("Y-m-d h:i:s",strtotime($date));
try {
$stmt = $this->_db->prepare('call view_availibility(:id,:appdate)');
$stmt->bindParam(":appdate", $date, PDO::PARAM_STR, 255);
$stmt->bindParam(":id", $docId, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows);
} catch(PDOException $e) {
if(ENV == 1){
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
}else{
echo 0;
}
}
}
Now, when I am calling the first jquery method, the method is called, but onsuccess of ajax, data variable only gets a blank string.
I have other methods, which work exactly like this, but this one is not. I tried echoing random string to debug, but no luck, still get blank string in onsuccess.
Can someone please point out what is the mistake I am doing. I have many other methods which work and are exactly like this, but not this one. Maybe I am doing a noob mistake somewhere, but cannot find it out. Please help.
Thanks.
I'm trying to use Javascript to read stock data from yahoo finance at "http://table.finance.yahoo.com/table.csv?s=000001.sz", which returns a csv file and convert the data into json format as in http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-ohlcv.json&callback=? to be used in highcharts.
I tried using $.ajax get and jquery.get but neither worked. Can somebody tell me how to read the data from the url and convert it into json? Thanks a lot.
This can be easily done with PHP.
<?php
file_put_contents("data.csv", fopen("http://table.finance.yahoo.com/table.csv?s=000001.sz", 'r'));
//reads the CSV file and save value into an associative array
function csv_to_array($filename = '', $delimiter = ',')
{
if (!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE) {
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
if (!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
$arr = csv_to_array('data.csv');
//<pre></pre> tags appear only to prevent white-space collapsing
//prints the associative array
echo "<pre>";
print_r($arr);
echo "</pre>";
//displays the the JSON
echo "<pre>";
echo json_encode($arr, JSON_PRETTY_PRINT);
echo "</pre>";
?>
Now depending on the format of JSON that it acceptable to Highcharts API, you are required to tweak how the array is encoded into JSON.
Also avoid using JSON_PRETTY_PRINT if the size of the incoming data is large.
I guess you are facing Cross Domain issue. Use jsonp calls for Cross Domain requests. Use something like this
$.ajax({
url : "http://xx.xx.xx.xx/xxx/xxx",
type: "GET",
dataType: "jsonp",
jsonp : "callback",
success: function(data) {alert("Success");},
error: function(data) { alert("Error"); }
});
});
I'm trying to perform some PHP code and then pass it's results to another PHP script through jquery.
One of these results is an array, and I'm passing it to a GET so it gets to the other script. (alot of work, but I can't have page reloads even tho I have to use PHP).
The problem occurs when I'm trying to put the PHP variable through JQuery.
What I have to do this for me is:
var _leafs = <?php echo json_encode($leafs); ?>;
When I run json_encode on $leafs and then print the result (all using PHP), it gives me a json array that has been successfully validated by JSONLint.
When I use the above code and alert() the result it's missing the brackets and quotes.
Even weirder is when I pass it through like so:
$.get('set_fields.php?pt=' + _path + '&lf' + _leafs, function(data) {
The result is this:
" string(4) "
"
Which shows up to be a <br> in my html reader.
Am I missing something when I'm converting it to json?
Additional code:
<?php
// Fetch the XML from the URL
if (!$xml = file_get_contents($_GET['url'])) {
// The XML file could not be reached
echo 'Error loading XML. Please check the URL.';
} else {
// Get the XML file
$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);
$paths = [];
$leafs = [];
foreach ($xpath->evaluate('//*|//#*') as $node) {
$isLeaf = !($xpath->evaluate('count(#*|*) > 0', $node));
$path = '';
foreach ($xpath->evaluate('ancestor::*', $node) as $parent) {
$path .= '/'.$parent->nodeName;
}
$path .= '/'.($node instanceOf DOMAttr ? '#' : '').$node->nodeName;
if ($isLeaf) {
$leafs[$path] = TRUE;
} else {
$paths[$path] = TRUE;
}
}
$paths = array_keys($paths);
$leafs = array_keys($leafs);
echo "Choose a path<br><br>
<form>
<select id='field_dropdown'>";
foreach($paths as $value) {
echo "<option value='".$value."'>".$value."</option>";
}
echo " </select>
<button id='send_path'>Send path</button>
</form>
";
}
?>
<script>
$(document).ready(function() {
$('#send_path').click(function() {
var _path = $("#field_dropdown").val();
// Get the leafs array and send it as a json string to set_fields.php
var _leafs = <?php echo json_encode($leafs); ?>;
$.get('set_fields.php?pt=' + _path + '&lf=' + _leafs, function(data) {
$('#fields').append(data);
}).error(function() {
$('#fields').html('Error calling XML script. Please make sure there is no error in the XML file.');
});
return false;
});
});
</script>
And here the code where I want the json array to end up (and then get turned back into a PHP array).
<?php
// Match all the fields to the values
$path = $_GET['pt'];
$leafs = json_decode($_GET['lf']);
$fieldLeafs = [];
$pathLength = strlen($path) + 1;
foreach ($leafs as $leaf) { if (0 === strpos($leaf, $path.'/')) { $fieldLeafs[] = substr($leaf, $pathLength); } }
var_dump($path."<br>");
var_dump($leafs."<br>");
?>
What if you get the array through jquery instead of echoing it?
<input id="hidden-value" value="<?php echo json_encode($leafs); ?>" />
and then
var _leafs = $('#hidden-value').val();
What about adding an = after the lf query parameter when you build the get URI?
$.get('set_fields.php?pt=' + _path + '&lf=' + _leafs, ...
Just write 'json' in the last parameter of get method:
$.get('set_fields.php?pt=' + _path + '&lf' + _leafs, function(data) {
$('#fields').append(data);
},'json')//<-- this
.error(function() {
$('#fields').html('Error calling XML script. Please make sure there is no error in the XML file.');
});
Did you try this?
var _leafs = [<?php foreach($leafs as $leaf){ echo "'$leaf',"; } ?>]