Ajax + PHP validation and call Javascript function inside PHP validation - php

Basically, I'm trying to call a Javascript function inside a PHP script when using Ajax.
JavaScript:
<script type="text/javascript">
function Validate() {
hr = new XMLHttpRequest();
name = document.getElementById('name').value;
hr.open('POST', 'validator.php', true);
hr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
hr.onreadystatechange = function() {
if ( hr.readyState == 4 && hr.status == 200 ) {
document.getElementById('message').innerHTML = hr.responseText;
}
}
hr.send('name=' + name);
}
function disable() {
document.getElementById('message').innerHTML = '';
}
</script>
HTML:
<div id="message"></div>
Name: <input type="text" id="name /">
<input type="button" onclick="Validate();" value="Validate" />
PHP:
<?php
$name = $_POST['name'];
if ( !empty( $name ) ) {
if ( $name == 'Tom' ) {
echo "<script>alert('Hello Tom, Welcome Back')</script>";
} else {
echo 'You are not Tom';
}
} else {
echo 'Please enter a name.';
}
?>
Everything works fine except calling the Javascript function inside PHP echo <script>alert()</script>
What I think the problem here is because I declared hr.responseText, as a result, the javascript I want to show has returned into text. But what should I do to solve this problem?
Any help would be appreciated.

Try changing your echo from "<script>alert('Hello Tom, Welcome Back')</script>";
to just 'Hello Tom, Welcome Back';
Then in your javascript you can call alert(hr.responseText);
You will have to change your javascript to check for what is returned so you know to call either the alert or the
document.getElementById('message').innerHTML = hr.responseText;
EDIT: I will add all the changed code...
<?php
$name = $_POST['name'];
if(!empty($name)){
if($name == 'Tom'){
echo 'Hello Tom, Welcome Back';
}else{
echo 'You are not Tom';
}
}else{
echo 'Please enter a name.';
}
?>
Javascript
<script type="text/javascript">
function Validate(){
hr = new XMLHttpRequest();
name = document.getElementById('name').value;
hr.open('POST', 'validator.php', true);
hr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
hr.onreadystatechange = function(){
if(hr.readyState == 4 && hr.status == 200){
response = hr.responseText.replace(/^\s+|\s+$/g,''); //remove whitespace so you can compare
if (response == ("You are not Tom") || response == ("Please enter a name."))
{
document.getElementById('message').innerHTML = hr.responseText;
}
else {
alert(hr.responseText);
}
}
}
hr.send('name=' + name);
}
function disable(){
document.getElementById('message').innerHTML = '';
}
</script>

Try this:
function do_alert($msg){
echo '<script type="text/javascript">alert("' . $msg . '"); </script>';
}
if(!empty($name)){
if($name == 'Tom'){
do_alert("You are tom");
}else{
do_alert("You are not tom");
}
}else{
echo 'Please enter a name.';
}

You didn't tag jQuery, but if you are using it, $.getScript might be what you want.
Aside from that, it might be better to build the script into your original document, and then execute this or that function based on the response text.

Related

Undefined variables in PHP after sending data via Ajax

I am trying to send data via Ajax to my php file and process it, I don't know where is the error Ajax seems to be Okay but after receiving data via $_POST in php file but when I am trying to echo my variables I am getting errors.
I am sending data using a POST;
here is my frontend code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!-- <form id="ArticleEnterForm" method="POST" action="ProcessFormData.php"> -->
<div id="warningsDiv">
wowowo
</div>
<label id="ArticleTitleLabel">Article title: </label>
<input id="ArticleTitleInputField" type="text" name="">
<div>
</div>
<iframe id="ArticleiFrame"></iframe>
<label>Enter article: </label>
<textarea id="ArticleContentTextArea"></textarea>
<label id="ArticleFileNameLabel">Enter file name(save as):</label>
<input id="ArticleFileNameInputField" type="text">
<button id="SubmitButton" name="submitButton">Submit</button>
<!-- </form> -->
<script>
function SubmitForm() {
function CheckFields() {
var warningsDiv = document.getElementById('warningsDiv');
var ArticleTitle = document.getElementById('ArticleTitleInputField');
var ArticleContent = document.getElementById('ArticleContentTextArea');
var ArticleFileName = document.getElementById('ArticleFileNameInputField');
if (ArticleTitle.value == "") { warningsDiv.innerHTML += "<strong> Enter article Name </strong>"; } else { return true; }
if (ArticleContent.value == "") { warningsDiv.innerHTML += "<strong> Enter article content </strong>"; } else { return true; }
if (ArticleFileName.value == "") { warningsDiv.innerHTML += "<strong> Enter article file name (save as) </strong>"; } else { return true; }
}
if (CheckFields == true) {
var articleTitle = ArticleTitle.value;
var articleContent = ArticleContent.value;
var articleFileName = ArticleFileName.value;
}
//submitting using POST method
var sendDataRequest = new XMLHttpRequest();
sendDataRequest.open("POST", "ProcessFormData.php", true);
sendDataRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
sendDataRequest.onreadystatechange = function () {
if (sendDataRequest.readyState === 2) {
warningsDiv.innerHTML = "<strong>Loading...</strong>";
}
if (sendDataRequest.readyState === 4 && sendDataRequest.status === 200) {
console.log("dtatus: " + sendDataRequest.readyState);
warningsDiv.innerHTML = sendDataRequest.responseText;
}
}
var dataToSend = "ArticleTitleData=" + articleTitle + "&ArticleContentData=" + articleContent + "&ArticleFileNameData=" + articleFileName;
sendDataRequest.send(dataToSend);
}
var submitButton = document.getElementById('SubmitButton');
submitButton.addEventListener("click", SubmitForm);
</script>
</body>
</html>
and here is my PHP code:
<?php
ini_set('display_errors', 'On'); //to get errors displayed
$ArticleTitle = "";
$ArticleContent = "";
$ArticleFileName = "";
if(isset($_POST['ArticleTitleData'])){
$ArticleTitle = $_POST['ArticleTitleData'];
}else {
echo("no var artn ");
}
echo("data was entered successfully following data was entered: Title: " . $ArticleTitle );
?>
where is the error in this script.
the response text I am seeing on browser screen is:
data was entered successfully following data was entered: Title: undefined
The problem is that some of the variables you are using, are undefined in the scope you are trying to use them in:
function CheckFields() {
// The variables defined with `var` exist in the scope of this function
var warningsDiv = document.getElementById('warningsDiv');
var ArticleTitle = document.getElementById('ArticleTitleInputField');
var ArticleContent = document.getElementById('ArticleContentTextArea');
var ArticleFileName = document.getElementById('ArticleFileNameInputField');
if (ArticleTitle.value == "") { warningsDiv.innerHTML += "<strong> Enter article Name </strong>"; } else { return true; }
if (ArticleContent.value == "") { warningsDiv.innerHTML += "<strong> Enter article content </strong>"; } else { return true; }
if (ArticleFileName.value == "") { warningsDiv.innerHTML += "<strong> Enter article file name (save as) </strong>"; } else { return true; }
}
if (CheckFields == true) {
// No `ArticleTitle`, etc. here...
var articleTitle = ArticleTitle.value;
var articleContent = ArticleContent.value;
var articleFileName = ArticleFileName.value;
}
Note that you are defining your variables using var in the CheckFields() function. So the scope of these variables is that function and anything in it, they will not be available outside of the CheckFields() function.
To solve that, you can return them from or define them before the function.
For example:
var ArticleTitle = document.getElementById('ArticleTitleInputField');
var ArticleContent = document.getElementById('ArticleContentTextArea');
var ArticleFileName = document.getElementById('ArticleFileNameInputField');
function CheckFields() {
var warningsDiv = document.getElementById('warningsDiv');
if (ArticleTitle.value == "") { warningsDiv.innerHTML += "<strong> Enter article Name </strong>"; } else { return true; }
if (ArticleContent.value == "") { warningsDiv.innerHTML += "<strong> Enter article content </strong>"; } else { return true; }
if (ArticleFileName.value == "") { warningsDiv.innerHTML += "<strong> Enter article file name (save as) </strong>"; } else { return true; }
}
// etc.
Note that if you need the warningsDiv outside of the function as well, you would need to treat it the same.
Yes, I figured out what was the problem
short answer:
when I was not calling the CheckFields(); properly
long answer:
Instead of if(CheckFields() == true){ //something } I was doing if(CheckFields == true){ //something }
I came to know this because when I was submitting the input field empty there was no change in warningsDiv as it was supposed to be when CheckFields(); function is called.
Thanks everyone for helping me...

form validation in codeigniter with ajax

I want to validate groupname.
I am using ajax but it is not working
This is my view
<?php echo form_input(['name'=>'groupname','class'=>'form-control','placeholder'=>'Enter group name','value'=>'','ng-model'=>'myWelcome[0].groupname','onkeyup'=>'loadValid(this.value)']) ?>
Javascript function
<script type="text/javascript">
function loadValid(v) {
if(v)
{
var url= window.location.href;
var res = url.split("/");
var groupid = res[res.length-1];
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", site_url + "admin/Usergroup_controller/store_edit_group_name_ajax/" + groupid + "/" + v, true);
xhttp.send();
}
else
{
document.getElementById("demo").innerHTML = "Group name is required field.";
}
}
</script>
Controller function
public function store_edit_group_name_ajax($groupid,$groupname)
{
$this->load->library('form_validation');
$this->form_validation->set_rules('groupname', 'Group name', 'trim|required|alpha|is_unique[group.groupname]|min_length[3]');
if( $this->form_validation->run() )
{
echo form_error('groupname','<p class="text-danger">','</p>');
}
}
Please help...
Make sure you are creating a response object first.
$response = new stdClass();
if ($this->form_validation->run() == false)
{
$response->status = 'failure';
$response->error = validation_errors('<p class="text-danger">', '</p>');
}
...
return $response;
In Javascript after getting response;
document.getElementById("demo").innerHTML = xhttp.responseText.error;
Just echo-ing ajax results is something you need to leave immediately. Please take it as a friendly advise.

How do I code this the smart way, Ajax/PHP

I've got myself a little script that checks the validity of a link supplied by the user, making it safe to store in the database (safer at least) and to confirm it's a link to facebook.
Now I want to roll this code out for another links, changing parameters as and when needed so that links to people user profile on these sites work, bit I dont want to copy and paste the code another 5 times and then try and adapt the Ajax to work with it, if theres a better way to approach this.
This is my code, it can been seen working at www.vwrx_project.co.uk/test.php. It hopefully only accepts facebook.com/(something here) .
link_checker.php
<?php
function check_url($dirty_url) {
//remove anything before facebook.com using strstr()
//clean url leaving alphanumerics : / . only - required to remove facebook link format with /#!/
$clean_url = strstr(preg_replace('#[^a-z0-9:/.?=]#i', '', $dirty_url), 'facebook.com');
$parsed_url = parse_url("http://www.".$clean_url); //parse url to get brakedown of components
$safe_host = $parsed_url['host']; // safe host direct from parse_url
// str_replace to switch any // to a / inside the returned path - required due to preg_replace process above
$safe_path = str_replace("//", "/", ($parsed_url['path']));
if ($parsed_url['host'] == 'www.facebook.com' && $parsed_url['path'] != '' && $parsed_url['path'] != '/') {
echo "Facebook";
} else if ($parsed_url['host'] == 'www.facebook.com' && $parsed_url['path'] == '') {
echo "missing_profile1";
} else if ($parsed_url['host'] == 'www.facebook.com' && $parsed_url['path'] == '/') {
echo "missing_profile2";
} else {
echo "invalid_url";
}
}
?>
Test.php
<?php
include_once ("includes/check_login_status.php");
include_once ("includes/link_checker.php");
// AJAX CALLS THIS LOGIN CODE TO EXECUTE
if(isset($_POST["L"])){
$dirty_url = $_POST["L"]; //user supplied link
//$dirty_url = "http://www.facebook.com/profile.php?id=4";
// if $dirty_url is blank
if($dirty_url == ""){
echo "no link supplied";
exit();
} else {
check_url($dirty_url);
}
exit();
}
?>
<html>
<head>
<title>testing</title>
<script type="text/javascript" src="js/main.js"></script>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
function emptyElement(x){
_(x).innerHTML = "";
}
function cleanURL(){
var user_url = _("user_link").value;
var func = _("hidden").value;
if(user_url == ""){
_("status").innerHTML = "Please provide a link before clicking submit";
} else {
_("submitbtn").style.display = "none";
_("status").innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "test.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "no link supplied"){
_("status").innerHTML = "Submitted blank form data.";
_("submitbtn").style.display = "block";
} else if(ajax.responseText == "invalid_url"){
_("status").innerHTML = "The url supplied is invalid";
_("submitbtn").style.display = "block";
} else if(ajax.responseText == "missing_profile1"){
_("status").innerHTML = "Please supply a link to your profile";
_("submitbtn").style.display = "block";
} else if(ajax.responseText == "missing_profile2"){
_("status").innerHTML = "Please supply a link to your profile";
_("submitbtn").style.display = "block";
} else{
_("status").innerHTML = ajax.responseText;
}
}
}
ajax.send("L="+user_url);
}
}
</script>
</head>
<body>
<p id="status"></p>
<form id="linkform" onSubmit="return false;">
<input type="text" id="user_link">
<input type="hidden" id="hidden" value="Facebook">
<button id="submitbtn" onClick="cleanURL()">Submit</button>
</form>
Why dont you add an additional parameter which is the website you want to allow?
function check_url($dirty_url, $websiteURL)
Then update your function to use the $websiteURL variable instead of the hardcoded 'facebook.com'
Then when you want to have several different urls you can do this
check_url($dirty_url, 'facebook.com');
or
check_url($dirty_url, 'twitter.com');
Or are you wanting to be able to check for multiple sites in the single function? such as facebook.com and twitter.com

echo out php variable in jQuery

this is changepassword.php file
<?php
include 'core/init.php';
if (empty($_POST) === false) {
if (md5($_POST['current_password']) === $user_data['password']) {
} else {
$errors[] = 'Your current psasword is incorrect';
}
}
if (empty($_POST) === false && empty($errors) === true) {
change_password($session_user_id, $_POST['password']);
} else if (empty($errors) === false) {
$error = output_errors($errors);
this variable
}
?>
this is the jQuery file
$('#save_pass').click(function(){
var current_password = $('#current').val();
var password = $('#new').val();
var password_again = $('#confirm').val();
if ((password == password_again) && (password.length >= 8)) {
$.post('changepassword.php', {current_password: current_password, password: password, password_again: password_again });
$('#show').html('password changed').fadeIn(500).delay(2000).fadeOut(500);
} else if ((current_password ==0) || (password_again.length == 0) || (password.length == 8)) {
$('#show').html('all fields are required').fadeIn(500).delay(2000).fadeOut(500);
} else {
$('#show').html('your password must be at least 8 characters').fadeIn(500).delay(2000).fadeOut(500); }
$('#current').val(null);
$('#new').val(null);
$('#confirm').val(null);
});
i want to echo out $error variable when a user enters an incorrect password and click on the change password button with id="#save_pass"
You cannot echo php variables within a javascript file. Instead, put the javascript in your php file and echo it there - eg:
<script>
function something() {
alert('<?php echo $error; ?>');
}
</script>
In order to get back the errors from your $.post() ajax call, you need to echo $errors in your php script. Then add a success/done function to your $.post():
$.post('changepassword.php', {current_password: current_password ...})
.done(function (data) {
alert(data);
}
This should be the basics for getting back the raw echo data, but look at $.post documentation for more guidance on how to refine this.

validating and submitting with 'if' and 'else' using PHP

This code is supposed to check to see if any fields are blank or invalid, if they are, it will turn them red. if all is ok then it will send to the database.
The problem is, if the last 'if' is not met, then the 'else' will fire.
This means as long as a valid email address is entered the form will submit, even if other fields are blank.
How can I make so that all requirements must be met for the form to submit
if(empty($_POST['company'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#companyForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
}
if(empty($_POST['name'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#nameForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
}
if(empty($_POST['email'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
}
else {
//submits to database...
}
You can use a flag as:
$isValid = true;
if(empty($_POST['company'])) {
$isValid = false;
// your echo
}
Similarly add the $isValid = false; for all the other if bodies.
Finally remove your else part and replace it with:
if($isValid) {
// submit to DB.
}
you either can use else if, but then you won't see your "red" for all wrong fields but only for the first that failed validation.
like so:
if() {
} elseif() {
} else {
...
}
or you could set something to $error=false at the beginning, and set error to true inside the if controlled code and the submission to database checks if error is still false...
<?php
$error = 1;
if(empty($_POST['company'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#companyForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 0;
}
if(empty($_POST['name'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#nameForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 0;
}
if(empty($_POST['email'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 0;
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 0;
}
if($error == 1) { //submits to database...
}
?>
There is a far better way of doing this instead of repeating your own code for each POST variable, which is not efficient.
// loop through all submitted fields
foreach( $_POST as $key => $value){
// see if the field is blank
if($value=="" || $value is null){
// if blank output highlighting JS
echo "<script type='text/javascript'>
$(document).ready(function() {
$('#".$key."Form').animate({backgroundColor:'#ffbfbf'},500);
});
</script>";
// variable to value showing form is invalid in some way
$invalid=1;
}
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$invalid= 1;
}
// if form invalid variable not set, submit to DB
if($invalid!=1){
// submit to DB
}
If you want to be super efficient you can simply use:
// search for any values that are null (empty fields)
$invalid_fields=array_keys($_POST, null);
// you may need to use $invalid_fields=array_keys($_POST, "");
// if there are any results from this search, loop through each to highlight the field
if($invalid_fields){
foreach( $invalid_fields as $key => $value){
echo "<script type='text/javascript'>
$(document).ready(function() {
$('#".$value."Form').animate({backgroundColor:'#ffbfbf'},500);
});
</script>";
}
$error = 1;
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 1;
}
if($error!=1){
// submit to DB
}
Introduce a Variable $sendToDb and initialy set it to (bool) true. If any of your checks fails, set this variable to false.
Then rewrite the else-Part and do a
if ($sendToDb) {
/* Your Db-Write code */
}
Take a flag variable and check like this
$flag=0;
if(empty($_POST['company'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#companyForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$flag=1;
}
if(empty($_POST['name'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#nameForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$flag=1;
}
if(empty($_POST['email'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$flag=1;
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$flag=1;
}
if ($flag == 0)
{//submit to database
}
You really shouldn't be mixing server-side code (PHP) with client-side code (JavaScript).
Validate on the server side first. Then add validation on the client side. The reason being, if your user has JavaScript enabled then they'll get the error messages before the form submits. If they have JavaScript disabled, then your PHP script will throw the errors. Something like the following script:
<?php
if (isset($_POST['submit'])) {
$errors = array();
// do server-side validation
if ($_POST['fieldName'] == '') {
$errors['fieldName'] = 'fieldName is required';
}
if (count($errors) == 0) {
// save your record to the database or whatever
}
}
And then the following template:
<style>
.error { border-color: red; }
</style>
<script>
$(document).ready(function() {
$('form#yourFormId').submit(function() {
var errors = null;
if (errors.length > 0) {
return false;
}
});
});
</script>
<form action="yourScript.php" method="post" id="yourFormId">
<input type="text" name="fieldName" value="" id="id"<?php if (in_array('fieldName', $errors)) echo ' class="error"'; ?>>
<input type="submit" name="submit">
</form>
This will apply a class of .error to any invalid form fields, first by JavaScript and then server-side.

Categories