How to check the login using jquery post? - javascript

I am trying to create a login test application using jquery post, php ..
It is reading the value but not sending the data to server.php and returning the data.
HTML CODE
<div class="contact-form pad-25">
<div class="subpage-title">
<h5>Please Login</h5>
</div>
<div>
<div class="row">
<div class="col-md-4">
<input class="form-control" placeholder="Name" type="text" id="fname" name="firstname">
<input class="form-control" type="password" placeholder="Pass" type="text" id="pass" name="password" style="display:none">
</div>
</div>
<a class="btn btn-flat flat-color btn-rounded" id="next_name">NEXT</a>
<button class="btn btn-flat flat-color btn-rounded" type="submit" id="submit" style="display:none">Submit</button>
<div>
<!-- row-fluid -->
</div>
//SCRIPT
<script type="text/javascript">
$(document).ready(function(){
$("#next_name").click(function(){
$("#fname").hide('slow');
$("#pass").show('fast');
$("#next_name").hide();
$("#submit").show();
$("#submit").click(function(){
var r=confirm("Login Confirmaition!!")
if(r==true)
{
//alert("asd");
var pass=$("#pass").val();
var fname=$("#fname").val();
alert(pass);
alert(fname);
$.post('server.php', {fname:fname, pass:pass, type:'passwordcheck'}, function(msg){
alert(msg);
});
}
});
});
});
</script>
SERVER SIDE CODE
I tried to dump the data but the application is not reaching the server.php at all
<?php
//echo "asdasd";
$type=$_POST['type'];
$fname=$_POST['fname'];
$pass=$_POST['pass'];
//var_dump($fname);
$data = '{"name":"Pramit", "password":"Pramit123"}';
if($type=='passwordcheck'){
$phpdata = json_decode($data);
if($phpdata->name == $fname && $phpdata->password == $pass)
{
echo "success";
}
else
{
echo "fail";
}
}
?>

In your script, you have an error.
<script type="text/javascript">
$(document).ready(function(){
$("#next_name").click(function(){
$("#fname").hide('slow');
$("#pass").show('fast');
$("#next_name").hide();
$("#submit").show();
$("#submit").click(function(){
var r=confirm("Login Confirmaition!!")
if(r==true)
{
pass=$("#pass").val();
fname=$("#fname").val();
//$.post('/server.php', {fname:fname, pass:pass, type:'passwordcheck'}, function(msg){
$.post('http://localhost/server.php', {fname:$fname, pass:$pass, type:'passwordcheck'}, function(msg){
alert(msg);
});
}
});
});
});
</script>
If you are in the same server where are you doing the request, you haven't got to insert the server, but if you put the server, i recommend you to put at least the protocol, because that request is doing on http://localhost/localhost/server.php, thats why you can't see the receive in the server part.
Remember too that in Javascript, variables are written like that:
var variable1;
variable = variable1;
Never put the variables like PHP, using the $ symbol
Tell me if that is useful to you :D

You are calling wrong url you must add http:// in your post url like,
$.post('http://localhost/server.php'...

Related

Multiple file upload using jquery serialization works only at the second call

I experience a strange problem:
Form ajax call with multiple files and form values works perfect, but only on the second call. First call ends up the the success: function(result) "else" condition. Second call works perfect and sends all data to the php. So I hit the submit button once and it shows up an empty error box and I hit the submit button again and everything works perfect.
How is that possible and how to solve that?
UPDATE #1: Found workaround, but not the solution. It works when I put if (result==="") { $(".form-application").submit(); } below the success function. But thats very dirty! ... and it upload all files twice! :-(
PROBLEM SOLVED David Knipe provided the solution!! Thank you so much!!
JQUERY:
$(".form-application").submit(function(e) {
e.preventDefault();
$("#btnSubmit2").text("Please wait...");
$("#btnSubmit2").attr("disabled", true);
var files = $('#files')[0].files;
var form = $(this);
var error='';
var formData = new FormData(this);
grecaptcha.ready(function() {
grecaptcha.execute('6Le4Qb0UAAAAAHUPcsmVYIk7zc4XCsiBnf6oE-fP', {action: 'create_comment'}).then(function(token) {
$('<input>').attr({
type: 'hidden',
value: token,
name: 'token'
}).appendTo('form');
for(var count = 0; count<files.length; count++)
{
var name = files[count].name;
var extension = name.split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
{
error += "Invalid " + count + " Image File"
}
else
{
formData.append("files[]", document.getElementById('files').files[count]);
}
}
if(error == '')
{
$.ajax({
url: form.attr("action"),
method: form.attr("method"),
data: formData,
processData: false,
contentType: false,
success: function(result) {
if (result == "0") {
$("#btnSubmit2").text("Thank you!");
$("#btnSubmit2").attr("disabled", true);
$(".output_message").text("");
$(':input','.form-application')
.not(':button, :submit, :reset, :hidden')
.val('')
.prop('checked', false)
.prop('selected', false);
$(".output_message").append("<div class='alert alert-success alert-dismissible fade show' role='alert'>We have received your application!</div>");
} else {
$(".output_message").text("");
$(".output_message").append("<div class='alert alert-danger alert-dismissible fade show' role='alert'>"+result+"</div>");
$("#btnSubmit2").attr("disabled", false);
$("#btnSubmit2").text("try again");
}
}
});
}
else
{
alert(error);
}
});
});
return false;
});
HTML:
<form class="form-application" id="applicationform" method="post" action="https://<?PHP echo $_SERVER['HTTP_HOST']; ?>/include/process-application.php" enctype="multipart/form-data">
<input type="hidden" name="crsf" value="<?=$_SESSION['crsf']?>"/>
<input type="hidden" name="crsf-expire" value="<?=$_SESSION['crsf-expire']?>"/>
<div class="space40"></div>
<h6>Name</h6>
<input name="name" type="text" class="form-control" placeholder="Your Name">
<div class="space30"></div>
<h6>Email</h6>
<input name="email" type="text" class="form-control" placeholder="Your Email Address">
<div class="space30"></div>
<h6>Instagram Name</h6>
<input name="instagram" type="text" class="form-control" placeholder="Your Instagram Name">
<div class="space30"></div>
<h6>City & Country</h6>
<input name="from" type="text" class="form-control" placeholder="Where do you live?">
<div class="space30"></div>
<h6>Tell us more about you</h6>
<textarea name="message" class="form-control" rows="3" placeholder="Write some details about you, so we know you better."></textarea>
<div class="space30"></div>
<h6>Upload some photos of yourself</h6>
<div class="file-field">
<div class="btn btn-aqua">
<input name="files" id="files" type="file" accepts="image/*" multiple>
</div>
<div class="file-path-wrapper">
</div>
<div class="space20"></div>
</div>
</div>
<div class="col-12 text-center">
<button id="btnSubmit2" type="submit" class="btn btn-full-rounded btn-aqua">Submit Application</button>
<div class="space10"></div>
<span class="output_message"></span>
</div>
</form>
PHP Script /include/process-application.php
<?PHP
echo "0";
?>
OK, I think I've figured this out. $('<input>').attr(...); sets the token attribute on a new <input> element. But this is after var formData = new FormData(this);, so the token doesn't get included in formData. Then I guess you get an authentication error, and I guess it does the authentication before it even gets to the PHP part. It would just be a HTTP401 response with no body, hence "". But then, on the second attempt, the <input> has already been created with the correct token, and this ends up being used to authenticate.
Either keep onsubmit or action. Remove action from form tag, it will work

$.post variables not passing to php getting undefined index error

This code almost works, it inserts into the db and it is giving feedback on the page to say it has updated. However I am getting undefined index between lines 5-8 in the insert_message.php and my database is filling with blank entries (except the date).
Apologies for being new to jquery and AJAX. Need some help.
form
<form enctype='multipart/form-data' action='insert_message.php' method='POST' id='contact_form'>
<div class="row">
<div class="col-xs-6">
<div class='form-group'>
<label for='email'>Email:</label>
<input class='form-control' type='email' id='email' name='email' required='required' maxlength='35'/>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-6">
<div class='form-group'>
<label for='subject'>Subject:</label>
<input class='form-control' type='text' id='subject' name='subject' required='required' maxlength='35'/>
</div>
</div>
</div>
<div class="form-group">
<label for='message'>Message:</label>
<textarea class="form-control" placeholder="Message" id='message' required="required"></textarea>
</div>
<input type="hidden" name="reciever" id='receiver' value="Admin">
<input class='btn btn-primary' id='submit' type='submit' value='submit' >
</form>
<span id="result"></span>
jquery
<script>
$(document).ready(function(){
$("#submit").click( function(e) {
e.preventDefault();
var message1 = $('message').val();
var sender1 = $('sender').val();
var receiver1 = $('receiver').val();
var subject1 = $('subject').val();
$.post("insert_message.php", {message:message1, sender:sender1, receiver:receiver1, subject:subject1}, function(info) { $("#result").html(info);
});
clearInput();
});
$("#contact_form").submit( function() {
return false;
});
function clearInput() {
$("#contact_form :input").each( function() {
$(this).val('');
});
}
});
</script>
insert_message.php
<?php
include("connections/conn.php");
$getsubject = mysqli_escape_string($conn,$_POST["subject1"]);
$getmessage = mysqli_escape_string($conn,$_POST["message1"]);
$getsender = mysqli_escape_string($conn,$_POST["sender1"]);
$getreceiver = mysqli_escape_string($conn,$_POST["receiver1"]);
$date = date("Y-m-d");
$insertmessage = "INSERT INTO messages (id,subject,message,date,sender,receiver) VALUES (NULL,'$getsubject','$getmessage','$date','$getsender','$getreceiver')";
$insert = mysqli_query($conn, $insertmessage) ;
if($insert){
echo "Message Sent";
}else{
echo "Message did not send";
}
UPDATE
attempted alternative way but I still get the undefined index in the inser_message.php
$(document).ready(function(){
$("#submit").click( function(e) {
e.preventDefault();
$.ajax({
url: "insert_message.php",
type: "POST",
data: $("#contact_form").serialize(),
success: function(result){
$("#result").html(result);
}
});
});
});
You have several problems in both JS and PHP.
Adjust typo in input hidden where actually name="reciever" instead of name="receiver";
In your $("#submit").click() function you're trying to selecting elements with an invalid selector (e.g. $('message').val() instead of $("#message").val());
Adjust $_POST keys by removing 1 at end. If you have any doubt, print the whole array print_r($_POST);
This is not an error but a suggestion. Since you require conn.php to do your job, I would use require instead of include.
Remove the $conn and the 1's from your 'get' block and, for example:
$getsubject = mysqli_escape_string($_POST["subject"]);
$getmessage = mysqli_escape_string($_POST["message"]);
$getsender = mysqli_escape_string($_POST["sender"]);
$getreceiver = mysqli_escape_string($_POST["receiver"]);

window.location.href don't work with AJAX

For some reason, the "window.location.href" function does not work for me, can't seem to find out why.
This is the code from index.php:
<div class="dropdown-menu">
<div style="width: 300px;">
<div class="panel panel-primary">
<div class="panel-heading">Login</div>
<div class="panel-heading">
<label for="email">Email</label>
<input class="form-control" id="email" name="email" required />
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" required />
<p><br/></p>
Forgotten Password<input type="button" class="btn btn-success" name="login" id="login" value="Login">
</div>
</div>
<div class="panel-footer"></div>
</div>
</div>
And this is the function in the "action.php" file that is mentioned in the jQuery function:
<?php
if(isset($_POST["userLogin"])){
$email = mysqli_real_escape_string($con, $_POST["userEmail"]);
$password = md5($_POST["userPassword"]);
$sql = "SELECT * FROM user_info WHERE email = '$email' AND password = '$password'";
$run_query = mysqli_query($con, $sql);
if($run_query===false){
echo mysqli_error($con);
} else {
$row = mysqli_fetch_array($run_query);
$_SESSION["uid"]= $row["user_id"];
$_SESSION["name"]= $row["first_name"];
echo "welcome";
}
}
?>
This is the jQuery with the AJAX function:
$(document).ready(function(){
$("#login").click(function(event){
event.preventDefault();
var email = $("#email").val();
var pass = $("#password").val();
$.ajax({
url : "action.php",
method : "POST",
data : {userLogin: 1, userEmail:email, userPassword:pass},
success : function(data){
if(data == "welcome"){
window.location.href = "profile.php";
}
/* alert(data);*/
}
});
});
});
notes:
As you can see in the jQuery function, there is this: "alert(data);". I wanted to look if it does work and put it on the screen without the "window.location.href" function to see that the "if" statement is correct, and it does work. Further more, when I go directly to the profile.php file, I see That the user is logged in, which means for me that the SQL functions is working fine, just it will not Re-Direct me to that (profile.php) page.
window.location.href expects an absolute url or a url relative to your domain (if it starts with a /).
If you only want to change the file part of your current path, you can use window.location.assign("profile.php")
If you want to redirect inside same domain
window.location.href = "/profile.php";
If you want to redirect to another domain
window.location.href = "http://www.antotherdomainname.com/profile.php";

call a php variable on hover using ajax

I have a variable $form in PHP and want it to be called or displayed whenever I hover a button.
I am a novice in ajax and don't know how to call the variable on hovering the button.
The code is:
Javascript
<script type="text/javascript">
$(document).ready(function() {
$("#login_button").hover(function() {
$("login-form").slideDown(400);
});
$("#login_button").hover(function() {
$("login-form").css('visibility','visible');
});
$("#login_button").dblclick(function() {
$("login-form").slideUp(1200);
});
$("#login-form").mouseleave(function() {
$("login-form").slideUp(1000);
});
});
</script>
PHP
<?php
$form = "<form action='?' method='post' id='login-form' name='login-form'><!-- class='form-horizontal well' -->
<strong><legend>Login</legend></strong>
<fieldset id='inputs'>
<input type='text' placeholder='Username' name='name' class='input-large' id='username'>
<input type='password' placeholder='Password' name='password' class='input-large' id='password'>
</fieldset>
<fieldset id='actions'>
<input type='submit' id='submit' class='btn btn-primary' value='Sign in'>
<div class='forgot'>
<strong><a href='?forget=1' id='forget'>Forgot Password?</a></strong>
</div>
</fieldset>
";
?>
You can using jquery post to get value and send it to your url :
$("#yourID").hover(function(){
$("fomr").css({visible:visible});
var url = "your-url-here";
var username = $("#input-for-username").val();
var password = $("#input-password").val();
//init ajax post
$.post(url,{username:username,password:password}.function(data){
//any thing here
});
});
No AJAX required;
$(document).ready(function() {
var php_var = '<?php echo json_encode($form); ?>';
});
Use it like:
$('#element').hover(function() {
$('#form_container').html(php_var);
}, function() {
$('#form_container').html('');
});
php is server-side and javascript (like html) is client-side.
What you have to do is display the content of $form in your page inside a hidden container, then use a trigger to display it:
<div id="login-form" style="display:none"><?php echo $form; ?></div>
For the js part, I simplify your example:
$("#login_button").hover(function(e) {
$("#login-form").slideDown(400);
},
function(e) {
$("#login-form").slideUp(1200);
});
jquery.hover doc
Notice the current version of jquery use this syntax:
$(document).on("hover", "#login_button", function(e){
// your commands here
});

Using php and javascript to put random number in txt file

I have a text input field with a button that generates a random number between 1 and 20 and displays within the text field. The problem I am having, is taking that random number that it generates and saving it into a .txt file. The file chat.txt is stored in the same directory as the rest of these files. Not sure I am going about this the right way. The following is the code. Any ideas would be helpful.
chat.php:
<div id="pageWrap">
<form action="roll.php" name="rollBox" method="post">
<input type="text" name="roll" id="demo">
<button type="button" name="button" onclick="myFunction()">Roll</button>
<script>
function myFunction()
{
var x=document.getElementById("demo")
x.value=Math.floor((Math.random()*20)+1);
}
</script>
<h2>Chat</h2>
<p id="name-area"></p>
<div id="chatWrap"><div id="chat-area"></div></div>
<form id="send-message-area">
<p>Your message: </p>
<textarea id="sendie" maxlength = '100' ></textarea>
</form>
</div>
roll.php:
<?php
if(isset($_POST['button']))
{
$roll = $_POST['roll'];
$file = fopen("chat.txt");
fwrite($file,$roll);
fclose($file);
print_r(error_get_last());
}
?>
If you are interested in your way of generating random number on client end with javascript:
on html:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="pageWrap">
<form action="page.php" id="rollBox" name="rollBox" method="post">
<input type="text" name="roll" id="demo">
<button type="submit" name="submit" >Roll</button>
<script>
$(document).ready(function () {
$('#rollBox').submit(function(e) {
var x=document.getElementById("demo");
x.value=Math.floor((Math.random()*20)+1);
e.preventDefault();
var obj = $(this), // (*) references the current object/form each time
url = obj.attr('action'),
method = obj.attr('method'),
data = {};
obj.find('[name]').each(function(index, value) {
var obj = $(this),
name = obj.attr('name'),
value = obj.val();
data[name] = value;
});
$.ajax({
url: url,
type: method,
data: data,
success: function(response2) {}
});
return false;
});
});
function myFunction()
{
var x=document.getElementById("demo")
x.value=Math.floor((Math.random()*20)+1);
document.getElementById("rollBox").submit();
}
</script>
</form>
<h2>Chat</h2>
<p id="name-area"></p>
<div id="chatWrap"><div id="chat-area"></div></div>
<form id="send-message-area">
<p>Your message: </p>
<textarea id="sendie" maxlength = '100' ></textarea>
</form>
</div>
on php change this
<?php
if(isset($_POST['submit']))//on submit
{
//echo 'here';
$roll = $_POST['roll'];
$file = fopen("chat.txt","w");//no mode selected
fwrite($file,$roll);
fclose($file);
print_r(error_get_last());
}
?>
This works and generates the chat.txt
The random number is only generated on the client side: you're not sending it to the server yet. You're starting a form (name=rollbox), which you not sending back to the server (also you seem to be missing a </form>. Either submit the form, or use AJAX to send the information to the back-end.
Why don't you just generate the random number in PHP, and then put it in the file with file_put_contents()like this?
<?php
$roll = rand(1,20);
file_put_contents("chat.txt",$roll);
?>
You have some issues with the HTML of your top FORM.
Try replace it with the following code:
<form action="roll.php" name="rollBox" method="post">
<input type="text" name="roll" id="demo">
<input type="submit" name="button" onclick="myFunction();" value="Roll">
</form>

Categories

Resources