Extracting information from PHP to JavaScript - php

I've been stuck for hours now trying to pass a few pieces of information from a PHP script to JavaScript. The PHP script echoes out HTML and I've figured there might be a problem with this if I'm to try and send the JavaScript a JSON object through AJAX. The thing is, all the arrays and such are made within the PHP file which echoes out the results, so what I have done is to try and json_encode those arrays/and or echo them out somehow.
Is it even possible for me to send the information this way? The only thing I can think of would be to write those arrays into a new file and then explode it up into new ones and similar. Not a very fun thought.
To give you an idea of what my PHP looks like:
echo "<html here>";
echo "<html here>";
echo "<html here>";
echo json_encode($array);

Just build your HTML/JavaScript code from PHP...
Simple example (PHP)
<?php
$phpvariable = 'test variable from php';
echo "<html>\n<head>\n</head>\n<body>\n";
echo "<script type=\"text/javascript\">\n";
echo " myPHPvar = '$phpvariable';\n";
echo " alert(myPHPvar);\n";
echo "</script>\n";
echo "</body>\n</html>";
?>
Output (HTML)
<html>
<head>
</head>
<body>
<script type="text/javascript">
myPHPvar = 'test variable set in php';
alert(myPHPvar);
</script>
</body>
</html>
Output (Browser)
JavaScript variable myPHPvar gets value from PHP variable $phpvariable. That is the simplest way to pass variable from PHP to JavaScript.

What's your question? What are you trying to achieve in javascript with your data from PHP? Does the ajax call work at all?
In general I'd recommend separating HTML construction from providing array data as json.
You'd like to handle both in one single PHP call, don't you?
You could attach html parts to you array and send json only, or have array data in a fake html element, that you might exclude from display later. Depends on how complex both parts are. Give some more example code and information, please.

Related

What is the proper way to execute JS?

Is it possible to use JS/JQuery from an external file? If so, what is the best practice?
What is the best practice to call a JQuery function inside a PHP or HTML page?
Here is file.php
echo "<table..";
echo "some code...";
echo "</table>":
<script type="javascript">
$('table').hide().fadeIn(700);
</script>
or:
echo '<script type="javascript">';
echo '$('#foo').toggle("slow");';
echo '</script>';
So, besides a best practice. is any of this possible? I can't seem to make it work from external file or directly.
also from external.js
$(document).ready(function(){ $('table').css({ // code here ... }); });
You can certainly echo jquery (or any html code) directly from PHP
echo '<script type="javascript">
$(\'#foo\').toggle("slow");
</script>';
Your issue in that one was the un-escaped quotes around #foo
I'm not really sure what you meant in the first part of your question, but since you have php I would use this option rather than trying to add jquery into an html file from another javascript file (if that's what you were trying to do)
Both internal and external javascript/jquery code should work.
Make sure you jquery script tag was include in you header/body
If external, make sure to include the external.js script tag after the jquery script tag
Make sure the document was ready first ( $(document).ready() ), and check again the selector either they are exist or not.
For more clean code, no need to echo every single line html code. Just close the php ( ?> ) and write the html as usual.
Please provide as much information as you can so that we know exactly what's the problem was.

Getting another URL's Javascript variable in PHP?

I was wondering if there was some way to get a javascript variable from another url into a variable within PHP?
For example:
A page called exampleurl.com/page (which I do not have control over) with some inline javascript like:
function examplefunction() {
evar = "http://ikmp.co/Usdfio1";
}
Assuming there's HTML and other javascript surrounding this variable I want, how would I be able to retrieve it? Is there a special function to do this, or would it be easier to simply parse the HTML through PHP and then trim the variable to what I want?
In theory, the PHP would have a URL set to retrieve the JS from, and it would echo only what is in that variable.
PHP code (hypothetical) at mysite.com/getvariable.php:
$url = 'exampleurl.com/page';
$js_var = get_js_data($url, $evar);
echo $js_var;
Thanks in advance to anyone who can help me out here!
how about this:
HTML FILE:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<div id="result"></div>
<script>
var javascriptVar ='pie'; //this is whatever the js variable you want it to be
$('#result').load('path/to/my/myphpfile.php?var='+javascriptVar );
</script>
myphpfile.php
<?php
$javascriptVar =$_GET['var'];
echo $javascriptVar;
?>
notice the php code HAS to be in a seperate file than the html for this to work

is it possible to dynamically assign ID to an element in webpage using JS/ PHP?

can i set the id of an element programatically, as in a dynamic setting of id of an element, during runtime of the webpage?
Consider this scenario -
<body id="body1">
Now, i want to set the id of this element "body" dynamically, using the value of a variable in the php code. Is this possible? something like -
<body id=" <?php echo $bodyID; ?> ">
I use php and jquery in the page; please let me know whether such dynamic id assignment is possible to the elements in the html.
thanks.
PHP is the background language, it's what produces your HTML output. So basically, what ever you output from PHP eventually becomes your HTML, meaning yes you can use PHP variables as your elemnt-ID or anything else for that matter.
<?PHP
$var = "body1";
?>
<body id="<?PHP echo $var; ?>"> Hello my ID is <?PHP echo $var; ?></body>
OR You can output all of the HTML using a single echo statement.
<?PHP
$var = "body1";
echo "<body id='$var'>Hello my ID is $var</body>";
?>
In conclusion, whatever is left after PHP is finished executing is your HTML code that the end users browser interprets... Hope this helps...
$(function() {
var variable = 'insert_id';
$('body').attr('id', variable);
});
gives (with jquery)
<body id="insert_id">
Why not? As long as you keep your randomizer ( Math.rand ) big enough there should be little chance for conflicts.
I usually do this, and then at the same time call a JS method and passing the same ID. That would require you storing the ID aside so you can pass it later.
Edit: If you are only setting this on the body then you would not need to access it later.

how to pass a php values to javascript?

here is the code??
posting code:
$.post('get.php',{selected:"aaaa"},function(return){alert(return);});
when i check the values of "selected" value using
<?php
$r=$_POST['selected'];
echo $r;
?>
is displays the value "aaaa" correctly..
this code works fine...
<?php
$r=$_POST['selected'];
?>
var answer="<?php echo "welcome" ?>";
when we echo the value"welcome" it is stored in the variable answer.and i could print that...
but when i put like this....
<?php
$r=$_POST['selected'];
?>
var answer="<?php echo $r ?>";
an empty value is stored in answer... and nothing gets displayed....
whether specifying $r inside " " is not right... how to specify that......
Assuming that the php code you are showing, is located in get.php, there is no use of using javascript in that same file. If you want to get the returned value in a javascript variable in your page, you need to use the first php snippet and use the return value in your .post function:
javascript in original page:
$.post('get.php',{selected:"aaaa"},function(data){
var answer = data;
});
get.php
<?php
$r=$_POST['selected'];
echo $r;
?>
$_POST['selected'] is probably empty to start with. Make sure you're sending a nonempty value for selected, and that you're using POST. (The easiest way is to look in your browser's developer tools for the initial request).
Note that directly outputting user input into the page introduces a Cross-Site Scripting Vulnerability: The input "; alert("evil"); can show that. Assuming you're using UTF-8 all around, you can write:
var answer = <?php echo json_encode($_POST['selected']); ?>
Also, there are often better ways to transfer data from php to JavaScript, including XHR requests/JSON or data-* attributes.

Embed javascript in PHP echo

echo "<td> + manuf + </td>";
Is this above ever going to work??
I'm pulling results from a mysql db to edit the contents but need the jQuery functionality to edit it, hence the embedded javascript variable...
EDIT:
Sorry for the lack of context, its related to another question i've asked on here Mysql edit users orders they have placed
this is the end goal. To edit the order i place, i need to pull the results into an environment similar to how the user placed the order. So my thinking was to include the jQuery functionality to add items to a cart etc, then they could press submit and in the same way i used .Ajax to post the data to an insert php script i would post the values to an update php script! Is this backwards thinking, any advice welcomed!
I suggest you take a look at the follwing.
json_encode
Ajax
JSONP
Now your simplest solution under you circumstances is to do go for the json_encode method. Let me show you an example:
$json_data = array(
'manuf' => $some_munaf_data
);
echo "<script type=\"text/javascript\">";
echo "var Data = " . json_encode(json_data);
echo "</script>";
This will produce an object called Data, and would look like so:
<script type="text/javascript">
var Data = {
munaf : "You value of $some_munaf_data"
}
</script>
Then when you need the data just use Data.munaf and it will hold the value from the PHP Side.
Try just emitting the MySQL content with PHP:
echo "<td id='manuf'>".$manuf."</td>"
Then get the contents with jQuery like this:
var manuf = $('#manuf').text();
Would you not echo out the jQuery within a Javascript code island? You need the client-based code (jQuery) to be able to execute after the server-side code (PHP).
echo '<td><script language = "JavaScript" type = "text/JavaScript">document.write("");</script></td>';
Is this above ever going to work??
Nope. You'd need to output valid JavaScript for the browser to interpret:
echo "<script>document.write('<td>'+manuf+'</td>')</script>";
But that is a dreadful construct, and I can't really see why you would need this, seeing as the td's contents are likely to be static at first.
Consume you have the table echoed with php:
<table id="sometab">
<tr>
<td>
</td>
<tr>
</table>
The jquery for printing resuls in any td is :nth-child(2) takes 2 table td object :
<script type="text/javascript">
$(function(){
$("#sometab tr td:nth-child(2)").html("bla");
})
</script>
Is "manuf" a JS variable or part of a PHP output e.g. part of generated ?
Basically this can easily be done by:
mysql thru PHP(*I can't put table tag..sorry.):
while($row = mysql_fetch_object($result)) {
echo 'tr';
echo 'td a href="#" class="myres"'.$row->manuf.'/a /td';
echo '/tr';
}
then on your JS just attach a "click" handler
$(function() {
$(".myres").click(function() {
//my update handler...
});
});
i think you cant embed the jquery variable in the php like this .
you just give the class name here from here when edit will be click you will get the variable as in submit click in other questions .

Categories