I have searched a lot and can't seem to find what I am looking for.
I have a .js field, and I really need help with some php code in side it. I have no idea how to put them together and would really appreciate some help.
The Javascript code(This code is inside the js file):
<span class="gravatar"><img src="',params.gravatar, '" width="23" height="23" onload="this.style.visibility=\'visible\'" />
where the <img src="',params.gravatar,'">
I want to add:
<?php
$con=mysqli_connect("localhost","root","","facebook");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM login WHERE username='$username'");
$username = $_SESSION['username'];
while($row = mysqli_fetch_array($result))
{
echo $row['profilepic'];echo "<br>";
mysqli_close($con);
}
?>
Insted of ,params.gravatar,
I assume you mean that the HTML snippet you are posting is inside a separate JS file. If that is the case, you can assign the profile picture URL to a global JS variable in your PHP code:
Your PHP file:
<?php
// Your DB call code goes here...
?>
<script>
var profilePic = '<?=$row['profilepic']?>';
</script>
<script src="/your/jsFile.js"></script>
And in your jsFile.js:
var img = '<span class="gravatar"><img src="'+profilePic+'" width="23" height="23" />';
If what you want was even possible, an attacker could just change your queries and execute them directly from javascript. That would be funny, but not very good in the end for developers.
What you should look for is asking javascript (through JQuery) to query the php code and from PHP do your queries and return the results to the javascript in JSON format.
Look up $.post in JQuery.
I really need help with some php code in side it
No web server is executing PHP code inside a .js file per default, you have to create a .php file so your web server is executing the file's content. So this won't work without extra server setup, you need a different setup. I'm sorry…
Related
I have a file which is of php type. And I have a combination of HTML elements, javascript functions and some PHP scripts as well. I want to rerun the php script say some part of the script again and again. lets take this example:
<html>
<?php
$connection = mysql_connect('localhost','root','root');
$db = mysql_select_db('messenger');
if ($db == null)
{
echo "hello";
}
$messagecheck = "select * from Messages where destination = '$user' && status = 'ACTIVE'";
$result = mysql_query($messagecheck);
$no_rows = mysql_num_rows($result);
............
?>
<body>
........
<form>
<input type="submit">
.......
</form>
</body>
</html>
I want to run the above php script continuously for every 1 min from the same file. When I make use of location.reload() I find that complete document gets reloaded. I just want the affect the part of the page which php script accesses and not the whole doc.
How can I do that? Please help.
You can't do that out of the box, since php is called when the page is loaded.
You should take a look at Ajax or frameworks like JQuery, that embed Ajax.
As previously said by blue112 you need to use Ajax in order to get what you want.
If I did understand well what you need, a simple solution is using an iframe where you point to a file with only the php code you want to execute, and reload it every time you want.
I hope this helps
hi i am new to all html javascript and php. this is suppose to save the input from a html form to my database... but i have no idea why this doesnt work... the code dosent seem to go into the php section to execute the command...
kindly advise thank you
<html>
<script type = "text/javascript">
function processInputs()
{
//get data from html form
var email_data;
email_data=document.getElementById('txtInput').value;
//document.write(email_data);
<?php
//connect database
$con = mysql_connect("localhost","admin","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("internet", $con);
$newemail = $_GET['email_data'];
echo $newemail;
//query
mysql_query("INSERT INTO user_data (email) VALUES ($newemail)");
mysql_close($con);
?>
}
</script>
<FORM action="test.php" method="post">
<INPUT type="text" value="this is a text" name"txtInput" id="txtInput" />
</FORM>
<button type="button" onclick=processInputs() >click!</button>
You have multiple flaws:
you cannot "embed" like that a PHP script into a javascript function, for that you should use AJAX - try jQuery. PHP is server side, Javascript is browser based.
You have a MySQL injection hole there, you should escape your $_GET with mysql_real_escape_string()
Stop using mysql_* as those functions are deprecated. Read this article
onclick is invalid, it should be <button type="button" onclick="processInputs()">click!</button>
If you have a perception that -
On calling the js function on some user actions such as button click/hover, etc would trigger the php code and populate the data,
then YOU ARE WRONG.
PHP is a server side scripting language, and you can't use it this way. The complete page is parsed at the server end and given as response to the browser. To do dynamic updates use Ajax calls that would call a php page and populate the html for you.
I suggest refer the coredogs.com site for better understanding of php flow.
your function is not being called !!!
Change this
onClick = processInputs()
to
onClick = "processInputs()"
and try for an alert statement to see if function is being called or not
Also you cannot have php script within script tag
I want to display the photos according to the album selected. But, I don't want to post the page, I want to just change the div.
This is my script:
<script type="text/javascript">
function replaceContent(divName, contentS) {
document.getElementById(divName).innerHTML = <?php echo get_pictures_from_album($fb, $albums, contentS); ?>;
}
</script>
And this is the select tag that invokes it:
<select name="album" size= "1" style="width:210;" onchange="replaceContent('photos', this.options[this.selectedIndex].value);">
<?php get_albums_select_list($albums); ?>
</select>
<div id = "photos">
<?php echo get_profile_pictures($fb, $albums); ?>
</div>
I understand from a reading that I have done that the problem might be connected to javascript Vs php variable types.
Please advise.
Looks like you are looking for an AJax call to an PHP script that retrives the data for the appropriate album selected and THEN update the div with the callback function.
Ajax + PHP basics
You are mixing Clientside and Serverside Code here. The function replaceContent is called after the page (and the php code) was loaded. You would need an Ajax Call for that if you need more information about that:
Ajax Tutorials on Google
What you are doing is not possible because PHP code runs before (on the server because PHP is server-side language) javascript code.
You will have to resort ot AJAX for that.
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 .
Anybody have any idea how I might go about doing something like this.
I've got a textarea setup to allow users to edit page content. the content is then stored in a database and is retrieved on the frontend by php within an html template. something like:
<html>
yada yada...
<?php
echo get_page_contents_by_id($_GET['id']);
?>
yada yada...
</html>
its all run in a .php file, in case anyone wanted to call that out.
What I'm wondering is, because I'm getting the content from the database via php, is there any way that I can retrieve php code within that content and still run it without doing any sort of file writing.
You can use the PHP eval() method to execute the PHP code returned from the database - just as if it was actually written in your PHP file directly.
e.g.
<?php
eval("echo('hello world');");
?>
Prints:
hello world
You can use eval for this purpose.
http://php.net/manual/en/function.eval.php
eval() is as James Goodwin and Gazler say in fact the only way to execute PHP code from string data.
In addition to the security consequences - it will become possible to compromise your whole web site by gaining access to your mySQL data - this approach will make code very hard to debug, as you will have to follow all error messages through the eval()d code.
I attempted to do this same thing, but with the addition of tags and normal HTML tags. This will not work. If you need to store HTML along with your PHP, consider a more XHR solution that relies less on PHP code for every page.
Consider another alternative. Really.
Regardless of any security checks you do, function parsing, etc., this is still an EXTREMELY bad idea.
A slightly less bad idea, why not look into a templating solution like http://www.smarty.net or http://www.google.com/search?q=php+template+engine
Below is the code to execute the code in textarea.
<?php
if($_POST){
print_r($_POST);
extract($_POST);
$file = rand(1000,10000); // creating file with random number
file_put_contents($file.'.php', '<?php '.$code.' ?>');
ob_start();
include $file.'.php';
echo ob_get_clean();
unlink($file.'.php'); // deleting the created file after execution.
die('test');
}
?>
<textarea id="testcode" ></textarea>
<input type="submit" onClick="return changePermissions1()" />
<script>
function changePermissions1(){
var code = {};
code['code'] = $("#testcode").val();
var pass_url = "executefile.php"; // there you can pass the code
$.ajax({
type : "POST",
beforeSend : loadingStarts,
url : pass_url,
data : code,
success : function(responseText){`enter code here`
loadingEnds();
alert(responseText);
}
});
}
</script>