I have recently started coding with javascript/php using the Cloud9 IDE.
I know this may be a duplicate of some questions on here, but I have yet to find a solution that works for me.
I have an array of custom javascript objects that I would like to save to a file on the server (later to be retrieved to repopulate data on the page):
<script>
var questionList = [];
function saveToFile() {
var x =JSON.stringify(questionList);
$.post("saveQuestion.php", {data : x}, function(){alert("File saved successfully")});
}
</script>
//in the body of the html
<button id="saveToFileButton" type="button" onclick='saveToFile()'>Save to file</button>
The php file 'saveQuestion.php' is in the same directory, and is as follows:
<?php
$data = $_POST['data'];
file_put_contents("savetest.txt", $data);
?>
However, despite my best efforts, 'savetest.txt' remains empty.
I know that 'x' is being assigned the correct value as I can print it out to a html element.
Edit: The php script has permission to write to the file, but as far as I can tell it is never called. What would be a possible cause/solution to this?
Can someone offer a simple explanation that highlights what I am doing wrong and possible ways to fix it?
Thanks!
Maybe you should assign the questionsList array some values:
<script>
// Check if your assigning a value to this array
var questionList = ['value 1', 'value 2', 'etc..'];
function saveToFile() {
var x =JSON.stringify(questionList);
$.post("saveQuestion.php", {data : x}, function(){alert("File saved successfully")});
}
</script>
Related
Basically I have the most popular code in the world for a dynamic dependant dropdown using PHP & MySQL, but I'm trying to populate the select option text and option value from an array, let's say the id as the option value, and the name as the option text; I found a thread that exactly depicts what I am trying to do, but it is not working for me (the dyanmic dropdown works like a charm).Here's the link:
http://forums.phpfreaks.com/index.php?topic=287884.0
And here's my code;
`for (i=0;i<myarray.length;i++)
{
var optn = document.createElement("OPTION");
optn.text = myarray[i][0];
optn.value = myarray[i][1];
document.testform.id_proveedor.options.add(optn);
}`
And the part of the code from the dd.php
`while($nt=mysql_fetch_array($q)){
$str=$str.'new Array("'.$nt[id_proveedor].'","'.$nt[nombre].'"),';
}
$str=substr($str,0,(strLen($str)-1)); // Removing the last char , from the string
echo "new Array($str)";`
Any ideas on why the code is not working?
Thanks in advance!!
I think that this script uses "evaluate" function of javascript and I don't think it is a good think.
IMO the best practice would be such a code in php, using JSON
$result = array();
while($nt=mysql_fetch_array($q)){
$result[]=$nt;
}
echo json_encode($result);
And in your AJAX code you just have to use var myarray=JSON.parse(response);to have your array to traverse.
I'm trying to figure out the least obtrusive and least computationally expensive way to store PHP objects coming from my MySQL database such that their data can be rendered by JavaScript on click by a user.
Currently, I'm storing the data as custom attributes on a button. But this generates a lot of code and I've heard is "slow". I'm wondering if I should JSON encode my PHP object, $items (see below), and how that JavaScript would then look. Note I'm using Codeigniter for the PHP so that's what up with the alternate foreach loop syntax.
Here's where I'm at so far with the HTML/PHP:
<img id="img"></img><a id="url"></a> <!--elements where data is rendered on click-->
<? foreach($items as $item):?>
<button data-id="<?=$item->id?>" data-url="<?=$item->url?>" data-img="<?=$item->img?>">click<?=$item->id?></button>
<?endforeach;?>
And here's my JS:
$(document.body).on('click', 'button', function(){
var $this=$(this), id=$this.data('id'), url=$this.data('url'), img=$this.data('img');
$('#img').attr('src', img);
$('#url').attr('href', url).html(url);
});
Most of my site's data is coming from PHP via MySQL and I've long been confused by the issue of when should I convert that data to a JavaScript array/JSON or not.
If you json_encode your $items array (assuming it only consists of data you will want in JS), you can assign this to a JS variable:
<script>var items = <?php echo json_encode($items); ?></script>
You can then remove the data-url and data-img attributes. Then, within your JS code:
var $this = $(this), id = $this.data('id'), url = items[id].url, img = items[id].img;
// the rest of your code
Edit: when you move the click handler in a separate file, you would get something like this:
function setup_click(items) {
var $img = $('#img'), $url = $('#url');
$('button').click(function(evt) {
var id = $(this).data('id'),
url = String(items[id].url),
img=String(items[id].img);
$url.attr('href', url).html(url);
$img.attr('src', img);
});
}
here's a JSfiddle showing off the javascript/JSON part: http://jsfiddle.net/fz5ZT/55/
To call this in one shot from your template:
<script src="[your ext script file path].js"></script>
<script>setup_click(<?php echo json_encode($items); ?>);</script>
Hope that helps :)
I have a specific array that php needs to access and write to a file. I also want to be able to call the php to get the array info back. I use JSON.strigify to store the array in a string, but i cant figure out how to send it to a server with php. I have very little php experience and i tried:
<script language="javascript">
var COMMENTS_FOR_DISPLAY = new Array('Have fun with this code: Chris');
// Adds a new comment, name pair to the Array feeding textualizer.
function add_comment() {
// Retrieve values and add them to Array.
var new_comment = $('#kwote').val();
var new_name = $('#name').val();
COMMENTS_FOR_DISPLAY.push(new_comment + ': ' + new_name);
// Reset <input> fields.
$('#kwote').val('');
$('#name').val('');
var arrayAsString = JSON.stringify(COMMENTS_FOR_DISPLAY);
}
$(document).ready(function() {
var txt = $('#txtlzr'); // The container in which to render the list
var options = {
duration: 5, // Time (ms) each blurb will remain on screen
rearrangeDuration: 5, // Time a character takes to reach its position
effect: 'random', // Animation effect the characters use to appear
centered: true // Centers the text relative to its container
}
txt.textualizer(COMMENTS_FOR_DISPLAY); // textualize it!
txt.textualizer('start'); // start
});
</script>
in main.php i put:
<?php
$kwoteString = $_GET["arrayAsString"];
echo $kwoteString;
?>
I used echo to see if i was getting any output,but i wasn't. It could be a very simple fix, maybe im missing a header or something telling my html document to read main.php?? any help would be appreciated!
Use jquery with
$.post(url,params);
there are many tutorials around the web and stack overflow itself.
Here the doc:
http://api.jquery.com/jQuery.post/
you can add a hiddenField and set the string to the hidden field.
php code will read the value from hidden field.
I hope you'll able to help me. I'm fed up of trying things without any solution and php it's just driving me crazy. I'm looking for help because I have a html document where I use ajax thanks to jquery api. Inside this file, in a js function I have:
$.ajax({
type: "GET",
url: "c.php",
data: "dia="+matriz[0]+"&mes="+matriz[1]+"&ano="+matriz[2]+"&diaa="+matriz2[0]+"&mess="+matriz2[1]+"&anoo="+matriz2[2]+"&modo=0&semana=0",
success: Mundo,
error: function(e){
alert('Error: ' + e);
}
});
This code allows me to send the information that I want to the file c.php where I have:
include('funciones.php');
include('config.php');
$mierda = array();
$mierda[0] = $_GET['modo'];
$mierda[1] = $_GET['dia'];
$mierda[2] = $_GET['mes'];
$mierda[3] = $_GET['ano'];
$mierda[4] = $_GET['diaa'];
$mierda[5] = $_GET['mess'];
$mierda[6] = $_GET['anoo'];
$mierda[7] = $_GET['semana'];
As you see it's very simple. My crazy problem is that with firebug I've seen that the data is sent well but for some reason I can't use it. I have tried with $_Get, $_post and $_request and always is the same problem. But this can be stranger... If I put:
echo json_encode($mierda);
then miraculously, the php returns the data that I have passed so in conclusion I have:
I can send the data to the php file well
I can print all the data that I have sent well just accessing yo $_GET, $_POST, $_REQUEST
I can't use any value separatly like $_GET['dia']
What's going wrong there?
PS. The include php files are functions that access to my database so there's no interaction with them.
Your data is not URL-encoded. Try do something like this,
$.ajax({ type: "GET",
url: "c.php",
data: {"dia":matriz[0], "mes":matriz[1] ....},
success: Mundo,
error: function(e){ alert('Error: ' + e); }
});
If you are returning a json value use json to read that.
See
http://api.jquery.com/jQuery.getJSON/
http://pinoytech.org/blog/post/How-to-Use-JSON-with-jQuery-AJAX
Here is an example to read json value
$('document').ready(function(){
$('#submit).click(function(){
$.post('your_php_page.php', {employee_id: '456'},
function(data){
console.log(data.first_name);
console.log(data.last_name);
}, 'json');
})
});
Hope it helps
You have a crazy problem. According to your question:
$mierda = array();
$mierda[0] = $_GET['dia']; //... and so on
echo json_encode($mierda);
works while:
echo $_GET['dia'];
doesnt. Try:
$mierda = array();
$mierda[0] = $_GET['dia'];
echo $mierda[0];
echo $_GET['dia'];
It will show you whether the problem is in the PHP, or the javascript.
I have encoded the data as ZZColer said and the error is still.
Starx, it's not a question of the returning.
digitalFresh, in fact the error is from PHP because I can copy $_POST, $_GET array to a new array and print all this information but if I put after all things like:
If( mierda[0] == 0) {... The element is empty! and if I try directly $_GET['dia'] it says that this element doesn't exist in the array. Also I have tried $_GET[dia] or $_GET[0] without a solution.
PD:
I don't know how but PROBLEM SOLUTIONED!
Thanks to all!
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
How do I access PHP variables in JavaScript or jQuery? Do I have to write
<?php echo $variable1 ?>
<?php echo $variable2 ?>
<?php echo $variable3 ?>
...
<?php echo $variablen ?>
I know I can store some variables in cookies, and access these values via cookies, but values in cookies are relatively stable values. Moreover, there is a limit, you can not store many values in cookies, and the method is not that convenient. Is there a better way to do it?
Your example shows the most simple way of passing PHP variables to JavaScript. You can also use json_encode for more complex things like arrays:
<?php
$simple = 'simple string';
$complex = array('more', 'complex', 'object', array('foo', 'bar'));
?>
<script type="text/javascript">
var simple = '<?php echo $simple; ?>';
var complex = <?php echo json_encode($complex); ?>;
</script>
Other than that, if you really want to "interact" between PHP and JavaScript you should use Ajax.
Using cookies for this is a very unsafe and unreliable way, as they are stored clientside and therefore open for any manipulation or won't even get accepted/saved. Don't use them for this type of interaction.
jQuery.ajax is a good start IMHO.
If AJAX isn't an option you can use nested data structures to simplify.
<?php
$var = array(
'qwe' => 'asd',
'asd' => array(
1 => 2,
3 => 4,
),
'zxc' => 0,
);
?>
<script>var data = <?php echo json_encode($var); ?>;</script>
You're asking kind of a two-part question. As far as syntax (I think since PHP4?) you can use:
<?=$var?>
... if PHP is configured to allow it. And it is on most servers.
As far as storing user data, you also have the option of storing it in the session:
$_SESSION['bla'] = "so-and-so";
for persistence from page to page. You could also of course use a database. You can even have PHP store the session variables in the db. It just depends on what you need.
Basically, yes. You write alert('<?php echo($phpvariable); ?>');
There are sure other ways to interoperate, but none of which i can think of being as simple (or better) as the above.
I ran into a similar issue when building a custom pagination for a site I am working on.
The global variable I created in functions.php was defined and set to 0. I could output this value in my javascript no problem using the method #Karsten outlined above. The issue was with updating the global variable that I initially set to 0 inside the PHP file.
Here is my workaround (hacky? I know!) but after struggling for an hour on a tight deadline the following works:
Inside archive-episodes.php:
<script>
// We define the variable and update it in a php
// function defined in functions.php
var totalPageCount;
</script>
Inside functions.php
<?php
$totalPageCount = WP_Query->max_num_pages; // In my testing scenario this number is 8.
echo '<script>totalPageCount = $totalPageCount;</script>';
?>
To keep it simple, I was outputting the totalPageCount variable in an $ajax.success callback via alert.
$.ajax({
url: ajaxurl,
type: 'POST',
data: {"action": "infinite_scroll", "page_no": pageNumber, "posts_per_page": numResults},
beforeSend: function() {
$(".ajaxLoading").show();
},
success: function(data) {
//alert("DONE LOADING EPISODES");
$(".ajaxLoading").hide();
var $container = $("#episode-container");
if(firstRun) {
$container.prepend(data);
initMasonry($container);
ieMasonryFix();
initSearch();
} else {
var $newItems = $(data);
$container.append( $newItems ).isotope( 'appended', $newItems );
}
firstRun = false;
addHoverState();
smartResize();
alert(totalEpiPageCount); // THIS OUTPUTS THE CORRECT PAGE TOTAL
}
Be it as it may, I hope this helps others! If anyone has a "less-hacky" version or best-practise example I'm all ears.
I would say echo() ing them directly into the Javascript source code is the most reliable and downward compatible way. Stay with that unless you have a good reason not to.