Calling an external jQuery function from php File - php

I have been trying to use Messi.js to return a pop up box if the user has an input error in a form. I have a php file called add email:
<?php
/ini_set('display_errors',1);
//ini_set('display_startup_errors',1);
//error_reporting(-1);
include('connectionFile.php');
//test for duplicate emails
$query="SELECT * FROM ClientEmail WHERE ClientEmailAddress = '" . $_POST['emailAdd'] . "'";
$email=$_POST['emailAdd'];
$result=mysql_query($query);
$num=mysql_num_rows($result);
if($num==0)
{
if(isset($_POST['emailAdd']) && $_POST['emailAdd'] != "<<please enter email>>" && $_POST['emailAdd'] !="")
{
// the form was submitted
//remove hacker HTML
$email=strip_tags($_POST['emailAdd']);
//Insert data into database
$sql2="INSERT INTO ClientEmail SET ClientEmailAddress='$email'";
$result=mysql_query($sql2);
}
else
{
print '<script type="text/javascript">';
print 'new Messi("Please enter a valid email.", {title: "Input error", modal:true});';
print '</script>';
}
}
else
{
print '<script type="text/javascript">';
print 'new Messi("Sorry, you have entered an existing email.", {title: "Duplicate Email", modal:true});';
print '</script>';
}
?>
I am not sure where to call the jQuery files and css. I have done so in my index.php page(where the addEmail function is called) but it is still not working.
html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Club Blaque - Sign up for the Revolution</title>
<link href="css/reset.css" rel="stylesheet" type="text/css">
<link href="css/main.css" rel="stylesheet" type="text/css">
<link href="css/messi.min.css" rel="stylesheet" type="text/css"/>
<link href="js/jquery-1.8.2.js" type="text/javascript"/>
<script src="js/messi.js" type="text/javascript"></script>
Thanks in advance
EDIT
My form section currently looks as follows
<form name="emailAddr" method="post" action="">
<p>BE INVITED TO THE REVOLUTION <input id="emailAddress" name="emailAdd" type="text" value="<<please enter email>>" onFocus="clearText(this)" onblur="addText(this)"/>
<button type="submit" name="submit" value="Submit"><img id="submitImage"src='image/submit.ico'/></button> </p>
</form>

You can do the field validation testing in jQuery/javascript before even POSTing the form. That way you can trap errors without refreshing the page.
Note how the Submit button is type="button", not type="submit". The submit function is done via jQuery.
See below stand-alone, fully working example.
jsFiddle here
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#mybutt').click(function() {
//Do your field validation testing here, then submit if okay
var em = $('#emailAdd').val();
var pw = $('#pwordAdd').val();
if (em !='' && pw !='' ) {
$('#myform').submit();
}else{
alert('Please complete all fields');
}
});
}); //END $(document).ready()
</script>
</head>
<body>
<form id="myform" action="yourphpprocessor.php" method="POST">
Email Address:<br />
<input id="emailAdd" name="emailAdd" type="text" /><br />
Password:<br />
<input id="pwordAdd" name="pwordAdd" type="password" /><br />
<input type="button" id="mybutt" value="Submit It" />
</form>
</body>
</html>
Note that if you wish to store the javascript/jQuery in an external file the code would look something like this:
<script type="text/javascript" src='myjavascript.js'></script>
And the file myjavascript.js would look like this:
$(document).ready(function() {
$('#mybutt').click(function() {
//Do your field validation testing here, then submit if okay
var em = $('#emailAdd').val();
var pw = $('#pwordAdd').val();
if (em !='' && pw !='' ) {
$('#myform').submit();
}else{
alert('Please complete all fields');
}
});
}); //END $(document).ready()
For querying the database during field validation, use AJAX. It allows you to send the email address off to a PHP file (let's call it your PHP processor file), do the database lookup, and return a response. The response is anything that you want to build: from a simple 1 or 0 response, to a fully formatted HTML response that you will post into a DIV. In your case, a simple 1 or 0 will be fine.
First thing you must decide is how you want to trigger the AJAX lookup. You could use Submit button, but in our example let's use the jQuery blur() selector as it is triggered the moment a user leaves a field.
$('#emailAdd').blur(function() {
//Test if this email already exists
var em = $('#emailAdd').val();
$.ajax({
type: "POST",
url: "myphpprocessor.php",
data: 'eml='+em+'&anothervar='+summatelse,
success: function(whatigot) {
alert(whatigot);
if (whatigot == 'itexists') {
alert('This email address already exists. Please choose another.');
$('#emailAdd').css({'background-color':'yellow','border-color':'red'});
$('#emailAdd').focus();
}
} //END success callback
}); //END ajax block
}); //END emailAdd.blur
An Important Note About AJAX: All processing of received info must happen in the success: function. So, for example, the error message must happen in there. Once you start working with AJAX (95% of which is in this example - it's not very difficult), this note must be your Bible. Remember it.
Your PHP processor file would look like this:
myphpprocessor.php
<?php
$email = $_POST['eml']; //Note that it is same as the var NAME posted in AJAX
$summat = $_POST['anothervar'];
if ($email != '' && $email != '<<please enter email>>') {
include('connectionFile.php');
//test for duplicate emails
$query="SELECT * FROM `ClientEmail` WHERE `ClientEmailAddress` = '$email'";
$result=mysql_query($query);
$num=mysql_num_rows($result);
if($num > 0) {
echo 'itexists';
}else{
//do nothing
}
}

Related

Jquery $.post() data cannot be retrieved as PHP variable

I am having a difficult time trying to make the Ajax request $.post() from Jquery work. I would like to send data from a form with $.post() and retrieve it as php variables in order to further process them into an SQL database.
Below, I put a simplified version of my problem in a one page code (the Jquery posts to the same page when the function is triggered). I wish to use this method in order to not trigger a page reload when submitting the form.
The problem : my post() function works, I get the correct alert stating the data posted, BUT, print_r($_POST) check method stays empty after I submit my request.
My question : how can I get the posted data into php variables ($_POST['name'] & $_POST['email'] ?
<!DoCType html>
<html lang="fr-CH">
<head>
<title> TEST </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="/JS/jquery-3.3.1.min.js"></script>
</head>
<body>
<?php
print_r($_POST); // always returns an empty array, even after clicking the submit button
if (isset($_POST['name'])) {
echo "PHP received data";
} else {
echo "It did not work";
}
?>
<div class='caseform'>
<form id="form" method="post">
Name:<br> <input type="text" name="name"> <br>
Email:<br> <input type="text" name="email"> <br>
<button id="button"> Submit </button>
</form>
</div>
<script>
$( document ).ready(function() {
$("#button").click(function( event ) {
event.preventDefault();
var postData = $('#form').serialize();
// the $.post goes to the same php file "test.php"
var jqxhr = $.post("test.php", postData ,function() {
}).done(function() {
// this works, I get an alert with postData from my form (name=&email=)
alert(postData);
}).fail(function() {
alert("Error submitting the form.");
})
});
});
</script>
</body>
</html>
The issue is you haven't got anything to prevent the post handling code from running for a GET request. When you initially load the page it is a GET request, and it is running your print_r($_POST) which of course is empty.
Wrap that code in a check like this, and move it to the top of the file.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
print_r($_POST); // always returns an empty array, even after clicking the submit button
if (isset($_POST['name'])) {
echo "PHP received data";
} else {
echo "It did not work";
}
exit();
}
?><!DoCType html>
...
...

Ajax Query Isn't Going Through to PHP Script

I am trying to run a simple scenario in which: a form is submitted -> jquery ajax request for JSON data -> PHP script reads from the database and encodes to JSON -> data is shown on my page.
the fields on the MySQL are: Name and Password
step 1 - my form - Search.php
<html lang="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="Query.js"></script>
<title></title>
</head>
<body>
<form method="post" id="formoid" action="">
<input type="text" name="enterpass" placeholder="Enter Password">
<input type="submit" name="subbpass">
</form>
<input type="text" id="showname"><br/>
<input type="text" id="showpassword">
step 2 - my jquery file- Query.js
$(document).ready(function(){
$("#formoid").submit(function(){
alert("form submitted") // this alert goes through
var passid = $("#enterpass").val();
$.ajax({
url: "ModelQuery.php",
method: "POST",
dataType: "JSON",
data: {args: passid},
success: function(data)
{
console.log('ajax successfully sent'); // this alert isn't working
$("#showname").text(data.Name); // data isn't showing here
$("#showpassword").text(data.Password);
console.log(data); // or here ...
}
});
});
});
and lastly, my php -- ModelQuery.php -- I omitted some code lines but that script is the normal script for reading from the database and has worked for me in the past.
<?php
if(isset($_POST['args'])) {
$arg = $_POST['args']
$CON = mysqli_connect('127.0.0.1','root','','testdb');
// ....
$QUERY = "SELECT * FROM testtable where Password = '$arg'";
// ...
while($row = mysqli_fetch_array($RESULT))
{
$jsonresults["Name"] = $row['Name'];
$jsonresults["Password"] = $row['Password'];
}
echo json_encode($jsonresults);
}
the alert in the Jquery script right after the form is submitted does go through, but the ajax itself doesn't show anything, neither on the console nor on my two textboxs.
What am I doing wrong here?
Thank you very much!
I figured out the issue, which consisted of 3 different problems:
1) my input textbox <input type="text" name="enterpass" placeholder="Enter Password"> didn't have id attribute, only name
2) as #RamRaider suggested, I changed it to button and gave it id as well.
3) one of the lines in the php didn't have ; at its end..
Thanks you!

How to get response from ajax after selecting the auto completing email

I have a code to check email id is available or not in the database using ajax on keypress. If email Id is available then submit button will enable or email id is not available in the database then submit button will show disabled.
I have no issue in above process below code is working for above process.
My issue is some time users are getting the popup to store the username and password in the browser when the user entered the username and password. I am talking about cookies or can say auto-filed data. For example: If you enter the email id two or three times in text field then next time you clicked on the field you will automatically get your email.
Same issue I am getting. I saved the username and password on my browser and now I am selecting my username and clicking the button which is not working because I am using ajax on keypress. I f I type the email then it is working If I select the email then not working. I need if any user selects the email id than also button should active.
Hope you understand my issue .would you help me in this issue?
On keypress Getting ajax response
Auto filling the email the no response from ajax
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="" method="POST">
<input type="email" id="email" name="email" class="text_field" />
<span id="email-validation-error" class="error"></span>
<input id="submitYesNo" type="submit" name="next" value="submit" disabled="disabled">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
/*checking email id is already exist or not*/
$(document).ready(function() {
$('input[type="submit"]').attr('disabled', true);
});
$(document).ready(function()
{
var elem = $("#id"); //assign target element with id
$("input[name='email']").on('keyup',function()
{
var email = $('#email').val();
$.ajax(
{
url:'process.php',
type:'POST',
data:'email='+email,
success:function(data)
{
if (data == "success") {
$("#submitYesNo").prop('disabled', false);
$("#email-validation-error").html(data);
}
else{
$("#email-validation-error").html(data);
$("#submitYesNo").prop('disabled', true);
}
},
});
});
});
</script>
</body>
</html>
PHP
if(isset($_POST['email'])){
$email=$_POST['email'];
$_SESSION['username']=$email;
$query="SELECT Email FROM `request` WHERE Email='".$email."'";
$result = $conn->query($query);
$search_record=$result->num_rows;
if ($search_record > 0) {
echo "success";
}
else{
echo "Email does not exist, please sign up to use our services";
}
}
This function will work when the user click or focus outside of that input field otherwise it wont work
$("input[name='email']").bind('change keyup', function(){
console.log(this.value);
});
Check this once it may help on your scenario
Bind blur event with keyup event.So that when your textbox loose focus at that time your ajax can be called again
$("input[name='email']").on('keyup blur',function() // Add blur event
{

JS - submitting through javascript does not pass post variables

I am using Pure JS to first prevent the form from submitting then I have some validation code and finally automatic submission but the data is not passing from client side to server script.
Here is the HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Chat Room</title>
<link type="text/css" href="main.css" rel="stylesheet" />
<script type="text/javascript" src="main.js"></script>
</head>
<body>
<div id="container" class="add-nick">
<h3>Enter Your Name</h3>
<form action="chat.php" method="post" id="add-nicki">
<input type="text" placeholder="At least 6 alphabets e.g. Jackson" class="text" name="name" />
<input type="submit" value="Submit" class="submit" name="btnsubmit" />
</form>
</div>
</body>
</html>
The JS:
window.onload = function() {
document.forms[0].onsubmit = function(e) {
e.preventDefault();
var regexp = new RegExp("^[A-Za-z]+$"),
elem = this.elements[0],
value = elem.value;
if(regexp.test(value) && typeof value != "null" && value.length > 5) {
elem.className = "text correct";
var formElem = this;
setTimeout(function() { formElem.submit(); }, 0);
}
else elem.className = "text wrong";
};
};
The PHP file:
<?php
session_start();
if(isset($_POST['btnsubmit'])) {
$_SESSION['name'] = $_POST['name'];
echo $_SESSION['name'];
}
else {
if(!isset($_SESSION['name']))
echo "Header";
else
echo $_SESSION['name'];
}
?>
Is there something wrong or JS submit function is not functioning properly ?
The request parameter corresponding to a submit button is only passed if the form is submitted as a result of clicking that button. That's not the case here since you suppress the original form submit (the one triggered by the button), then later call formElem.submit() from JavaScript; no button click means no request parameter, and therefore isset($_POST['btnsubmit']) in your PHP script won't ever return true.
One solution might be to add the btnsubmit parameter to the form's action before submitting it:
formElem.action += (formElem.action.indexOf('?') == -1 ? '?btnsubmit=Submit' : '&btnsubmit=Submit');

Can a submit button work without refresh AJAX?

I have a problem with my very simple chat. The page is constanly refreshing with AJAX with an timeout of 750ms. If I press or use enter to submit my 'reaction', the page refreshes: is there an way to remove that, so that you can instantly see what you've posted?
You can see the chat at my website: chat
The code:
Index.php
<!DOCTYPE HTML>
<?php include 'config.php'; ?>
<html>
<head>
<script type="text/javascript" src="jquery-1.7.1.js">
function submitenter(myfield,e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;
if (keycode == 13)
{
myfield.form.submit();
return false;
}
else
return true;
}
</script>
<title>JavaScript Chat</title>
<link href="style.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="container">
<div id="chatwindow">
</div>
<div class="inputMessage">
<form method="post">
enter code here
<hr></hr>
<textarea name="message" rows="1" cols="55"></textarea><br/>Fill username here<br/>
<input type="text" value="" name="username" />
<input type="submit" value="verstuur" name="submit" onKeyPress="return submitenter(this,event)" />
</form>
<?php include 'send.php'; ?>
</div>
<script type="text/javascript">
$(document).ready(function(){
setInterval ( "get()", 750 );
});
function get(){
$.ajax({
type: 'GET',
url: 'chat.php',
success: function(data){
$("#chatwindow").html(data);
}
});
}
</script>
</div>
</body>
</html>
chat.php
<?php
include 'config.php';
$result = mysql_query("select * from Message");
while($row = mysql_fetch_array($result))
{
echo '<p>' . $row['username'] . " : " . $row['message'] . '</p>';
}
?>
send.php
<?php
if(isset($_POST['submit']))
{
if (!empty($_POST['username']))
{
if(!empty($_POST['message']))
{
$message = mysql_real_escape_string(htmlentities($_POST['message']));
$username = mysql_real_escape_string(htmlentities($_POST['username']));
$query = "INSERT INTO Message (`username`,`message`) VALUES ('".$username."','".$message."')";
mysql_query($query);
}
else
{
echo '<script type="text/javascript">alert(\'Je kan niet niks sturen\')</script>';
}
}
else
{
echo '<script type="text/javascript">alert(\'Vul een gebruikresnaam in!\')</script>';
}
}
?>
if my question is not clear say it please.
And is there a topic/question/post about good spacing? google translated it as "indent".
Thanks
Replace
<form method="post">
With
<form onsubmit="event.preventDefault()" method="post">
You may also use your callback function here like:
<form onsubmit="event.preventDefault();return submitenter(this,event);" method="post">
Working demo: http://jsfiddle.net/usmanhalalit/5RCwF/2/
Add e.preventDefault(); in JS.
Your desired action is to prevent the onSubmit action as the other answers have mentioned. Currently your script isn't quite ready to block submit as you don't have an ajax post method.
You need ajax functionality for the submission side of the application still. For this you can use jQuery post().
You want to create something like
function send() {
$.post(); // Fill in appropriate post() code.
return false;
}
And then call it from your event handlers like onsubmit="return send()" and in place of myfield.form.submit() in your keypress handler.

Categories