Submit -> Execute PHP script -> Alert User -- while staying on same page - javascript

I have a page with two submit buttons using if ($_POST['action'] == 'Test SMS') to executed code for my "Test SMS" button. I need to execute code from a PHP script then give an alert box while not leaving the page.
index.html
<form action="updateUserConfig.php" method="post">
<input type='submit' name='action' value='Test SMS' class='btn-test'>
<input type="submit" name="action" value="Save" class="btn btn-primary">
</form>
updateUserConfig.php
if ($_POST['action'] == 'Test SMS') { //action for Test SMS Button
//grab ntid and phone from header
if(isset($_POST['ntid'])) $ntid = $_POST['ntid'];
if(isset($_POST['phone'])) $phone = $_POST['phone'];
//using the notify_sms_users funtion from send_notification.php
require 'send_notification.php';
notify_sms_users(array($ntid), "", 4);
//alert user that there message has been sent
$alert = "Your message has been sent to " . $phone;
echo '<script type="text/javascript">alert("'.$alert.'");';
echo '</script>';
header('Location: index.php');
} else {-----action for other submit button------}
I asked a similar question that was marked a duplicate at Alert after executing php script while not leaving current page but was able to come up with a solution so I wanted to share.

I was able to accomplish this by adding a URL query string in my header('location: index.php?text=success) function then using JS I was able to use an if statement to look for the query string and alert if so.
index.html
<form action="updateUserConfig.php" method="post">
<input type='submit' name='action' value='Test SMS' class='btn-test'>
<input type="submit" name="action" value="Save" class="btn btn-primary">
</form>
<script type="text/javascript">
$(document).ready(function () {
if(window.location.href.indexOf("settings=success") > -1) {
alert("Your settings have been saved");
}
else if(window.location.href.indexOf("text=success") > -1) {
alert("A SMS has been sent!");
}
});
</script>
updateUserConfig.php
if ($_POST['action'] == 'Test SMS') { //action for Test SMS Button
//grab ntid and phone from header
if(isset($_POST['ntid'])) $ntid = $_POST['ntid'];
if(isset($_POST['phone'])) $phone = $_POST['phone'];
//using the notify_sms_users funtion from send_notification.php
require 'send_notification.php';
notify_sms_users(array($ntid), "", 4);
header('Location: index.php?text=success');
} else {-----action for other submit button------}
header('Location: index.php?settings=success');
The only downside to this solution is that I don't have easy access to my PHP $phone variable to tell the user what number the message was sent to.

AJAX is the method most suited to this job, because what you are trying to achieve is a frontend interaction. Php is a server side language.
AJAX will transmit form data to the backend php script. Once the the php script has handled the data on the server, it can return the data you require to the AJAX script. This is done sometimes using JSON, especially as you have multiple variables.
$formdata = array(
'ntid' => $_POST['ntid'],
'phone' => $_POST['phone']
);
return json_encode($formdata);
The returned JSON code will look something like:
{"ntid":"NT ID","phone":"Phone number"}
Tutorials similar to this are very useful:
[http://www.yourwebskills.com/ajaxintro.php][1]
I have found that taking a break from your main project and investing a little time in learning the mechanics behind what your trying to achieve, enables you to solve your problem faster.

Related

php mail() to send sms

I built a very small simple php() mail app to send sms messages to my staff from our portal. Strange thing is, it was working fine this morning, tested it on and off for a couple of hours, everything was fine. Then I left for the afternoon, came back and went back to make sure everything was still intact, and all of a sudden, the sms stopped working. Nothing was changed, the code was identical, I even re-uploaded the back-up I had from when it was working. Here is what I know:
The send_sms.php works fine if I run it straight from the browser, I just get an empty message, but everything else is there.
I have additional scripts in the page to display an error or success message, which it doesn't do either of, also a snippet to clear the textarea when submitted, they have all stopped working. I have researched this for hours, tried re-writing the send_sms.php, and the js, but can't get it to respond at all. So here is what I have:
HTML
<form id="sendsms" name="sendsms" method="post" action="send_sms.php">
<p>
<textarea name="text" cols="45" rows="5" id="text" maxlength="130" placeholder="Type your Text here, 130 characters max" required="required"> </textarea><div class="res4 text-muted" id="charNum"><small></small></div>
</p>
<button type="submit" id="test" name="submit" class="btn btn-warning btn- sm">Send SMS</button>
<div class="formsuccess" id="sendsmsResponse">
</div>
</form>
here is the js
$("#sendsms").submit(function(event)
{
event.preventDefault();
var $form = $( this ),
$submit = $form.find( 'button[type="submit"]' ),
message_value = $form.find( 'textarea[name="text"]' ).val(),
url = $form.attr('action');
var posting = $.post( url, {
text: message_value
});
posting.done(function( data )
{
$( "#sendsmsResponse" ).html(data);
$submit.text('Your text was sent.');
$submit.attr("disabled", true);
$('#sendsms')[0].reset();
setTimeout(function() {
$('#sendsmsResponse').fadeOut();
$('#text').val('')
}, 10000 );
function enableButton(){
$('#test').attr("disabled", false);
$('#test').text('Send Text');
}
setTimeout(enableButton, 10500);
});
});
and here is the mail script
<?php
$text = $_POST['text'];
$to = "**********#vtext.com";
$subject = "Support";
$message = "$text";
$from = "*****#**********.net";
$headers = "From: $from";
if (mail($to,$subject,$message,$headers))
{
echo "<h5 class='alert alert-success res4'>Your text has been sent. We will respond soon.</h5>";
}
else
{
echo "<h5 class='alert alert-danger res4'>Your text has NOT been sent. Please try again.</h5>";
}
?>
I just can't for the life of me figure out what happened to make it stop working, I have been trying to fix it for hours
I found the culprit, was just plain stupidity on my part. I added a small login form to my nav header, which I have as a php include on the page with the text submit form, and it was using the same <button type="submit">that I have on the sms form, as soon as I moved the login out of the header, everything worked fine. I'm an idiot, thanks for your input, I'll be sure to look everywhere next time.

php function to display which field is not filled in

I have a simple JavaScript function that will not allow a form to be submitted if all the fields are not filled out. On top of that I would like PHP to write out an error message next to just the fields that are empty. The problem is the function activates upon the $_POST and yet my JavaScript function will not allow for $_POST to occur as long as one of the fields are empty.
If I keep the action outside of the $_POST condition then the page will load with the error message already showing. I am fairly new to PHP and JavaScript and would like any insight on perhaps another available condition that I could use to trigger my error messages to appear in my form. I am also open to any other suggestions for error handling. I do prefer to keep my JavaScript present due to it's ability to keep the form from being submitted if it is not properly filled. Unless there is another way to take that action then I have to keep the JavaScript.
PHP:
function cleanCrew ($id, $pswrd) {
$id = stripslashes($id);
$pswrd = stripslashes($pswrd);
$id = strip_tags($id);
$pswrd = strip_tags($pswrd);
return array($id, $pswrd);
}
require_once 'dbServ.php';
$db_server = mysqli_connect($db_host,$db_user,$db_pass,$db_base);
if ($db_server) {
$error_1 = "";
} else{
$error_1 = "connection to database unsuccessful";
}
$error_2 = "";
$error_3 = "";
if ($_POST) {
$user_id = mysqli_real_escape_string($db_server, $_POST['userId']);
$user_pass = mysqli_real_escape_string($db_server, $_POST['pass']);
$id_and_pass = cleanCrew($user_id, $user_pass);
if ($user_id == "" || $user_id == null) {
$error_2 = "please fill in proper User Id";
} else{
$error_2 = " ";
}
if($user_pass == "" || $user_pass == null){
$error_3 = "please fill out password";
} else{
$error_3 = " ";
}
echo $id_and_pass[0];
echo $id_and_pass[1];
}
HTML:
<div id="intro">
<h1 id="the_blog" align="center">The <span id="blog_animate" style="position:relative;">Blog</span></h1>
<div id="log-in"><p id="log">Log In</p><br> <?php echo $error_1; ?>
<form action="blog.php" method="post" onsubmit="return checkForm(this)" name="form1">
<p id="log">User ID :</p> <input type="text" placeholder="johnnyApple175" name="userId"></input><?php echo $error_2 ?><br>
<p id="log">Password:</p> <input type="password" name="pass"></input><?php echo $error_3; ?><br>
<input type="submit" value="submit" class="button" ></input>
</form>
First:
It's always a very good idea to validate the data server side, like you're doing.
Reason is simple: Javascript is client-side and can easily be modified to e.g. bypass those checks. Also, good that you escaped the sent data prior using it in the Database query.
Your problem is, that you're checking for $_POST to exist - it always exists, it's a super global var. You actually want to check if it's empty:
if (!empty($_POST))...
You might want to think over it, if you really want to give detailed information what exactly was wrong. Giving more info is more user friendly, but it makes attacks easier, especially if you don't block the user after X retries.

jQuery Mobile submit with PHP without AJAX and JavaScript

Sorry, I consider myself as a real newbie around jQuery Mobile. I'm not good at all regarding JavaScript. Here's the thing. I want to build a jQuery Mobile site without using AJAX. Just want the nice design from jQuery Mobile and then use PHP to submit forms etc.
I tried to build a simple page that submit first and last name to a MySQL database. It will submit, tell the user that it's submitted and then the user can press [Page 2] to see all the results. Now I use if(isset()) to display the message and else to display the form. So, the user who enter the site will get the form, when press [Submit] he/she will get the message that first and last name was submitted. Then press the button [Page 2] to see all the first and last names.
PHP (index.php)
if(isset($_POST['send'])) {
$insert = $db->prepare("INSERT INTO name (fname, lname) VALUES(:fname, :lname)");
$insert_array = array(
":fname" => $_POST['fname'],
":lname" => $_POST['lname']
);
$insert->execute($insert_array);
$db = NULL;
echo $_POST['fname'] . ' ' . $_POST['lname'] . ' was added!<br><br>';
}
else {
echo '
<form method="post" data-ajax="false">
First name:
<input type="text" name="fname"><br>
Last name:
<input type="text" name="lname"><br>
<input type="submit" name="send" value="Add">
</form><br>';
}
Page 2
PHP (page2.php):
$query = $db->query("SELECT * FROM name");
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo $row['fname'] . ' ' . $row['lname'] . '<br>';
}
$db = NULL;
echo 'Index';
Let's say I enter "Test" as first and last name. It will echo out "Test Test was added!". If I now press [Page 2] I will see that "Test Test" was added. BUT when I then press [Index] to go back I want it to display the form again, but the message "Test Test was added!" is displayed again instead of the form, why? I have to update the page to get the form. Now, if I enable data-ajax it's working with submitting and back-button. BUT then I have to press update at page2.php when I get there to see all the first and last names. Do I make myself understood what's the problem?
Sorry, really new at jQuery Mobile and I can't find the answer at Google. Everyone is using JavaScript to submit data. Is it possible this way or do I have to learn JavaScript to submit forms? Read somewhere that using buttons instead of submit-buttons affect it.
Thanks in advance! :)
I think you are looking to modify the DOM after the request? So post the form, add the user then display the results without having to click the button.
So on your ajax call use the done function to hide the form and show the results.
Take a look below and let me know if it helps.
EDIT: Added the .on click for the button. You may also want to look at adding a keypress checker to the inputs or an onsubmit on the form.
<div id="content">
<?php
if(isset($_POST['send'])) {
$insert = $db->prepare("INSERT INTO name (fname, lname) VALUES(:fname, :lname)");
$insert_array = array(
":fname" => $_POST['fname'],
":lname" => $_POST['lname']
);
$insert->execute($insert_array);
$db = NULL;
echo $_POST['fname'] . ' ' . $_POST['lname'] . ' was added!<br><br>';
}
else {
echo '
<form method="post" data-ajax="false" id="contentForm">
First name:
<input type="text" name="fname"><br>
Last name:
<input type="text" name="lname"><br>
<input type="submit" name="send" value="Add" id="sendButton">
</form><br>';
}
?>
</div>
<script type='text/javascript'>
<!-- https://api.jquery.com/jQuery.ajax/ -->
$('#sendButton').on("click", function(){
$.ajax({
type: "POST",
url: "page2.php",
data: $('#contentForm').serialize()
})
.done(function( msg ) {
$('#content').html( msg );
});
});
</script>

How to display php form validation errors beside the form?

i have created a signup form which is validated by both javascript and php.Whenever any javascript form validation error occur such as username is required,it is displayed beside the form,But when any php validation error occur such as username already exist,it is displayed on another link.How can i display php validation errors beside the form?
<?php
include('configdb.php');
if(isset($_POST['submit']))
{
checks if the username is in use
if (!get_magic_quotes_gpc()) {
$_POST['username'] = addslashes($_POST['username']);
}
$usercheck = $_POST['username'];
$sql1 = "SELECT username FROM users WHERE username = '$usercheck'";
$result1 = mysqli_query($mysqli,$sql1) or die(mysqli_error());
//if the name exists it gives an error
if (mysqli_num_rows($result1) != 0) {
die('Sorry, the username '.$_POST['username'].' is already in use.');
}
}
Another option if you don't want to use ajax. It can be done with php but user need to reload the page to see error.
To do this, html form code and php validation code must be placed at the same file.
<?php
$error = false;
if(isset($_POST['submit'])){
// your validation
// if something wrong
$error = true;
}
?>
<form action="validation_checking.php" method="post">
<?php
if($error)
{ echo '<p style="color:red;">Sorry, the username '.$_POST['username'].' is already in use.</p>'; }
?>
<input type="text" name="username">
<input type="submit" value="submit">
</form>
You must use ajax to execute php functions without refreshing the page.
Read this

Extract uid from Facebook Connect with php

I would like to extract the users facebook-id and put it into a php-variable.
The code I'm using is from a facebook tutorial video, and its working. I just want to be able to use the user id in a php code.
This is my code:
<form action="" method="post">
<div id="user">
Name: <input name="name" size="27" /><br />
<fb:login-button length="long" onlogin="update_user_box();"></fb:login-button>
</div>
<textarea name="comment" cols="30" rows="5"></textarea><br />
<input type="submit" value="Submit comment" />
</form>
<script type="text/javascript" src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php"></script>
<script type="text/javascript">
function update_user_box() {
var user_box = document.getElementById("user");
user_box.innerHTML =
"<span>"
+"<fb:profile-pic uid='loggedinuser'></fb:profile-pic>"
+"Welcome, <fb:name uid='loggedinuser' useyou='false'></fb:name>. "
+"You are signed in with your Facebook account."
+"<fb:uid uid='loggedinuser'></fb:uid>"
+"<a href='#' onclick='FB.Connect.logout(function() { reload(); }); return false;' ><img id='fb_logout_image' src='http://static.ak.fbcdn.net/images/fbconnect/logout-buttons/logout_small.gif' border='0' alt='Connect'/></a>"
+"</span>";
FB.XFBML.Host.parseDomTree();
}
FB.init("API-KEY","xd_receiver.htm");
FB.ensureInit ( function () {
FB.Connect.ifUserConnected(update_user_box);
});
</script>
You can't pass a variable from JavaScript to PHP; JavaScript is a client-side language (ie. it's executed by the browser), whereas PHP is a server-side language (ie. it's executed by the server).
It's possible to pass data from JavaScript to PHP using an XMLHttpRequest (commonly known as AJAX) to send a HTTP request to a PHP script, but I'm not sure that's what you want.
Once the user is logged in (usually using javascript FB.login()), a cookie is set. PHP can access that cookie. Check out the following PHP code (from http://developers.facebook.com/docs/guides/web#login):
<?php
define('FACEBOOK_APP_ID', 'your application id');
define('FACEBOOK_SECRET', 'your application secret');
function get_facebook_cookie($app_id, $application_secret) {
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value) {
if ($key != 'sig') {
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $application_secret) != $args['sig']) {
return null;
}
return $args;
}
$cookie = get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET);
?>
You can then get $cookie('uid'), and use that where you need it.
The page I linked above should have all you need to know about using the JavaScript SDK in conjunction with PHP.
You should include the facebook client library for php and then you can get the user id easily something like this:
include ('facebook_client_library.php');
$facebook = new facebook('API', 'SECRET');
$fbid = $facebook->get_loggedin_user();
echo $fbid;
Or try this javascript (not sure):
alert(FB.Facebook.apiClient.get_session().uid);
Use an array, Check my question Facebook Registration Connect it has the code I used then just add
$fuid = $response["registration"]["user_id"];
Or if that doesn't work then try
$fuid = $response["user_id"];
Hope I've been of help,
Brad

Categories