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...
Related
I have a page with two forms. I need to know which button is submitting the form. When the form gets submitted I am checking the set status of the button, but it doesn't seem to be set. Can anyone help?
HTML
<div id="contact-wrapper" class="">
<h1 style="color: white">Send me an email.</h1>
<div id="msg-status"></div>
<form id="contact" method="post">
<div class="contact-title">Email Address</div>
<input type="email" name="emailAddress" id="email-addr-txt" placeholder="Your Email Address" require>
<div class="contact-title">Subject</div>
<input type="text" name="emailSubject" id="email-subject-txt" placeholder="Subject" require>
<div class="contact-title">Message</div>
<textarea name="emailMessage" id="email-msg-txt" placeholder="Message" require></textarea>
<input type="submit" name="sendBtn" value="Send" id="send-msg-btn">
</form>
</div>
PHP
<?php
$phpconsole = "";
if ($_SERVER['REQUEST_METHOD'] === 'POST'){
if (isset($_POST["loginBtn"])) {
//Do Stuff
}
if (isset($_POST["sendBtn"])) {
//Do Stuff
}
$phpconsole = var_dump($_POST); }
?>
JavaScript
$('#contact').submit(function(e){
e.preventDefault();
email_regex = /^\b[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i;
var msg = "";
if ($('#email-addr-txt').val() == ""){
msg += "<p>The email address is missing!</p>";
} else if (!email_regex.test($('#email-addr-txt').val())) {
msg += "<p>The email address is invalid!</P>"
}
if ($('#email-subject-txt').val() == "") {
msg += "<p>The Subject is missing!</p>";
}
if ($('#email-msg-txt').val() == "") {
msg += "<p>The message is missing!</p>"
}
var heightOfContactWrapper = $('#contact-wrapper').height();
if (msg != "") { // There were errors that need to be delt with before sending message.
msg = "<h2>There were errors.</h2>" + msg;
$('#msg-status').html(msg);
$('#msg-status').addClass('msg-status-fail');
var heightOfMsgStatus = $('#msg-status').height() + $('#contact-wrapper').height() + "px";
$('#contact-wrapper').css('height', (heightOfContactWrapper + $('#msg-status').height() + "px"));
} else { //No errors found.
$('#msg-status').removeClass('msg-status-fail');
$('#msg-status').addClass('msg-status-success');
$('#msg-status').html("<h2>Message is sending. Please wait.</h2>")
$('#contact-wrapper').css('height', (heightOfContactWrapper + $('#msg-status').height() + "px"));
$('#contact').unbind('submit').submit();
}
});
Output of var_dump is
array(3) { ["emailAddress"]=> string(13) "asdf#aedf.com"
["emailSubject"]=> string(4) "asdf" ["emailMessage"]=> string(4)
"asdf" }
Errors are:
Notice: Undefined index: loginBtn in /var/www/new-site/index.php on
line 5 Notice: Undefined index: SendBtn in /var/www/new-site/index.php
on line 5
The problem is that your Javascript code ends up being the thing that triggers the form submit, not your button. If you removed your JS code you'd see your sendBtn value.
Instead of calling e.preventDefault in your .submit() callback, you could just return true if you want the form submission to continue, or false if you don't. That way, you don't have to call $('#contact').submit() to get your form to submit, or even unbind your submit handler. Something like this:
$('#contact').submit(function(e){
email_regex = /^\b[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i;
var msg = "";
if ($('#email-addr-txt').val() == ""){
msg += "<p>The email address is missing!</p>";
} else if (!email_regex.test($('#email-addr-txt').val())) {
msg += "<p>The email address is invalid!</P>"
}
if ($('#email-subject-txt').val() == "") {
msg += "<p>The Subject is missing!</p>";
}
if ($('#email-msg-txt').val() == "") {
msg += "<p>The message is missing!</p>"
}
var heightOfContactWrapper = $('#contact-wrapper').height();
if (msg != "") { // There were errors that need to be delt with before sending message.
msg = "<h2>There were errors.</h2>" + msg;
$('#msg-status').html(msg);
$('#msg-status').addClass('msg-status-fail');
var heightOfMsgStatus = $('#msg-status').height() + $('#contact-wrapper').height() + "px";
$('#contact-wrapper').css('height', (heightOfContactWrapper + $('#msg-status').height() + "px"));
return false;
} else { //No errors found.
$('#msg-status').removeClass('msg-status-fail');
$('#msg-status').addClass('msg-status-success');
$('#msg-status').html("<h2>Message is sending. Please wait.</h2>")
$('#contact-wrapper').css('height', (heightOfContactWrapper + $('#msg-status').height() + "px"));
return true;
}
});
Currently, I am working on a formula. I created the check function and they are all working. If the check function returns false nothing gets saved, but it still redirects to the congrats page?
here the code:
function check() {
var msg = "";
if ($_POST['Bustransfer'] == "ja" ) {
msg = "wrong\n";
document.formular.v6.style.backgroundColor = "#FF0000";
}
if (msg == "") return(true);
else {
alert(msg);
return(false);
}
}
and then I got the following in the body section:
<form method="post" action="Email.php" name="formular" onsubmit="return check()">
I don't get it, hope you can help me. Cheers!
You are mixing them(javascript & php) up. Should be '<?php echo $_POST['Bustransfer']; ?>' instead of $_POST['Bustransfer'] in the check.
function check() {
var msg = "";
if ('<?php echo $_POST['Bustransfer']; ?>' == "ja" ) {
msg = "wrong\n";
document.formular.v6.style.backgroundColor = "#FF0000";
}
if (msg == "") return(true);
else {
alert(msg);
return(false);
}
}
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
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.
I'm trying to validate some form fields using JS functions, but they don't seem to load or check the field when the submit button is clicked.
<html>
<body>
<?php require_once('logic.php'); ?>
<h1>Add new Region/Entity</h1>
<?php
if ($_POST['submitted']==1) {
echo $error;
}
?>
<form action="logic.php" method="post" name="registration" onSubmit="return formValidation();">
Region: <input type="text" name="region" value="<?php echo #$_POST['region']; ?>"><br>
Description: <br><textarea name="description" cols="50" rows="10"><?php echo #$_POST['description']; ?></textarea><br>
Remarks: <input type="text" name="remarks" value="<?php echo #$_POST['remarks']; ?>">
<input type="hidden" name="submitted" value="1"><br>
<input type="submit" value="Submit" onclick="">
And here's the JS:
<script type="text/javascript">
function formValidation() {
var region = document.registration.region;
var descr = document.registration.description;
var remarks = document.registration.remarks;
if(empty_validation()) {
if(reg_validation()) {
if(reg_letters()) {
if (desc_letters()) {
if (desc_validation()) {
}
}
}
}
}
return false;
}
function empty_validation() {
var reg_len = region.value.length;
var descr_len = descr.value.length;
var rem_len = remarks.value.length;
if (reg_len == 0 || decr_len == 0 || rem_len == 0) {
alert("Please fill all the fields");
return false;
}
return true;
}
function reg_validation() {
if (reg_len > 50) {
alert("Only 50 characters are allowed in the Region field");
region.focus();
return false;
}
return true;
}
function reg_letters() {
var letters = /^[A-Za-z]+$/;
if(region.value.match(letters)) {
return true;
} else {
alert('Region field must have only alphabetical characters');
region.focus();
return false;
}
}
function desc_validation() {
if (descr_len > 500) {
alert("Only 500 characters are allowed in the description field");
descr.focus();
return false;
}
return true;
}
function desc_letters() {
var iChars = "!##$%^&*()+=-[]\\\';,./{}|\":<>?";
for (var i = 0; i < descr_len; i++) {
if (iChars.indexOf(descr.value.charAt(i)) != -1) {
alert ("Your description has special characters. \nThese are not allowed.\n Please remove them and try again.");
return false;
}
}
return true;
}
</script>
</form>
</body>
</html>
As you can see, I'm posting values from the form to a PHP file. And I've used the onSubmit event in the form tag to initialize the formValidation() function. It isn't working for some reason.
Here's a working example if you need one.
I'm not going to fix every little error you have, but the main problem is that variables aren't defined where you expect them to be. You can't declare a variable in one function and expect it to be available in the next (without passing it as a parameter or declaring it globally). For example, your empty_validation function should be this:
function empty_validation(region, descr, remarks) {
var reg_len = region.value.length;
var descr_len = descr.value.length;
var rem_len = remarks.value.length;
if (reg_len == 0 || decr_len == 0 || rem_len == 0) {
alert("Please fill all the fields");
return false;
}
return true;
}
And in your formValidation function, you call it like this:
if(empty_validation(region, descr, remarks)) {
This is just one example, and you would need to do it in a few places.
A few other things - you always return false from formValidation...did you mean to put return true; inside the innermost if statement? Also, since all you seem to be doing is calling each of those functions, you can probably put them into one big if statement, like this:
if (empty_validation() && reg_validation() && reg_letters() && desc_letters() && desc_validation()) {
return true;
}
return false;