I want to pass JavaScript variables to PHP using a hidden input in a form.
But I can't get the value of $_POST['hidden1'] into $salarieid. Is there something wrong?
Here is the code:
<script type="text/javascript">
// View what the user has chosen
function func_load3(name) {
var oForm = document.forms["myform"];
var oSelectBox = oForm.select3;
var iChoice = oSelectBox.selectedIndex;
//alert("You have chosen: " + oSelectBox.options[iChoice].text);
//document.write(oSelectBox.options[iChoice].text);
var sa = oSelectBox.options[iChoice].text;
document.getElementById("hidden1").value = sa;
}
</script>
<form name="myform" action="<?php echo $_SERVER['$PHP_SELF']; ?>" method="POST">
<input type="hidden" name="hidden1" id="hidden1" />
</form>
<?php
$salarieid = $_POST['hidden1'];
$query = "select * from salarie where salarieid = ".$salarieid;
echo $query;
$result = mysql_query($query);
?>
<table>
Code for displaying the query result.
</table>
You cannot pass variable values from the current page JavaScript code to the current page PHP code... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.
You need to pass variables to PHP code from the HTML form using another mechanism, such as submitting the form using the GET or POST methods.
<DOCTYPE html>
<html>
<head>
<title>My Test Form</title>
</head>
<body>
<form method="POST">
<p>Please, choose the salary id to proceed result:</p>
<p>
<label for="salarieids">SalarieID:</label>
<?php
$query = "SELECT * FROM salarie";
$result = mysql_query($query);
if ($result) :
?>
<select id="salarieids" name="salarieid">
<?php
while ($row = mysql_fetch_assoc($result)) {
echo '<option value="', $row['salaried'], '">', $row['salaried'], '</option>'; //between <option></option> tags you can output something more human-friendly (like $row['name'], if table "salaried" have one)
}
?>
</select>
<?php endif ?>
</p>
<p>
<input type="submit" value="Sumbit my choice"/>
</p>
</form>
<?php if isset($_POST['salaried']) : ?>
<?php
$query = "SELECT * FROM salarie WHERE salarieid = " . $_POST['salarieid'];
$result = mysql_query($query);
if ($result) :
?>
<table>
<?php
while ($row = mysql_fetch_assoc($result)) {
echo '<tr>';
echo '<td>', $row['salaried'], '</td><td>', $row['bla-bla-bla'], '</td>' ...; // and others
echo '</tr>';
}
?>
</table>
<?php endif?>
<?php endif ?>
</body>
</html>
Just save it in a cookie:
$(document).ready(function () {
createCookie("height", $(window).height(), "10");
});
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}
And then read it with PHP:
<?PHP
$_COOKIE["height"];
?>
It's not a pretty solution, but it works.
There are several ways of passing variables from JavaScript to PHP (not the current page, of course).
You could:
Send the information in a form as stated here (will result in a page refresh)
Pass it in Ajax (several posts are on here about that) (without a page refresh)
Make an HTTP request via an XMLHttpRequest request (without a page refresh) like this:
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var PageToSendTo = "nowitworks.php?";
var MyVariable = "variableData";
var VariablePlaceholder = "variableName=";
var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;
xmlhttp.open("GET", UrlToSend, false);
xmlhttp.send();
I'm sure this could be made to look fancier and loop through all the variables and whatnot - but I've kept it basic as to make it easier to understand for the novices.
Here is the Working example: Get javascript variable value on the same page in php.
<script>
var p1 = "success";
</script>
<?php
echo "<script>document.writeln(p1);</script>";
?>
Here's how I did it (I needed to insert a local timezone into PHP:
<?php
ob_start();
?>
<script type="text/javascript">
var d = new Date();
document.write(d.getTimezoneOffset());
</script>
<?php
$offset = ob_get_clean();
print_r($offset);
When your page first loads the PHP code first runs and sets the complete layout of your webpage. After the page layout, it sets the JavaScript load up.
Now JavaScript directly interacts with DOM and can manipulate the layout but PHP can't - it needs to refresh the page. The only way is to refresh your page to and pass the parameters in the page URL so that you can get the data via PHP.
So, we use AJAX to get Javascript to interact with PHP without a page reload. AJAX can also be used as an API. One more thing if you have already declared the variable in PHP before the page loads then you can use it with your Javascript example.
<?php $myname= "syed ali";?>
<script>
var username = "<?php echo $myname;?>";
alert(username);
</script>
The above code is correct and it will work, but the code below is totally wrong and it will never work.
<script>
var username = "syed ali";
var <?php $myname;?> = username;
alert(myname);
</script>
Pass value from JavaScript to PHP via AJAX
This is the most secure way to do it, because HTML content can be edited via developer tools and the user can manipulate the data. So, it is better to use AJAX if you want security over that variable. If you are a newbie to AJAX, please learn AJAX it is very simple.
The best and most secure way to pass JavaScript variable into PHP is via AJAX
Simple AJAX example
var mydata = 55;
var myname = "syed ali";
var userdata = {'id':mydata,'name':myname};
$.ajax({
type: "POST",
url: "YOUR PHP URL HERE",
data:userdata,
success: function(data){
console.log(data);
}
});
PASS value from JavaScript to PHP via hidden fields
Otherwise, you can create a hidden HTML input inside your form. like
<input type="hidden" id="mydata">
then via jQuery or javaScript pass the value to the hidden field. like
<script>
var myvalue = 55;
$("#mydata").val(myvalue);
</script>
Now when you submit the form you can get the value in PHP.
I was trying to figure this out myself and then realized that the problem is that this is kind of a backwards way of looking at the situation. Rather than trying to pass things from JavaScript to php, maybe it's best to go the other way around, in most cases. PHP code executes on the server and creates the html code (and possibly java script as well). Then the browser loads the page and executes the html and java script.
It seems like the sensible way to approach situations like this is to use the PHP to create the JavaScript and the html you want and then to use the JavaScript in the page to do whatever PHP can't do. It seems like this would give you the benefits of both PHP and JavaScript in a fairly simple and straight forward way.
One thing I've done that gives the appearance of passing things to PHP from your page on the fly is using the html image tag to call on PHP code. Something like this:
<img src="pic.php">
The PHP code in pic.php would actually create html code before your web page was even loaded, but that html code is basically called upon on the fly. The php code here can be used to create a picture on your page, but it can have any commands you like besides that in it. Maybe it changes the contents of some files on your server, etc. The upside of this is that the php code can be executed from html and I assume JavaScript, but the down side is that the only output it can put on your page is an image. You also have the option of passing variables to the php code through parameters in the url. Page counters will use this technique in many cases.
PHP runs on the server before the page is sent to the user, JavaScript is run on the user's computer once it is received, so the PHP script has already executed.
If you want to pass a JavaScript value to a PHP script, you'd have to do an XMLHttpRequest to send the data back to the server.
Here's a previous question that you can follow for more information: Ajax Tutorial
Now if you just need to pass a form value to the server, you can also just do a normal form post, that does the same thing, but the whole page has to be refreshed.
<?php
if(isset($_POST))
{
print_r($_POST);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="data" value="1" />
<input type="submit" value="Submit" />
</form>
Clicking submit will submit the page, and print out the submitted data.
We can easily pass values even on same/ different pages using the cookies shown in the code as follows (In my case, I'm using it with facebook integration) -
function statusChangeCallback(response) {
console.log('statusChangeCallback');
if (response.status === 'connected') {
// Logged into your app and Facebook.
FB.api('/me?fields=id,first_name,last_name,email', function (result) {
document.cookie = "fbdata = " + result.id + "," + result.first_name + "," + result.last_name + "," + result.email;
console.log(document.cookie);
});
}
}
And I've accessed it (in any file) using -
<?php
if(isset($_COOKIE['fbdata'])) {
echo "welcome ".$_COOKIE['fbdata'];
}
?>
Your code has a few things wrong with it.
You define a JavaScript function, func_load3(), but do not call it.
Your function is defined in the wrong place. When it is defined in your page, the HTML objects it refers to have not yet been loaded. Most JavaScript code checks whether the document is fully loaded before executing, or you can just move your code past the elements it refers to in the page.
Your form has no means to submit it. It needs a submit button.
You do not check whether your form has been submitted.
It is possible to set a JavaScript variable in a hidden variable in a form, then submit it, and read the value back in PHP. Here is a simple example that shows this:
<?php
if (isset($_POST['hidden1'])) {
echo "You submitted {$_POST['hidden1']}";
die;
}
echo <<<HTML
<form name="myform" action="{$_SERVER['PHP_SELF']}" method="post" id="myform">
<input type="submit" name="submit" value="Test this mess!" />
<input type="hidden" name="hidden1" id="hidden1" />
</form>
<script type="text/javascript">
document.getElementById("hidden1").value = "This is an example";
</script>
HTML;
?>
You can use JQuery Ajax and POST method:
var obj;
$(document).ready(function(){
$("#button1").click(function(){
var username=$("#username").val();
var password=$("#password").val();
$.ajax({
url: "addperson.php",
type: "POST",
async: false,
data: {
username: username,
password: password
}
})
.done (function(data, textStatus, jqXHR) {
obj = JSON.parse(data);
})
.fail (function(jqXHR, textStatus, errorThrown) {
})
.always (function(jqXHROrData, textStatus, jqXHROrErrorThrown) {
});
});
});
To take a response back from the php script JSON parse the the respone in .done() method.
Here is the php script you can modify to your needs:
<?php
$username1 = isset($_POST["username"]) ? $_POST["username"] : '';
$password1 = isset($_POST["password"]) ? $_POST["password"] : '';
$servername = "xxxxx";
$username = "xxxxx";
$password = "xxxxx";
$dbname = "xxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO user (username, password)
VALUES ('$username1', '$password1' )";
;
if ($conn->query($sql) === TRUE) {
echo json_encode(array('success' => 1));
} else{
echo json_encode(array('success' => 0));
}
$conn->close();
?>
Is your function, which sets the hidden form value, being called? It is not in this example. You should have no problem modifying a hidden value before posting the form back to the server.
May be you could use jquery serialize() method so that everything will be at one go.
var data=$('#myForm').serialize();
//this way you could get the hidden value as well in the server side.
This obviously solution was not mentioned earlier. You can also use cookies to pass data from the browser back to the server.
Just set a cookie with the data you want to pass to PHP using javascript in the browser.
Then, simply read this cookie on the PHP side.
We cannot pass JavaScript variable values to the PHP code directly... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.
So it's better to use the AJAX to parse the JavaScript value into the php Code.
Or alternatively we can make this done with the help of COOKIES in our code.
Thanks & Cheers.
Use the + sign to concatenate your javascript variable into your php function call.
<script>
var JSvar = "success";
var JSnewVar = "<?=myphpFunction('" + JSvar + "');?>";
</script>`
Notice the = sign is there twice.
My form kept submitting and then refreshing so I looked at How to prevent page from reloading after form submit - JQuery to figure out how to stop it. The difference in the answer, however, with my solution was that I was submitting the form to itself.
Here's my code:
HTML
<form autocomplete="off" method="post" name="rp">
<input placeholder="Code" type="text" name="code" required>
<button type="submit">Submit</button>
</form>
PHP
<?php
$response = "";
if(isset($_POST['code'])){
echo "<script> alert('test'); </script>";
$password = $_POST["code"];
$result = $connection->query("SELECT * FROM Users WHERE passwords = '$password' LIMIT 1");
if($result->num_rows != 0) {
// unpack object
$data = mysqli_fetch_array($result);
// retrieves user ID (set into a cookie for x amount of time?)
$id = $data["ID"];
mysqli_close($connection);
echo "<script> alert('test 2'); </script>";
$response = "test 2";
header("Location: assessment.php");
} else {
$response = "test 3";
echo "<script> alert('test 3'); </script>";
mysqli_close($connection);
}
}
?>
JS
$("form").submit(function (e) {
// prevent page refresh
e.preventDefault();
var formData = $(this).serialize();
// Make AJAX request
$.post("login.php", formData);
});
I want the form to submit the data but not refresh. What am I doing wrong?
EDIT:
The problem has been narrowed down to the php. Since the request is through javascript, what should the name in the if-statement argument be. It can't be 'rp'.
So I found out something extremely curious. When I changed the if statement to if(isset($_POST['code']){} as some urged me to in the comments and I entered in the correct password, it follows the correct loop and produces this error:
VM1368 jquery.min.js:2 GET http://localhost:8080/assessment 404 (Not Found)
However, it does not produce the alert code I place before the header(). When I put in an incorrect password, it also doesn't do anything (even though I have an else statement). I've updated the php section to include most of the code. The $response variable and the echo/alerts are for debugging.
Final Edit:
Ironically, the reason none of my debugging wasn't working was because the page wasn't refreshing so alerts and variable updates wouldn't happen. (My quest to stop page refresh created all these problems). The solution to my original question was provided by MH2K9 and Toni Michel Caubet in the comment section. Thank you to them and others who tried to help.
Try this :
HTML :
<form autocomplete="off" method="post" name="rp" onsubmit="return false;">
<input placeholder="Code" type="text" name="code" required>
<br>
<button type="submit">Submit</button>
<button id="back_button" type="button"><img src="pics/back_arrow.png">Back</button>
</form>
JS:
$("form").submit(function (e) {
// prevent page refresh
e.preventDefault();
var formData = $(this).serialize();
// Make AJAX request
$.post("login.php", formData , function(data) {
alert(data);
$("form").reset();
});
});
You can alternatively call a function using the onsubmit attribute in HTML.
<form onsubmit='return preventSubmit(e)'>
// form content
</form>
<script>
function preventSubmit(e) {
e.preventDefault()
return false
}
</script>
I am using secureimage to validate a captcha. I think I am doing things they way they should be done, but I may be missing a big point. I am neither a jQuery guru nor an AJAX guru.
I have a form that passes data to a script to send a thank you email. At the top of the thankYou.php script there is a check against the captcha (using secureimage). It works if I simply submit the form to the PHP. The PHP can properly determine if the captcha is the correct one. If it fails, I can return back to my page. No problems there. What I wanted to do is check the captcha first using AJAX and then if it passes submit the same captcha to the thankYou.php script so I can capture a failed captcha without submitting the form.
I can successfully use AJAX to ask a PHP script if the captcha was correct.
My problem is if I first do the AJAX call and there is a failure, perfect I'm done. If successful, I need to send the captcha to my thankYou.php script to validate before sending the email. Sorry I am long winded. I guess ONE, can I validate the same captcha twice and TWO, if I can't what is a better way to do this? Thanks for whatever suggestions you may have.
PROBLEM SOLVED:
I'm not sure why I did not go straight to this. I am now sending the captcha to the thank you email code via AXAJ. If the captcha fails, I don't send an email and I return an error code. If the captcha is successful, I send the email and return appropriate completion code. Silly I didn't think of this first.
<!-- HTML CODE -->
<form action="ThankYou.php" method="post" id="thankYou">
<img id="captcha" src="securimage/securimage_show.php" alt="CAPTCHA Image" /><br />
Enter Text:<br />
<input type="text" name="captcha_code" size="6" maxlength="6" required />
</span><img src="securimage/images/refresh.png" alt="refresh the Captcha image" height=25 width=25/>
<input type="button" value="submit" class="darkButton" id="contactInfo" onclick="submitTheForm()" />
</form>
/* Javascript Code */
function submitTheForm() {
checkCaptcha(function(data) {
if (data=="true") {
document.getElementById("thankYou").submit();
}
else {
alert("Error");
}
});
}
function checkCaptcha(callBack) {
return $.ajax({
url: 'check_captcha.php',
data: {cc: $( "input[name='captcha_code']" ).val()},
dataType: "json",
type: 'post'
}).done(callBack)
}
/* PHP CODE */
/* thankYou.php */
<?php
session_start();
include_once $_SERVER['DOCUMENT_ROOT'] . '/ACC/securimage/securimage.php';
$securimage = new Securimage();
if ($securimage->check($_POST['captcha_code']) == false) {
$myVariable = "";
foreach($_POST as $key => $value){
$myVariable = $myVariable . $key . "-" . $value . " | ";
}
print($myVariable);
exit;
}
/* check_captcha.php */
<?php
session_start();
include_once $_SERVER['DOCUMENT_ROOT'] . '/ACC/securimage/securimage.php';
$securimage = new Securimage();
if ($securimage->check($_POST['cc']) == false) {
$return = "false";
}
else {
$return = "true";
}
die(json_encode($return));
?>
I'm trying to load a response from the php onto the same page. My Client side html looks like this.
<p>
<script type="text/javascript">// <![CDATA[
function sendForm() {
var dataSend = "?ClientName=" + $("#ClientName").val();
$.post("AddClient.php", dataSend, function(data) {
$("#responseDiv").html(data);
});
// ]]></script>
</p>
<div id="responseDiv"> </div>
<form action="AddClient.php" onsubmit="sendForm()">
<h1>Client Wizard <span>Please fill all the texts in the fields.</span></h1>
<label> <span>Client Name :</span> <input id="ClientName" type="text" name="ClientName" /> </label> <span> </span> <input class="button" type="Submit" value="Send" />
</form>
My Server side php looks like this:
<?php
$dbhost='127.0.0.1';
$dbuser='name';
$dbpass='password';
$dbname='dbname';
$conn=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
if(!$conn)
{
die('Could not connect:'.mysqli_connect_error());
}
$client=$_REQUEST["ClientName"];
$retval=mysqli_query($conn,"INSERT into client (clientid,clientname) VALUES (NULL,'$client')");
if(!$retval)
{
die('Could not add client:'.mysql_error());
}
$display_string="<h1>Client Added Successfully</h1>";
echo $display_string;
mysqli_close($conn);
?>
Unfortunately not only is the response being shown in anew html page, Its not accepting any name typed in the form. When I check the sql table the Column has a blank entry under it. I have not been able to figure out where I'm going wrong. Any help would be really appreciated.
All right. Your code have some room for improvement, but it's not an endless thing.
I saw somebody mention sanitization and validation. Alright, we got that. We can go in details here
This is how I will restructure your code using some improvements made by Samuel Cook (thank you!) and added a lot more.
index.html
<p>
<script type="text/javascript">// <![CDATA[
function sendForm() {
var dataSend = {clientName: $('#clientName').val()}
$.post("AddClient.php", dataSend, function(data) {
$('#responseDiv').html(data);
});
return false;
}
//]]>
</script>
</p>
<div id="responseDiv"></div>
<form action="AddClient.php" onsubmit="sendForm(); return false;">
<h1>Client Wizard <span>Please fill all the texts in the fields.</span></h1>
<label><span>Client Name :</span><input id="clientName" type="text" name="clientName"/><span></span><input type="submit" class="button" value="Send"></label>
</form>
Notice change in an input id and input name - it's now start with a lower case and now clientName instead of ClientName. It's look a little bit polished to my aesthetic eye.
You should take note on onsubmit attribute, especially return false. Because you don't prevent default form behavior you get a redirect, and in my case and probably your too, I've got two entries in my table with a empty field for one.
Nice. Let's go to server-side.
addClient.php
<?php
$dbhost = '127.0.0.1';
$dbuser = 'root';
$dbpass = '123';
$dbname = 'dbname';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if (!$conn) {
die('Could not connect: ' . mysqli_connect_error());
}
$client=$_REQUEST["clientName"];
$client = filter_var($client, FILTER_SANITIZE_STRING);
if (isset($client)) {
$stmt = $conn->prepare("INSERT into client(clientid, clientname) VALUES (NULL, ?)");
$stmt->bind_param('s', $client);
$stmt->execute();
}
if (!$stmt) {
die('Could not add client:' . $conn->error);
}
$display_string = "<h1>Client $client Added Successfully</h1>";
echo $display_string;
mysqli_close($conn);
?>
That is going on here. We are using PHP filters to sanitize our incoming from somewhere string.
Next, we check if that variable $client even exist (you remember that twice sended form xhr? Double security check!)
Here comes a fun part - to protect our selves even more, we start using prepared mySQL statements. There is no way someone could SQL inject you somehow.
And just check for any errors and display it. Here you go. I've tested it on my machine, so it works.
Forms default behavior is to redirect to the page given in the action attribute (and if it's empty, it refreshes the current page). If you want it to make a request without redirecting to another page, you need to use Javascript to intercept the request.
Here's an example in jQuery:
$('form').on('submit', function(e) {
e.preventDefault(); // This stops the form from doing it's normal behavior
var formData = $(this).serializeArray(); // https://api.jquery.com/serializeArray/
// http://api.jquery.com/jquery.ajax/
$.ajax($(this).attr('action'), {
data: formData,
success: function() {
// Show something on success response (200)
}, error: function() {
// Show something on error response
}, complete: function() {
// success or error is done
}
});
}
Would recommend having a beforeSend state where the user can't hit the submit button more than once (spinner, disabled button, etc.).
First off, you have a syntax error on your sendForm function. It's missing the closing bracket:
function sendForm() {
//...
}
Next, You need to stop the form from submitting to a new page. Using your onsubmit function you can stop this. In order to do so, return false in your function:
function sendForm() {
//...
return false;
}
Next, you aren't actually sending any POST data to your PHP page. Your second argument of your .post method shouldn't be a query string, but rather an object (I've commented out your line of code):
function sendForm() {
var dataSend = {ClientName:$("#ClientName").val()}
//var dataSend = "?ClientName=" + $("#ClientName").val();
$.post("AddClient.php", dataSend, function(data) {
$("#responseDiv").html(data);
});
return false;
}
Lastly, you have got to sanitize your data before you insert it into a database. You're leaving yourself open to a lot of vulnerabilities by not properly escaping your data.
You're almost there, your code just need a few tweaks!
I have a login-form created using HTML that looks like this:
<div class= "form-header">Login</div>
<div class= "error-message" id= "login-error-exists"></div>
<form action= "login.php" method= "POST" onsubmit= "loginCheckIncorrect()">
<div class= "form-field">
<div class= "form-text">
username:
</div>
<input type= "text" class= "login-textbox" id= "login-login-username" name= "loginLoginUsername">
</div>
<div class= "form-field">
<div class= "form-text">
password:
</div>
<input type= "password" class= "login-textbox" id= "login-login-password" name= "loginLoginPassword">
</div>
<input type= "submit" value= "Login" class= "signup-confirm">
</form>
As you can see, its a simple form that is sent to login.php though POST. Upon submitting this form, it calls a JavaScript (using jQuery) function known as loginCheckIncorrect(), which is shown below:
function loginCheckIncorrect() {
"use strict";
var loginLoginUsername = $("#login-login-username").val(), loginLoginPassword = $("#login-login-password");
alert("test1");
$.post('usernameIncorrect.php', {'loginLoginUsername': loginLoginUsername, 'loginLoginPassword': loginLoginPassword}, function (data) {
$("#login-error-exists").html(data);
alert("test2");
event.preventDefault();
return false;
});
alert("test3");
event.preventDefault();
return false;
}
As you can see, this function creates the variables to store the value of username and password entered in each textbox. It sends an alert out (debugging), and then uses a jQuery.post function to send the variables to the PHP file, which I will show below. It then (is supposed to) takes the data sent back from the PHP file to echo into the error div I have in my HTML form.
It then calls an alert (more debugging) and uses a combination of event.preventDefault() and return false to (supposedly) stop the form from submitting. This is repeated after the post function.
This is my PHP code:
<?php
header("X-XSS-Protection: 1");
include("connect.php");
$username = mysqli_real_escape_string($con, $_POST["loginLoginUsername"]);
$password = mysqli_real_escape_string($con, $_POST["loginLoginPassword"]);
echo "<script>alert('test');</script>";
$sql = mysqli_query($con, "SELECT * FROM main WHERE username='$username' and password='$password'");
$count = mysqli_num_rows($sql);
if ($count == 1) {
echo "";
$_SESSION["username"] = $username;
$_SESSION["password"] = $password;
} else {
echo "username and/or password is incorrect.";
}
?>
When I attempt to execute this code, the only alert it displays is test1. Could someone explain to me why this is, and more importantly, how I can fix it? Thanks in advance.
Look at your network requests in your browser's debug panel to see if it's sending what you think it is, put some debug statements in your PHP to see what is and isn't getting hit.
In this case, I think you might be missing the .val() on $('login-login-password') just before the alert("test1") in your javascript.
There is no event defined. That would be a problem and the form will submit. And the preventDefault in the callback is useless since the function already finished.
1) The name of the php file is login.php
2) The url to which you are requesting the post is usernameIncorrect.php
Therefore:
$.post('login.php', {'loginLoginUsername': loginLoginUsername, 'loginLoginPassword': loginLoginPassword}, function (data) {
$("#login-error-exists").html(data);
alert("test2");
event.preventDefault();
return false;
});
Alert test1 is the only one appearing because the post fails.
Probably with a fail event you would have cached the error.
Try, if you want to test that:
$.post('wrongUrl.php', {'loginLoginUsername': loginLoginUsername, 'loginLoginPassword': loginLoginPassword}, function (data) {
$("#login-error-exists").html(data);
alert("test2");
event.preventDefault();
return false;
})
.fail(function() {
alert( "error" );
});