embedding php in javascript - php

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

Related

how to prevent php code to run when loading a page

Good day,
Although I'm an old programmer, I'm new to php, so I need help.
Context
1. I have a submit form with an update button.
2. I have php code to insert records in a MySQL database.
Problem
1. When I first start the page, the php code runs.
2. When I refresh the page, the php code runs again.
Code
<!-- Button definition -->
<input id="submit" type="submit" class="button" name="submit" value="submit" onclick="Update_MySQL()" />
<!-- Function to be executed by the onclick -->
<script>
<?php
function Update_MySQL() {
if(isset($_POST['submit']))
{
$sql = "MYSQL UPDATE STRING" ;
$MY_CONNECTION->query($sql) ;
}
}
?>
</script>
What I know
1. PHP runs on server and javascript on the browser (client)
2. PHP delivers data to the server when the page is launched or refreshed
Can anyone help me on this?
Many Thanks
You can't prevent this when using the native html <form action="form.php"> way, but there is a way around. After progressing your form, you can redirect using header() to another page (or even the same) with a GET-Redirection-Code (see wikipedia).
if (isset($_POST['field'])) {
// progress data
header('HTTP/1.1 303 See Other');
header('Location: '.$_SERVER['PHP_SELF']);
exit;
}
Another completely different but also working approach is to use javascript to submit your form data.

Can I call a PHP function in a JavaScript click handler?

I have a login system and I would like to introduce a feature where the user can change his email...
However if I click change the site reloads and nothing happens.
Here is the script in the function:
function changeemail($newemail, $mysqli) {
$sql="UPDATE members SET email = '$newemail' WHERE userid='$_SESSION[user_id]";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param();
$stmt->execute();
$stmt->close();
}
And here's the html part:
<form method="post" action="<?php echo esc_url($_SERVER['PHP_SELF']);?>">
<input type="text" id="newemail"><br>
<input type="submit" value="Ändern!" onclick="return changeemail(this.form,
this.form.newemail);"/>
</form><br>
Thanks in advance!
It is not possible to call a php function from a javascript onclick, because php is a serverside language and javascript a client side.
I don't need a function at all, because I can get the value, entered in the form, by POST.
Since php is server side you can not do that. But what you could do is use Javascript/jquery to load in a page onclick and then update the email
Then use Javascript to upload the page
$( "#result" ).load("yourpage.php");

How to make button to remove value in mysql field?

I am having difficulty making a button that removes existing values in MySQL database field. I have read up some information on it, some say use AJAX, but i'm not sure. What are your opinions? Can any Stackoverflow-er show me a method? I recognise I cannot use Javascript as it is on the client side and not server-side - but is there another way?
create form first in html
<form method="get" action="delete.php">
Enter id you want to delete : <input type="text" name="id">
<input type="submit">
</form>
delete.php
<?php
$dd=$_GET["id"];
$c=mysql_connect("localhost","root","");
mysql_select_db("mydatabase")
mysql_query("delete form mytable where id=$dd");
print "Remove successfully...";
?>
This upper code will remove the entries you want on clicking of submit button
If you want to remove the values from mysql database asynchronously then you'll need to use AJAX and that's the only option else if you are allowed to do it without refreshing the page then go with simple PHP.
you need not to do it with ajax if u dont want. simple php is good enuf..
just make a form with a button field.
post a variable though it to your php.
connect with your database using update the dtabase as you want..
Beware : One refresh would take place on this process as its not an asynchronous process. else you can choose AJAX
you could use a (post/get) request to a file on your server but i recommend you use AJAX to do this, the server side file will still look pretty much the same.
if you are using php for the back end the code would look like
$mysqli = new mysqli("localhost", "user", "password", "database");
$res = $mysqli->query('your delete statement');
if(! $mysqli->errorno )
header('Location:success url');
else
header('Location:fail url?error=' . $mysqli->error')
you could use a link for you button
<a class="button" href="script to delete">delete unwanted data</a>

PHP mysql inside Javascript

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…

How to submit a form on page load without clicking submit button?

Is there a way to make a form submit "onload" without clicking a
submit button with PHP? i saw some ways to make it with Javascript, but i love php and id like to make it with php.
For example:
<form action="https://xxxxxx.com/yyy.php" method="post" id="foo">
<input type="hidden" name="LoginEmail" value="user [at] domain.com">
<input type="hidden" name="LoginPassword" value="mycleartextpassword">
<input type="submit" name="Authenticate" value="Login">
<input type="hidden" name="Action" value="1" >
</form>
I can make it with javascript:
<form id="foo"> .... < /form>
<script type="text/javascript">
function myfunc () {
var frm = document.getElementById("foo");
frm.submit();
}
window.onload = myfunc;
</script>
Well, Can we make same thing with PHP? Could you please kindly share your ideas and advices?
Thank you.
It isn't possible to carry out a client-side (i.e.: browser based) form submit action using a server side language (i.e.: PHP). It's a bit like trying to get a library to read a book, if that makes sense. (You get the books from the library and return them there, but the library itself can't read books.)
As such, JavaScript is your only solution if you require an automated submission. Even then, you need to ensure there's a "normal" solution for use by people who don't have JavaScript enabled. (The joy of graceful degradation, etc.)
i had diffculty in dong this as well so thought i would post my solution here it goes...
this curl command posts the file to a url and send back any data it receives. It's posting an xml file which is why the content type is set to application/x-www-form-urlencoded.The api i was posting to requested that the data be encoded which is why I use --data-urlencode. I also assign the filename with a post variable name here so its like posting an input field with a name="whatever".
curl --data-urlencode [post variable name]=#[filename] --header "Content-Type:application/x-www-form-urlencoded" http://[url to send file to]
Assigning the command to a variable is easy...see below
'
content=$(put curl command in here);
P.s DO NOT FORGET TO ESCAPE ANY '=' or '&' in your url's, this causes issues if you're trying to retrieve data.
If you want to auto-submit form after page load (IMHO it's pointless) I assume you generated its values by yourself (by PHP code) and you want to send them to another page, right? If so redirect page to the another by header() passing values through POST:
$post_data = 'LoginEmail=username [at] domain.com&LoginPassword=...';
$content_length = strlen($post_data);
header('POST /another_page.php HTTP/1.1');
header('Host: fancyhost');
header('Connection: close');
header('Content-type: application/x-www-form-urlencoded');
header('Content-length: ' . $content_length);
header('');
header($post_data);
exit();
it is by using jquery ajax.
$(document).ready(function(){..........your code goes here........});
if you prefer jquery replay me i wll give you the help
Use printf to print your javascript code then when the client browser receives the page it will execute your javascript.
printf("<script type="text/javascript">
function myfunc () {
var frm = document.getElementById("foo");
frm.submit();
}
window.onload = myfunc;
</script>");
I do this a lot for the mapping services.

Categories