Execute a php function with field value after it has been entered - php

I have a form that ask the email of the new user. I got a php function that can use this email to get informations (firstname, lastname, office, job...) using a cURL request and return it into an array ($full_informations).
I want this function to be executed after an email has been entered. For different reasons, I cannot directly add code to my form, so I need something can be read somewhere else in the body or the head.
I got this field that is automatically populated by a script:
<input onKeyPress="" class="editingSize " type="text" id="emails" name="emails" size="" value="" maxlength="150">
I want to be able to send the value of this field to a php function such as
$full_informations = get_more_info_from_mail($email)
then I could do something like
$firstname = $full_informations['firstname'];
$lastname = $full_informations['lastname'];
$job = $full_informations['job'];
//...
and make these variables automatically inserted in my mysql DB without asking the user to complete the form (I know how to make that part).
So, again, my question is, how can I get my function to be called with the value of the field after the user has entered an email?
I suppose I'll need some ajax request but I'm not familiar with those at all.

Are you using a mysql database. You can achieve this in php like this:
Put this at the beginning of you page
<?
if (isset($_POST['submit'])) {
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$mail = $_POST['mail'];
$result = mysql_query("SELECT * FROM users WHERE email = $mail");
$row = mysql_fetch_row($result);
$firstName = $row[0]; //FirstName
$lastName = $row[1]; //LastName
$job = $row[2]; //Job
}
?>
You html should look like this:
<form action="" method="POST">
<input type="text" name="mail" />
<input type="submit" value="submit" name="submit" />
</form>
Hope this helps!

With jquery:
<script type="text/javascript">
$(function() {
$('#emails').on('blur',function() {
$.post('/path/to/your/php.php',
{email: $('#emails').val()},
function(json) {
alert('responded with '+json.response);
});
});
});
</script>
Your php script should look like this:
<?php
$email = $_GET['email'];
// make sure you verify the email is in a correct format.
// save it to a database
//if it succeeds:
echo json_encode(array('response'=>'success'));
//if it fails:
echo json_encode(array('response'=>'failure'));

Related

Get contents of form and then add on to url with php

I have found a stack overflow answer that shows me how to get the number of followers from Instagram. Basically, it adds the username onto the URL. I want to be able to get that username from an input box and then add it to the url.
$raw = file_get_contents('https://www.instagram.com/USERNAME'); //replace with user
preg_match('/\"edge_followed_by\"\:\s?\{\"count\"\:\s?([0-9]+)/',$raw,$m);
print intval($m[1]);
Right now I'm thinking of replacing the username with $_GET and connecting that to my form. How do I pull off this? Thanks.
Do this: in file.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit'])){
$username = $_POST['username'];
//check if length of username is greater 3
if (strlen($username) < 3)
echo "Kindly enter a valid username";
else{
$url = "https://www.instagram.com/".$username;
$raw = file_get_contents($url, false, null, 0, 100);
}
}
?>
In Your HTML file
<form method="POST" action='file.php'>
<label for='username'>Enter Username</label>
<input type='text' required name='username' id='username' />
<input type='submit' value='Submit' name='submit' />
you may try this code. I encode all the result via json from instagram.
method:
1. Get username from html
2. perform a json decode on file get contents
3 output the result and try on your browser.
if(isset($_POST['submit'])){
$username = $_POST['username'];
$url = 'https://www.instagram.com/'.$username;
$jsonData = json_encode(file_get_contents($url));
echo $jsonData;
// you may extend your code from here to achieve what you wanted
}
Hope this code might help you.

Search-engine: Php get data from anchor-tag

I have this html search here:
<form action="index.php" method="POST">
<input id="search" type="text" placeholder="Search for Friends" name="search_name">
<input class="submit" type="submit" name="search-submit" value="Search">
</form>
And this php code for the search engine:
<?php
if (isset($_POST['search-submit'])) {
$search_name = $_POST['search_name'];
$aVar = mysqli_connect('localhost','root','','socialnetwork');
$result = mysqli_query($aVar, "SELECT username FROM users WHERE username LIKE '%$search_name%'");
$found = 1;
while ($row = mysqli_fetch_assoc($result)) {
$username = $row['username'];
#$output .= '<h2 class="friends-display">'.$username.'</h2><hr>';
}
}
?>
Now this code is working fine. It allows the user to search for other users.
The anchor tag "friends-display" shows the result of the code by using the variable $output. The $output is then echoed later in the aside.
My problem is the following: I want to make an if-statement so when the anchor tag "friends-display" is clicked by the user it should show the profile of the username the user has clicked on.
Example: you search for Mike and you find this username. Than you click on it and it should show the profile of Mike. How can I make this with an anchor tag?
I have tried if isset(), but it did not work for me.
Change the output variable like below
....
while ($row = mysqli_fetch_assoc($result)) {
$username = $row['username'];
#$output .= '<h2 class="friends-display">'.$username.'</h2><hr>';
}
....
Create a new file profile.php and add the following basic line.
<?php
If(isset($_GET['user']) && !empty($_GET['user'])){
$username = $_GET['user'];
// check for username found in database.
// if not found exit with error "user not found"
// else show user profile
}else{
Die("unothrized access");
}
I hope this will guide you to achieve your target..
Happy coding :)

Validating form and sending a confirmation email on submission

I am creating an admin page, where the admin person can create users accounts for people. The idea is, that once the form is completed, when clicking 'Submit' an email must be sent to the user (containing the ID and name of account selected). In the same action, the form must also first be validated and if there are any errors with the validation the data should not be submitted to the database. None of this is happening though and I cannot figure out why.
The email is not being sent,
the data is inserted in the database even if there are errors and upon loading the page,
errors are displayed for all form fields even though the submit button have not been clicked.
Any help, advice or links to possible sources/tutorials would be greatly appreciated.
Below is my code: (Note that I am only working in PHP, HTML and using a MYSQL database)
<html>
<head>
<title>
User Registration
</title>
<?PHP
include_once 'includes\functions.php';
connect();
error_reporting(E_ERROR | E_PARSE);
//Assign variables
$accounttype=mysql_real_escape_string($_POST['accounttype']);
$sname = mysql_real_escape_string($_POST['sname']);
$fname = mysql_real_escape_string($_POST['fname']);
$email = mysql_real_escape_string($_POST['email']);
$address = mysql_real_escape_string($_POST['address']);
$contact_flag = mysql_real_escape_string($_POST['contact_flag']);
//Validating form(part1)
$error='';
//Connect to database
$SQL=
"INSERT INTO student
(
sname,fname,email, address, contact_flag
)
VALUES
(
'$sname', '$fname', '$email', '$address', '$contact_flag'
)
";
if (!mysql_query($SQL))
{
print'Error: '.mysql_error();
}
mysql_close($db_handle);
//Validate form(part 2)
if (isset($_POST['sname'], $_POST['fname'],$_POST['email'],$_POST['address']));
{
$errors=array();
$accounttype= mysql_real_escape_string($_POST['accounttype']);
$sname = mysql_real_escape_string($_POST['sname']);
$fname = mysql_real_escape_string($_POST['fname']);
$email = mysql_real_escape_string($_POST['email']);
$address = mysql_real_escape_string($_POST['address']);
$contact_flag = mysql_real_escape_string($_POST['contact_flag']);
// form validation
if(strlen(mysql_real_escape_string($sname))<1)
{
$errors[]='Your surname is too short!';
}
if(strlen(mysql_real_escape_string($fname))<1)
{
$errors[]='Please insert you full first name';
}
if(filter_var($email, FILTER_VALIDATE_EMAIL)===FALSE)
{
$errors[]='Please insert your valid email address';
}
if(strlen(mysql_real_escape_string($address))<8)
{
$errors[]='Please insert your postal address';
}
echo'<pre>';
print_r($errors);
echo'</pre>';
}
//confirmation email
// Subject of confirmation email.
$conf_subject = 'Registration confirmed';
// Who should the confirmation email be from?
$conf_sender = 'PHP Project <my#email.com>';
$msg = $_POST['fname'] . ",\n\nThank you for registering. \n\n You registered for account:".$accounttype."\n\n Your account number:".mysql_insert_id;
mail( $_POST['email'], $conf_subject, $msg, 'From: ' . $conf_sender );
?>
</head>
<body>
</br>
<form name ="form0" Method="POST" Action="<?PHP echo $_SERVER['PHP_SELF']; ?>">
</br>
</br>
<b>Select the course you wish to register for:</b></br>
<select name="accounttype">
<?PHP query() ?>
</select>
<?PHP close() ?>
</form>
<form name ="form1" Method="POST" Action="<?PHP echo $_SERVER['PHP_SELF']; ?>">
</br>
</br>
<Input type ="" Value = "Surname" Name = "sname"></br>
<Input type ="" Value = "First name" Name = "fname"></br>
<b>Email:</b> <Input type ="" Value = "" Name = "email"></br>
<b>Address:</b> </br>
<textarea rows="4" cols="20" Name="address">Please provide your postal address here </textarea></br>
<b>Tick to receive confinmation email:</b> <Input type ="checkbox" Value = "1" Name = "contact_flag"></br>
<Input type = "Submit" Value="Submit">
</form>
</body>
</html>
<?PHP
if(isset($_POST['submit']))
{
include_once 'includes\functions.php';
connect();
// your rest of the code
mail( $_POST['email'], $conf_subject, $msg, 'From: ' . $conf_sender );
}
?>
and keep this code out of the <html> tag but before it
and if you want to stick to PHP only then one error i can see is
that you have kept the **validation code below the `INSERT`**
query which means that the insert query will be executed first which will store the data in the database first and then it will go for the validation...so keep your validation code above the INSERT statement..
and second thing use exit() method after vaidating every field if it gives you error...it will stop executing rest of the php code if any field gives the error during validation....and so it will also prevent the data from storing into the database if it finds exit method whenever an error is found eg
if(strlen(mysql_real_escape_string($sname))<1)
{
$errors[]='Your surname is too short!';
echo '//whatever you want to echo';
exit();
}
if(strlen(mysql_real_escape_string($fname))<1)
{
$errors[]='Please insert you full first name';
echo '//whatever you want to echo';
exit();
}
At first, your query gets executed before you validate your form.
Move your SQL after your
echo'<pre>';
print_r($errors);
echo'</pre>';
and surround it with
if(!$errors){}
This will prevent your query from being executed if there are any errors.
(You can also delete your first assignement of your variables)
Concerning your email problem, test your connection with a simple message
mail('your#email.com', 'subject', 'message');
If you get any error, probably your mailserver isn't set up right

PHP Form must be submitted twice to update checkbox

I'm still relatively new to PHP. I'm trying to build a privacy settings page for members to opt out of automatic emails for triggered events (i.e. private message notification). I want the checkbox set automatically based on the database setting. As of now, the form does update the database correctly, but the checkbox status does not show the correct setting unless the Submit button is pressed twice, or the page is reloaded. Setting would be '0' for unchecked, '1' for checked. I'd love to use Ajax or jQuery to handle this, but I don't know those at all.
privacysettings.php
<?php
$id = "";
$pm_mail_able = "";
$pm_email = "";
if (isset($_GET['id'])) {
$id = preg_replace('#[^0-9]#i', '', $_GET['id']); // filter everything but numbers
} else if (isset($_SESSION['idx'])) {
$id = $logOptions_id;
} else {
header("location: index.php");
exit();
}
//query to get checkbox status
$sql = mysql_query("SELECT * FROM members WHERE id='$id'");
while($row = mysql_fetch_array($sql)){
$pm_mail_able = $row['pm_mail_able'];
}
switch ($pm_mail_able) {
case 0:
$pm_setting = NULL;
break;
case 1:
$pm_setting = "checked=\"checked\"";
break;
}
if(isset($_GET['pm_email']) && !empty($_GET['pm_email'])) {
$updateqry = mysql_query("UPDATE members SET pm_mail_able='1' WHERE id='$id'");
} else {
$updateqry = mysql_query("UPDATE members SET pm_mail_able='0' WHERE id='$id'");
}
?>
<html>
Email Notifications<br />
<form name="testform" method="get" action="PvResult.php">
When a friend sends me a private message
<input type="checkbox" name="pm_email" value="on"<?php echo $pm_setting;?> />
<br /><br />
<input type="submit" value="Submit" />
</form>
</html>
PvResult.php
<?php
$url = 'http://www.mywebsite.com';
//If the form isn't submitted, redirect to the form
if(!isset($_GET['Submit']))
header('Location: '.$url.'/privacysettings.php');
//Redirect to the correct location based on form input
$pm_email = $_GET['pm_email'];
$url .= '/privacysettings.php?pm_email='.$pm_email;
header('Location: '.$url);
?>
Okay, hopefully this won't just answer your question, but give you a few best practices you might want to consider.
You can combine these two scripts into one relatively easily. Also, I'd highly suggest using a POST instead of GET; GET is very limited and is not intended to submit data like you're using it. If you're going to be changing data in a back-end store, using GET will bite you. Maybe not today, maybe not tomorrow, but it will, trust me.
You really should consider moving to PDO instead of the mysql_ functions. PDO is a lot better in handling parameterized queries, which you really should have here for better security, and it's more portable if someday you want to move to a different database system.
I'm still a little hazy on how your app is getting the $id. Most apps get it from a $_SESSION variable, making sure that the user has successfully validated a login. If you're not doing that, please do. You might want to thoroughly digest this article, it's got a lot of juicy best practices regarding authentication and "remember me"-type functionality.
Here's a bit of a rewrite. I haven't actually tested it, but it should give you a pretty good idea on where to go with your immediate needs. If it throws any errors (remember the disclaimer: I haven't actually tested it!), let me know and I'll try to debug it.
<?php
$message = '';
$pm_setting = '';
$id = 0;
// Put your $id retrieval logic here. It should look something like:
if (isset($_SESSION['id'])) {
$id = $_SESSION['id'];
if (!preg_match('/^\\d{1,10}$/', $id) > 0) {
// Someone is trying to hack your site.
header("location: scum.php");
exit();
}
$id = intval($id);
}
// Quick security note: You might want to read up on a topic called
// session hijacking if you want to ensure your site is secure and
// this $id isn't spoofed.
if (isset($_POST['Submit'])) {
// The form is being submitted. We don't need to read the current
// pm_mail_able setting from the database because we're going to
// overwrite it anyway.
if ($id > 0) {
$pm_mail_able = 0;
if (isset($_POST['pm_email']) && $_POST['pm_email'] === 'on') {
$pm_mail_able = 1;
$pm_setting = 'checked ';
}
$query = 'UPDATE members SET pm_mail_able='.$pm_mail_able.
' WHERE id = '.$id;
mysql_query($query);
// Another quick security note: You REALLY need to consider
// updating to PDO so that you can bind these parameters
// instead. The mysql_ functions are probably going to be
// deprecated soon anyway.
if (mysql_affected_rows($query) > 0)
$message = '<p style="color: #00a000;">Settings saved!</p>';
else
$message = '<p style="color: #a00000;">User id not valid.</p>';
}
else
$message = '<p style="color: #a00000;">User id not valid.</p>';
}
else {
// This is the first load of the form, we need to just display it
// with the existing setting.
if ($id > 0) {
$query = mysql_query('SELECT * FROM members WHERE id = '.$id);
if (($row = mysql_fetch_array($query, MYSQL_ASSOC)) !== FALSE)
if ($row['pm_mail_able'] === 1) $pm_setting = 'checked ';
}
}
?>
<html>
<body>
<?= $message ?>
<!-- Without action parameter, form submitted to this script. -->
<form name="testform" method="post">
E-mail notifications<br />
<input type="checkbox" name="pm_email" value="on" <?= $pm_setting ?>/>
When a friend sends me a private message
<br /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Try to do these settings and see if it will work:
1) You need to add an space between "on" and "checked=checked"
<input type="checkbox" name="pm_email" value="on" <?php echo $pm_setting;?> />
2) You have to reference the submit button by its name, not its value
<input type="submit" name="Submit" value="Send" />
3) When the setting is "0", set $pm_setting as a empty string, instead of NULL
case 0:
$pm_setting = '';
4) Maybe there is some problem with $_GET['pm_email'] and the else is always being executed
5) If the things work when you press the Submit button twice, it means that the form is passing some GET var that make the code work, so try to discover what var is this

Getting variable value from PHP with jQuery

So how do i get variable value from php file with jquery...?
the jquery code is in other file (tpl)
for example i have register.php and register.tpl (template file for register.php)
register.php
...some includes here...
if(isset($_POST['submit'])) {
$username = mysql_real_escape_string(trim($_POST['username']));
$email = mysql_real_escape_string(trim($_POST['email']));
$check = $mysql->query("SELECT username FROM ".TBL_USERS." WHERE username = '".$username."' OR email = '".$email."'");
$rows_check = mysql_num_rows($check);
if($rows_check > 0) {
echo 1;
} else {
$password = mysql_real_escape_string($_POST['password']);
$salt = generate_salt($email);
$hash = hash_password($password, $salt);
$q = $mysql->query("INSERT INTO ".TBL_USERS." (username, password, email, salt) VALUES ('".$username."', '".$hash."', '".$email."', '".$salt."')");
if($q) {
header("Location: index.php");
} else {
die(mysql_error());
}
}
} else {
.. calling parse template function ...
}
register.tpl
..jquery library included..
<form id="register" action="register.php" method="post">
<tr>
<td>Username</td>
<td><input type="text" id="username" name="username" class="register" style="width: 200px;" />
</td>
email
...other inputs...
$("#username").blur(function()
{
var email_v = $("#email").val();
$("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
$.post("register.php",{ username:$(this).val(), email: email_v, submit: true } ,function(data)
{
if(data=="1")
{
$("#msgbox").fadeTo(200,0.1,function()
{
$(this).html('This User name Already exists').addClass('messageboxerror').fadeTo(900,1);
});
}
else
{
$("#msgbox").fadeTo(200,0.1,function()
{
$(this).html('Username available to register').addClass('messageboxok').fadeTo(900,1);
});
}
});
});
</script>
when i changed the whole register.php for testing purposes to
or
the script worked...however with the original version it shows always that username is available...
Best bet is to output the PHP variable as a hidden field or a JavaScript variable:
<input type="hidden" id="my_var" name="my_var" value="<?php echo($my_var); ?>" />
// access it like this:
alert($('#my_var').val());
or
<script type="text/javascript">
var my_var = <?php echo($my_var); ?>;
</script>
// access it like this
alert(my_var);
That should do it :-)
Either you make a Jquery Ajax Request that will request a php page which will return whatever you want or you echo a javascript variable with php
<?php
echo '<script> var javascript_variable = "whatever"; </script>';
?>
It will work if you do
echo "1";
and then
if(result == "1") {
If it doesn't (but I've checked on a code of mine without the quotes, it didn't work, with, it was ok), check the response from Firebug console.
In situations where my company's application needs to call Jquery on a dynamic element and we have the Jquery call IN the php file we'll directly call php in the Jquery call.
For example:
alert($('#').val());
Not for all situations, certainly. If you have to call a variable where you don't have PHP access to the file (possibly such as a .tpl file, depending on your setup) you might resort to setting a hidden input as detailed above.

Categories