Ajax not working on PHP page - javascript

I am trying to understand the basics of using AJAX in conjunction with PHP in order to use php pages to provide functions, but not change my 'view' on my MVC design.
So I created this basic login page...
<!DOCTYPE html>
<head>
<title>learning Php</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script type="text/javascript">
$(document).ready(function() {
$(#"login").click(function() {
var action = $("#form1").attr("action");
var form_data = {
username: $("#username").val(),
password: $("#password").val(),
is_ajax: 1
};
$.ajax({
type: "POST",
url: action,
data: form_data,
success: function(response)
{
if(response == 'success')
{
$("#form1").slideUp('slow', function() {
$("#message").html('<p class="success">You have logged in.</p>');
};
}
else
$("#message").html('<p class="error">Incorrect password or username.</p>');
}
});
return false;
});
});
</script>
</head>
<body>
<div>
<form name="form1" id="form1" method="post" action="loginForm.php">
<p>
<label for="username"> Username: </label>
<input type="text" id="username" name="username" />
</p>
<p>
<label for="password"> Password: </label>
<input type="text" id="username" name="username" />
</p>
<p>
<input type="submit" id="login" name="login" value="login" />
</p>
</form>
<div id="message"></div>
<div>
</body>
</html>
And this was my php page to "handle" to login...
<?php
$is_ajax = $_REQUEST['is_ajax'];
if(isset($is_ajax) && $is_ajax)
{
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if($username == 'demo' && $password == 'demo')
{
echo 'success';
}
}
?>
The problem I am having is that whenever I submit my login, I am redirected to "/loginForm.php" instead of staying on my current page and having the message change underneath the login form.
I tried using Firebug to help me track down what I suspected to be a javascript error, but to no avail.
Any idea on why I am being redirected or why the form is not submitting via Ajax?

One more mistake here
if(response == 'success')
{
$("#form1").slideUp('slow', function() {
}); <--- You Missed ")" here
}

a small mistake
$(#"login").click(function() {
This should be
$("#login").click(function() {
^ // # inside quotes.

Besides the typo and Rocky's good catch on the }); <--- You Missed ")" here
Both your username and password fields are the same.
<label for="username"> Username: </label>
<input type="text" id="username" name="username" />
and
<label for="password"> Password: </label>
<input type="text" id="username" name="username" />
the 2nd one should read as
<input type="text" id="password" name="password" />
In using everyone's answer, you will have yourself a working script.
Remember to hash your password once you go LIVE.
Edit sidenote: I've made a note below about using a button, rather than an input.
Here's a rewrite, just in case. However that input needs to be a <button>.
<!DOCTYPE html>
<head>
<title>learning Php</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script type="text/javascript">
$(document).ready(function() {
$("#login").click(function() {
var action = $("#form1").attr("action");
var form_data = {
username: $("#username").val(),
password: $("#password").val(),
is_ajax: 1
};
$.ajax({
type: "POST",
url: action,
data: form_data,
success: function(response)
{
if(response == 'success')
{
$("#form1").slideUp('slow', function() {
$("#message").html('<p class="success">You have logged in.</p>');
});
}
else
$("#message").html('<p class="error">Incorrect password or username.</p>');
}
});
return false;
});
});
</script>
</head>
<body>
<div>
<form name="form1" id="form1" method="post" action="loginForm.php">
<p>
<label for="username"> Username: </label>
<input type="text" id="username" name="username" />
</p>
<p>
<label for="password"> Password: </label>
<input type="text" id="password" name="password" />
<!--
Your original input
<input type="text" id="username" name="username" />
-->
</p>
<button type="submit" id="login" name="login" />LOGIN</button>
<!--
Your original submit input. Don't use it
<p>
<input type="submit" id="login" name="login" value="login" />
</p>
-->
</form>
<div id="message"></div>
</div>
</body>
</html>
Your last div just before </body> was unclosed </div>, I've changed that above.
Additional edit from comments.
It seems that there was probably a space inserted somewhere and the use of trim() was the final nail to the solution.
response.trim();
A special thanks goes out to Jay Blanchard to have given us a helping hand in all this, cheers Sam!
References (TRIM):
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim
http://php.net/manual/en/function.trim.php

Related

my form is making get request on same url, I don't know why it is doing it

I have login form, it is as follows, this will be let me login. I don't have experience with HTML and javascript.
<!DOCTYPE html>
<html lang="en">
<body>
<div class="container">
<h1> <b> Please sign in</b></h1>
<div id="login">
<form name="salesForm" id="submit_form">
<div class="form-group" id="UserNameD" >
<label for="UserName">Username</label>
<input id="UserName" type="text" name="UserName" class="form-control" required style="color:black">
</div>
<div class="form-group" id="passwordD" >
<label for="password">password</label>
<input id="password" type="password" name="password" class="form-control" required style="color:black">
</div>
<input id="submit" type="submit" class="btn btn-primary" value="submit">
</form>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<script src="static/js/login.js?233"> </script>
</body>
</html>
I have following javascript file as follows:
$(document).ready(function() {
$('#submit_form').submit(function(ev) {
var form_data = $('#submit_form').serializeArray()
console.log(form_data);
$.ajax({
"type": "POST",
"async": false,
"url":'xxxx',
"data": form_data,
"cache": false,
"processData": false,
"contentType": false,
success: function ( res ) {
successcallback(res);
},
error: function( err ) {
alert("Login Fail");
}
});
function successcallback( res ) {
window.location.replace("xxxx");
}
});
});
It is not working, it is making get request at / not url that I put in login.js.
Thanks for your help
try to add:
$('#submit_form').submit(function(ev) {
ev.preventDefault(); // prevent default form behavior
to prevent page reload after sumbit clicked

ajax jquery is not working

I am trying to submit the login request using Jquery Ajax. But the form is not submitting. I am tried to find the issue but can not. the code is vey simple but as I have started learning javascript so I am failing to find the problem in my code. Below is the code Please find the problem with it......
$(function() {
//get form by id
var form = $('#login_form');
//get message container by is
var message = $('#message');
//prevent default on form submit
$(form).submit(function(event) {
event.preventDefault();
//serialize form data
var form_data = $(form).serialize();
$.ajax({
type: 'post',
url: $(form).attr('action'),
data: form_data
}).done(function(response) {
//set the class of message container to success
$(message).removeClass('error');
$(message).addClass('success');
//put data received from server
$(message).html(response);
//clear form
$('#email').val('');
$('#password').val('');
}).fail(function(data) {
//set the class of message container to error
$(message).removeClass('success');
$(message).addClass('error');
//put the error message
if (data.responseText !== '') {
$(message).html(data.responseText);
} else {
$(message).text('Sorry...! an unexpected error has occured...!');
}
});
});
});
<html>
<head>
<meta charset="UTF-8">
<title>Ajax Practice</title>
<link href="assets/css.css" rel="stylesheet" type="text/css" />
<script src="assets/jquery.js" type="text/javascript"></script>
<script src="assets/ajax_code.js" type="text/javascript"></script>
</head>
<body>
<div class="login_form_div">
<form action="login.php" method="POST" name="login_form" id="login_form" class="login_form">
<div class="label">
<label>Email:</label>
</div>
<div class="form_input">
<input type="text" name="email" id="email">
</div>
<div class="label">
<label>Password:</label>
</div>
<div class="form_input">
<input type="password" name="password" id="password">
</div>
<div class="form_input">
<button type="submit" name="submit_form" id="submit_form">Login</button>
</div>
</form>
<span class="message1 error success" id="message">
</span>
</div>
</body>
</html>
your html and javascript is working perfectly.
can you post your php code?.
otherwise try put this code in your login.php file:
<?php
echo "form submitted";
?>
If you are using js fiddle then import the jquery js file on the dropdown on the left side of the panel.
$(function () {
//get form by id
var form = $('#login_form');
//get message container by is
var message = $('#message');
//prevent default on form submit
$(form).submit(function (event) {
event.preventDefault();
//serialize form data
var form_data = $(form).serialize();
$.ajax({
type: 'post',
url: $(form).attr('action'),
data: form_data
}).done(function (response) {
//set the class of message container to success
$(message).removeClass('error');
$(message).addClass('success');
//put data received from server
$(message).html(response);
//clear form
$('#email').val('');
$('#password').val('');
}).fail(function (data) {
//set the class of message container to error
$(message).removeClass('success');
$(message).addClass('error');
//put the error message
if (data.responseText !== '') {
$(message).html(data.responseText);
} else {
$(message).text('Sorry...! an unexpected error has occured...!');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<meta charset="UTF-8">
<title>Ajax Practice</title>
<link href="assets/css.css" rel="stylesheet" type="text/css"/>
<script src="assets/jquery.js" type="text/javascript"></script>
<script src="assets/ajax_code.js" type="text/javascript"></script>
</head>
<body>
<div class="login_form_div">
<form action="login.php" method="POST" name="login_form" id="login_form" class="login_form">
<div class="label">
<label>Email:</label>
</div>
<div class="form_input">
<input type="text" name="email" id="email">
</div>
<div class="label">
<label>Password:</label>
</div>
<div class="form_input">
<input type="password" name="password" id="password">
</div>
<div class="form_input">
<button type="submit" name="submit_form" id="submit_form">Login</button>
</div>
</form>
<span class="message1 error success" id="message">
</span>
</div>
</body>
</html>
Actually the problem was here. as the default form submission is prevented through javascript and I was looking for the message.
if (isset($_POST['submit_form'])) {
$email = mysqli_real_escape_string($_POST['email']);
$password = mysqli_real_escape_string($_POST['password']);
if (!empty($email) && !empty($password)) {
echo "Login Must be Successful...!";
} else {
echo "Login Failed....!";
}
}

Google Form Response not working from the website

I'm using a Google Form's value to integrate with my website where I want to submit the form and store data in google sheet as form responses. I'm using AJAX to redirect to another page instead of google form submit page. But whenever I'm trying to submit it's redirecting to my page accurately but datas are not saved in google sheet. Here are my codes,
<strong>Full Name</strong>
<input type="text" name="Fullname" class="form-control" id="Fullname" />
<strong>Email Address</strong>
<input type="text" name="Email" class="form-control" id="Email" />
<strong>Subject</strong>
<input type="text" name="Subject" class="form-control" id="Subject" />
<strong>Details</strong>
<textarea name="Details" rows="8" cols="0" class="form-control" id="Details"></textarea><br />
<button type="button" id="btnSubmit" class="btn btn-info" onclick="postContactToGoogle()">Submit</button>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
function postContactToGoogle() {
var email = $('#Email').val();
var fullname = $('#FullName').val();
var subject = $('#Subject').val();
var details = $('#Details').val();
$.ajax({
url: "https://docs.google.com/forms/d/abcdefgh1234567xyz/formResponse",
data: {
"entry_805356472": fullname,
"entry_1998295708": email, "entry_785075795":
subject, "entry_934055676": details
},
type: "POST",
dataType: "xml",
statusCode: {
0: function () {
window.location.replace("Success.html");
},
200: function () {
window.location.replace("Success.html");
}
}
});
}
</script>
How can I save the data in google sheet? Am I missing something in my code? Need this help badly? Thanks.
You can directly copy the form from google view form page like shown in the demo, and then do the following changes in the AJAX call as shown below.
And now once you submit data it is visible in google forms, view responses.
$(function(){
$('input:submit').on('click', function(e){
e.preventDefault();
$.ajax({
url: "https://docs.google.com/forms/d/18icZ41Cx3-n1iW7yTOZdiDx9a6mySWHOy9ryd1l59tM/formResponse",
data:$('form').serialize(),
type: "POST",
dataType: "xml",
crossDomain: true,
success: function(data){
//window.location.replace("youraddress");
//console.log(data);
},
error: function(data){
//console.log(data);
}
});
});
});
<div class="ss-form"><form action="https://docs.google.com/forms/d/18icZ41Cx3-n1iW7yTOZdiDx9a6mySWHOy9ryd1l59tM/formResponse" method="POST" id="ss-form" target="_self" onsubmit=""><ol role="list" class="ss-question-list" style="padding-left: 0">
<div class="ss-form-question errorbox-good" role="listitem">
<div dir="auto" class="ss-item ss-text"><div class="ss-form-entry">
<label class="ss-q-item-label" for="entry_1635584241"><div class="ss-q-title">What's your name
</div>
<div class="ss-q-help ss-secondary-text" dir="auto"></div></label>
<input type="text" name="entry.1635584241" value="" class="ss-q-short" id="entry_1635584241" dir="auto" aria-label="What's your name " title="">
<div class="error-message" id="1979924055_errorMessage"></div>
<div class="required-message">This is a required question</div>
</div></div></div>
<input type="hidden" name="draftResponse" value="[,,"182895015706156721"]
">
<input type="hidden" name="pageHistory" value="0">
<input type="hidden" name="fvv" value="0">
<input type="hidden" name="fbzx" value="182895015706156721">
<div class="ss-item ss-navigate"><table id="navigation-table"><tbody><tr><td class="ss-form-entry goog-inline-block" id="navigation-buttons" dir="ltr">
<input type="submit" name="submit" value="Submit" id="ss-submit" class="jfk-button jfk-button-action ">
</td>
</tr></tbody></table></div></ol></form></div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
If you go to your form on Google and click on 'View Live Form', and then view source on the form, you'll see that the fields you want to upload have aname in the form entry.12345678; the id is in the form entry_12345678. You need to use the name value. Try this:
<script>
function postContactToGoogle() {
var email = $('#Email').val();
var fullname = $('#FullName').val();
var subject = $('#Subject').val();
var details = $('#Details').val();
$.ajax({
url: "https://docs.google.com/forms/d/abcdefgh1234567xyz/formResponse",
data: {
"entry.805356472": fullname,
"entry.1998295708": email,
"entry.785075795": subject,
"entry.934055676": details
},
type: "POST",
dataType: "xml",
statusCode: {
0: function () {
window.location.replace("Success.html");
},
200: function () {
window.location.replace("Success.html");
}
}
});
}
</script>

PHP Ajax response is empty using jQuery

At the moment I create a register "page". Here is the html code of the form
<form class="register_form" method="POST" action="insert.php">
<label class="label_register">Benutzername*:</label>
<div class="input_group">
<input class="input_register" id="register_username" name="username" type="text"/><span class="register_span">-</span>
</div>
<label class="label_register">Passwort*:</label>
<div class="input_group">
<input class="input_register" id="register_password_1" name="password" type="password"/><span class="register_span">-</span>
</div>
<label class="label_register">Passwort wdh.*:</label>
<div class="input_group">
<input class="input_register" id="register_password_2" name="password2" type="password"/><span class="register_span">-</span>
</div>
<label class="label_register">E-Mail Adresse*:</label>
<div class="input_group">
<input class="input_register" id="register_email" name="email" type="text"/><span class="register_span">-</span>
</div>
<button class="button button_register">Jetzt kostenlos registrieren</button>
<p class="register_hint">
* Pflichtfeld
</p>
</form>
Here is my jquery code
var username_bool = true;
var password_bool = true;
var email_bool = true;
$('.register_form').on('submit', function(){
if(username_bool == true && password_bool == true && email_bool == true){
$.ajax({
type: "POST",
url: "insert.php",
data: $(this).serialize(),
success: function(response){
console.log(response);
alert(response);
},
});
}
else{
alert("---");
}
return false;
});
And here is the php code
<?php
if(isset($_POST["username"]) && isset($_POST["password_1"]) && isset($_POST["email"])){
echo "response";
}
?>
Now I have sent the form, but the respone is empty. I use Firebug to debugg. What is my mistake? And I made also other mistakes?
Thanks for you help.
You seem to be checking for a field named password_1
isset($_POST["password_1"])
while it's named password
<input class="input_register" id="register_password_1" name="password" type="password"/><span class="register_span">-</span>
You'll have to make sure the name attribute matches the value you're checking
The problem i see is you check on isset($_POST["password_1"]) and that is not in the form as you named your password field "password"
<input class="input_register" id="register_password_1" name="password" type="password"/><span class="register_span">-</span>
you need to check using isset($_POST["password"])

Sending values to the action script continuously. How to do that?

I want to repeatedly send values of username and password to the php script. How do I do this ? Like to send the values to the action script, we use submit button but how can I send the values automatically to the script and that too continuously ?
<form method="post" action="processor.php">
<input type="username" value="suhail" />
<input type="password" value="secret_code" />
<input type="submit" />
</form>
Using the jQuery form plugin you can do the following:
setInterval(function() {
$('form').ajaxSubmit();
}, 1000);
Another solution is to target the form to an iframe so if you submit the form, it doesn't reload the page:
HTML:
<form id="myform" method="post" action="processor.php" target="frm">
<input type="username" value="suhail" />
<input type="password" value="secret_code" />
<input type="submit" />
</form>
<iframe name="frm" id="frm"></iframe>
JS:
var form = document.getElementById('myform');
setInterval(function() {
form.submit();
}, 1000);
try something like this
JAVASCRIPT
<script language=javascript>
var int=self.setInterval(function(){send_data()},1000);
function send_data()
{
document.getElementById('my_form').submit()
}
</script>
HTML
<form method="post" id="my_form" action="processor.php">
<input type="username" value="suhail" />
<input type="password" value="secret_code" />
</form>
<form id="myform" method="post" action="processor.php">
<input type="username" value="suhail" />
<input type="password" value="secret_code" />
<input type="submit" />
</form>
<script type="text/javascript">
var count=100,i=0;
for(i=0;i<count;i++) {
document.getElementById('myform').submit();
}
</script>
This will submit the form 100 times
Use Ajax, it's really easy with jQuery. To send the form data to the processor.php script:
var sendForm = function () {
$.ajax({
type: 'post',
url: 'processor.php',
dataType: 'JSON',
data: {
username: $('#username').val(),
password: $('#password').val()
},
success: function (data) {
// do something with the answer from server?
},
error: function (data) {
// handle error
}
});
}
So, sendForm is a function that sends the form data to the server. Now, wee need to set a timer that will invoke it repeatedly:
window.setInterval(sendForm, 1000); // sends form data every 1000 ms
You may you $.post or $.get or $.ajax request repeatedly to send continuous request.
$(document).ready(function(){
setInterval(function() {
var username = $("#username").val();
var password = $("#password").val();
var dataString = 'username='+username+"&password="+password;
$.post('login.php',dataString,function(response){
//your code what you want to do of response
alert(response);
});
}, 1000);
});
and html code is like following
<form method="post" action="processor.php">
<input type="username" value="suhail" id="username"/>
<input type="password" value="secret_code" id="password"/>
<input type="submit" />
</form>
This is a full HTML file doing what you want, read the comments.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form method="post" action="processor.php">
<input type="username" id="username" value="suhail" />
<input type="password" id="password" value="secret_code" />
<input type="submit" />
</form>
<script>
function send_request(username, password) {
var dataString = 'username='+username+"&password="+password;
$.post('login.php',dataString,function(response){
// You can check if the login is success/fail here
console.log(response);
// Send the request again, this will create an infinity loop
send_request(username, password);
});
}
// Start sending request
send_request($('#username').val(), $('#password').val());
</script>
Try this,
JS:
$(document).ready(function(){
var int=self.setInterval(function(){statuscheck()},1000);
function statuscheck()
{
var username = $("#username").val();
var password = $("#password").val();
$.ajax({
type:"post",
url:"processor.php",
dataType: "html",
cache:false,
data:"&username="+username+"&password="+password,
success:function(response){
alert(response);
}
});
}
});
HTML:
<form method="post" action="processor.php">
<input type="username" value="suhail" id="username"/>
<input type="password" value="secret_code" id="password"/>
<input type="submit" />
</form>

Categories

Resources