ajax in html, get result from php - php

I have html:
<body>
<div class="po-logo">
<img src="img/logos/lw.png" alt="logo watchbees"/>
</div>
<form>
<div class="mui-textfield mui-textfield--float-label reg-window">
<input id="username" name="username" type="text"/>
<label>Username</label>
</div>
<div class="mui-textfield mui-textfield--float-label reg-window">
<input id="password" name="password" type="password"/>
<label>Password</label>
</div>
<div class="mui-textfield mui-textfield--float-label reg-window">
<button id="login" value="submit" onclick="return result" class="mui-btn mui-btn--raised reg-win-button">Sign in</button>
</div>
</form>
Jquery in html:
$("#login").click(function(){
var username=$("#username").val();
var password=$("#password").val();
if(($.trim(username).length > 0) & ($.trim(password).length > 0))
{
$.ajax({
type: "POST",
url: "http://127.0.0.1/app/login.php",
data: {username: username, password: password},
beforeSend: function(){ $("#login").html('Prihlasovanie...');},
success: function(data){
if(data == "success")
{
localStorage.login="true";
localStorage.username=username;
window.location.href = "profil.html";
}
else if (data = "failed")
{
alert("Problem s prihlasením, skúste znovu.");
$("#login").html('Prihlásiť sa');
}
}
});
}return false;
});
And php file on localserver, login.php:
if (isset($_POST['username'], $_POST['password'])){
$username=mysql_real_escape_string(htmlspecialchars(trim($_POST['username'])));
$password=mysql_real_escape_string(htmlspecialchars(trim($_POST['password'])));
$login = mysql_num_rows(mysql_query("SELECT * FROM `login` WHERE `username`='$username' AND `password`='$password'"));
if($login != 0){
echo "success";
}
else{
echo "failed";
}
}
But something is wrong, ajax doesn't send my back any data. It only changes #login to "connecting..." but nothing happens. Inscribing information is correct and they are uploaded to the database. Most likely php doesn't send back any data or ajax in html doesn't correct processing data from php. I don't where is problem. Profil.html is in the same folder as index.html. But login.php is on local server.
HTML: index.html; PHP: login.php on local server on my latop; Server: 127.0.0.1, database name db_login.
Any help or pointers greatly appreciated.

First - you have to check is ajax request pointed correctly to your php file. Open inspector in Chrome, switch to tan network then Emanuel filter xhr. After click on #login you should see new request there. Click on it, switch to response tab and paste its content here Please

Your issue is below lines:
in JS:
data: {username: username, password: password},
in PHP:
if(isset($_POST['login'])){
Reason
From JS side, you are passing 2 params in the POST request: username and password, while in PHP, you are checking for $_POST['login']. You should instead be checking for $_POST['username'] and $_POST['password'] in PHP.
Also, you are using mysql_real_escape_string() which is deprecated since PHP 5.5. And, you are injecting the username and password, which are both user inputs, directly into the mysql query leading to serious security issues relating to SQL Injection. Use PHP-MySQLi or PDO API and prepared statements.

OK, but why first If takes true ? Author, Please give us request headers of that xhr from inspector

Related

Redirecting from PHP page after jQuery $.ajax post

I'm using $.ajax to submit my data to a PHP page and I know I can do a redirect when success response is returned. However, is there a way to execute a redirect from my PHP page where I post to?
PHP
If you want a PHP way you can set the header.
header('Location: www.example.com');
Warning you can only use header if you haven't sent any other information to the client.
Remember that header() must be called before any actual output is
sent, either by normal HTML tags, blank lines in a file, or from PHP.
It is a very common error to read code with include, or require,
functions, or another file access function, and have spaces or empty
lines that are output before header() is called. The same problem
exists when using a single PHP/HTML file.
Javascript
You can redirect the browser using the following:
window.location = "www.example.com";
This can be done at any time.
Sources: PHP-Header JS-Window-Location
Here is what you want. The code below post data to server php backend via ajax and redirect users if posted data is not
empty
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#signin').click(function(){
var username = $('#username').val();
var password = $('#password').val();
if(username==""){
alert('please Enter username');
}
else if(password==""){
alert('please Enter password');
}
else{
$('#loader').fadeIn(400).html('<span>Please Wait, User is being logged</span>');
var datasend = "username="+ username + "&password=" + password;
$.ajax({
type:'POST',
url:'login.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
//empty username and password box after submission
$('#username').val('');
$('#password').val('');
$('#loader').hide();
$('#result').fadeIn('slow').prepend(msg);
$('#fadeoutResult').delay(5000).fadeOut('slow');
}
});
}
})
});
</script>
<input
name="username"
type="text"
class="form-control input-lg"
id="username"
/>
<input
name="password"
type="password"
class="form-control input-lg"
id="password"
/>
<div id="loader"></div>
<div id="result"></div>
<button type="submit" id="signin">
Submit
</button>
test.php
<?php
// lets do redirect if username and password is not empty. you can apply the same principle is your submission is successful
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
if ($username != '' && $password !=''){
header('Location: success.php');
exit();
}
?>

AJAX not receiving POST variables

I've read at least 20 of these similar questions and can't figure out what's wrong with my code.
I've got a login form as shown below:
<div class="login-form">
<form class="login-form-container" action="./" method="post" autocomplete="off">
<input id="login-user" type="text" placeholder=" Username"/>
<input id="login-pass" type="password" placeholder=" Password"/>
<div class="login-button-container">
<input id="login-button" type="submit" value="Log in"/>
</div>
</form>
</div>
My login.js script is as below:
$(document).ready(function(){
$("#login-button").click(function(e){
var username = $("#login-user").val();
var password = $("#login-pass").val();
$.ajax({url: "../includes/index.php", //.js file is in a diff directory
data: {'login':true,'name':username,'pwd':password},
type: "POST",
success: function(html) {
if (html=='true') {
//window.location="dashboard.php";
alert('success');
}
else {
alert('failure');
}
}
});
return false;
});
});
This is supposed to get sent back to 'index.php', which has included a separate php file that handles the login information. The reason for this is so I can update the page with the user's successful login without refreshing.
My other php file is simply checking for the post data:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
var_dump($_POST);
if (isset($_POST['login']) && $_POST['login']) {
} else if (isset($_POST['reg']) && $_POST['reg']) { //this is for registration, which will be used once this login is working
} else {
echo 'Neither login/reg were set';
}
The var dump shows:
array(0) { }
So the data is not being received. However, it clearly reaches the php page. I don't know what's wrong, any suggestions?
Edit: I figured I would add, that adding an alert at the top of login.js with the username/password does print the entered values. So the login.js is being reached, and the data is accessible there. But it doesn't go beyond that.
Edit2: Here is my updated HTML and login.js code:
index.php:
<form class="login-form-container" action="./" method="post" autocomplete="off">
<input id="login-user" type="text" placeholder=" Username"/>
<input id="login-pass" type="password" placeholder=" Password"/>
<div class="login-button-container">
<input id="login-button" type="button" value="Log in"/>
</div>
</form>
login.js
$(document).ready(function(){
alert(1);
$("#login-button").click(function(e){
alert(0);
//e.preventDefault();
var username = $("#login-user").val();
var password = $("#login-pass").val();
$.ajax({url: "../includes/index.php",
data: {'login':true,'name':username,'pwd':password},
type: "POST",
success: function(html) {
if (html=='true') {
//window.location="dashboard.php";
alert('success');
}
else {
alert('failure');
}
}
});
return false;
});
});
The solution was to change my
$("#login-button").click(function(e){
to
$(document).on("submit",".login-form-container",function(e) {
which will handle the form submit, and this includes pressing the button as well as hitting enter (ideal situation).
Now the data is being sent successfully and I can handle the actual login/registration SQL, so thank you to #Ashokkumar M. Prajapati for helping to come to the conclusion that the .js script was not actually firing upon submit (not that the rest of you didn't help!)
please replace type: "POST" with method: "POST"
you mentioned it wrong in jquery ajax function.
Default is "GET" in case you don't specify it. So, if you had checked both $_POST & $_GET then you would have found your data in $_GET.
try var_dump($_REQUEST) if it don't show up anything then your client is not sending data to server.
also, check net panel of you browser developer console. so, you will know what data are passed to server.

ajax form submit -> receive respone from php

I've been reading multiple threads about similar cases but even now I'm still unable to do it correctly.
What I want to do
Basically, i.e. I have form which allows user to change his login (simply query to database).
PHP script looks like that:
if(isset($_POST['login'])) {
$doEdit = $user->editData("login", $_POST['login']);
if($doEdit) {
$result = displayInfobox('success', 'Good!');
} else {
$result = displayInfobox('warning', 'Bad!');
}
} else {
$error = 'Bad!';
echo $error;
}
displayInfobox is just a div with class i.e. success and content - Good!.
Right now I would like to send this form by AJAX and display $result without reloading page.
HTML:
<form id="changeLogin" method="post" class="form-inline" action="usercp.php?action=editLogin">
<label for="login">Login:</label><br />
<div class="form-group ">
<input type="text" class="form-control" name="login" id="login" required>
<input type="submit" value="Zmień" class="btn btn-primary">
</div>
</form>
And finnally - my jquery/ajax:
$("#changeLogin").submit(function(e) {
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function(result) {
alert(result);
},
error: function(response) {}
});
e.preventDefault();
});
$("#changeLogin").submit();
If I leave "success" blank, it works -> form is submitted by ajax, login changed, but I do not see the result message. Otherwise whole page get reloaded.
Also, when I hit F5 form is being submited once again (even in Ajax).
I cant add comments because i do not have enough reputation but...
You should delete the last line with $("#changeLogin").submit();
And then in your php script file you should echo the result so you can get this result in ajax request. After that in your success method you have to read the result and (for example) append it somewhere to show the success or error box
I think you can use a normal button instead of submit button,just onclick can be an ajax request, the form should not be submitted,good luck.

AJAX use php variable returned to write if statement (Jquery Mobile/Ajax/Php)

I'm trying to create a login script where the user will enter their username and password. This will be sent via ajax to a php script to check if the details are correct. If they are the user should then be able to select a site, which ive been trying to display like this $('#logonContainer').load("login_DisplaySelectSite.php");
My problem is that I cant figure out how to run this code if the session has started with a valid username. Heres my code so far, maybe someone can help me!
html/jquery mobile:
<div data-role="content">
<form id='login' onsubmit="return false;">
<div id='logonContainer' style="background-color: #F8F4FA; padding: 10px; width:70%; margin: 0 auto; margin-top:15%;">
<input type="text" name='user' id='user' placeholder='Username'>
<input type="password" name='password' id='password' placeholder='Password'>
<input type="submit" id="submitLogin" name="login" value="Login" class='ui-btn ui-btn-c ui-btn-inline' data-theme='c' data-transition='pop'>
</div>
</form>
<div id="resultLog"></div>
</div>
ajax:
$(function userLogin() {
$("#submitLogin").click(function() {
var theUser = $.trim($("#user").val());
var thePassword = $.trim($("#password").val());
if(theUser.length > 0)
{
$.ajax({
type: "POST",
url: "callajax.php",
data: ({usr: theUser, pwd: thePassword}),
cache: false,
dataType: "text",
success: onSuccess
});
}
});
$("#resultLog").ajaxError(function(event, request, settings, exception) {
$("#resultLog").html("Error Calling: " + settings.url + "<br />HTTP Code: " + request.status);
});
function onSuccess(data)
{
$("#resultLog").html(data);
}
This next bit is not working at all!! This is where I'm trying to display a radio button list to replace the username and passowrd fields. After this I guess I will use a similar function to select the site, again, dependant on the session being active - once all these checks have been done the user should be sent to the home page
if(onSuccess(data) == 1)
{
$('#logonContainer').load("login_DisplaySelectSite.php");
} else {
}
});
php:
session_start();
if($_REQUEST['usr']=="admin" && $_REQUEST['pwd']=="1234"){
$_SESSION['USERNAME'] = "admin";
$_SESSION['SESSIONID']='123456';
echo "Login CORRECT WOOOOOOOO!! </br>" ;
//print json_encode($_SESSION);
print $_SESSION['USERNAME'];
$loggedon=1;
echo json_encode( $loggedon);
}
else{
echo "Incorrect Login :(" ;
$loggedon=0;
echo json_encode($loggedon);
}
Thanks
I see data isn't defined yet? And you might want to add this line too: data: $( "#login" ).serialize() in $.ajax();
You are missing the signature of the success event.
Just add the parameter to Success:
success: onSuccess(data)
and try to check, it should work fine.
to check if the success, event is triggered its better to use some debugging tools or alerts/console messages/print to screen etc based on your development environment and IDE that you use, that will tell you if its working fine.
thanks.

why does this text input not cache?

I have two web pages which work basically the same, code-wise, but one of them does not seem to cache information. By 'cache', I mean on the client/browser side. The text field does not retain previously entered information. In the first example below, if you register and then log in, the next time you log in, your username will be cached in the the browser to be selected; while in the second example, it does not retain that info.
http://www.dixieandtheninjas.net/hunter/ has a login prompt. once you've logged in once from a browser, when you revisit the page it has cached your username.
http://www.dixieandtheninjas.net/dynasties/ also has a login prompt, but it does not cache! And I cannot figure out why.
Perhaps because the second one is not within FORM tags? Maybe there's some other tiny coding mistake I've made which causes this.
Here's the code from the first example:
<form method = "post"
action = "">
Username: <input type="text" name="login_name" value="" />
<br><br>
Password: <input type="password" name="password" value="" />
<br><br>
<input type="submit" value="Login" />
</form>
Here is code from the second example: Note that the clicks are handled by jquery in the second example, while the first just uses pure html and php
<p>
Email address: <input type="text" id="logininfo" value="" />
<br>
Password: <input type="password" id="password" value="" />
<br>
<input type="button" id="loginbutton" value="Login" />
</p>
Here is the jquery used in the second example:
<script type ="text/javascript">
$(function(){
$('#loginbutton').click(function(){
var loginvar = $('#logininfo').val();
var passvar = $('#password').val();
//alert(loginvar + ", " + passvar);
if (loginvar != '' && passvar != '') {
var subdata = {
logindata : loginvar,
passdata : passvar
};
$.ajax({
url: "index_backend.php",
type: 'POST',
data: subdata,
success: function(result) {
//alert(result);
if (result == '1') {
// success
window.location.replace("http://www.dixieandtheninjas.net/dynasties/playermenu.php")
} else if (result == '2') {
//$('#logininfo').empty();
$('#logininfo').attr('value', '')
$('#password').attr('value', '')
alert("Login failed. Please try again, or register if you have not already created an account.");
} else {
alert("Something has gone wrong!");
alert (result);
}
} // end success
}); // end ajax
} else {
alert ("Please enter a username and password.");
}
}); /// end click function for button
}); //// end
</script>
Since you aren't truly submitting the form in the jQuery one, the browser doesn't know that the user has attempted to use this as input vs just typed something in and then went to another page. Because of that, you won't be seeing it in the stored form data.

Categories