Submission and receiving ajax form - php

I have a php script, only for learning purposes. I would like to use on my web app ajax form. Never did it, this is testing php script. So I would like to send via ajax form name and password, in php script will be checked if its correct and it will return either success(when login and password correct) or error(when no match). My problem is how to send it and receive it correctly in js or jQuery. Anyone who could help me maybe with better idea and/or better secure function of doing this?
I found on stackoverflow and tryed this script:
//bind an event handler to the submit event for your login form
$('#login_form').live('submit', function (e) {
//cache the form element for use in this function
var $this = $(this);
//prevent the default submission of the form
e.preventDefault();
//run an AJAX post request to your server-side script, $this.serialize() is the data from your form being added to the request
$.post($this.attr('action'), $this.serialize(), function (responseData) {
//in here you can analyze the output from your server-side script (responseData) and validate the user's login without leaving the page
});
});
And I was wondering if in php script it could work like this?:
<?php
$username = $_GET["name"];
$password = $_GET["password"];
if($username="*****" && $password==********)
{
header('Location:http://*****************/jaz/imes/index.html?login="success"');
}else{
header('Location:http://*****************/jaz/imes/index.html?login="error"');
}
?>
And as I said this is just a test script just for learning more about it.

First of all, try to use on() method if you're using jQuery 1.8+
Another thing is that you should set the session for that user in the PHP script, then redirect the user using the js:
jQuery:
$('#login_form').on('submit', function(){
$.post($this.attr('action'), $this.serialize(), function (responseData) {
if(responseData == 'success'){
window.location = "userpanel.php"
}else{
alert('NO MATCHES');
}
});
});
PHP:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
// VALIDATING HERE, in db maybe?
if($username == 'blah' && $password == 'blah'){
$_SESSION['username'] = $username;
echo "success";
}else{
echo "failed";
}
?>
And in your HTML form you need to have 2 inputs with IDs as "username" and "password" so the above code could work.

Related

can't get event.preventDefault() or return false to work. been trying from morning until evening

I have been creating a form that for users to log into my site that uses jquery to preform login validation and also has a PHP fallback just in case Javascript is disabled. The user's login form in itself is a lightbox. The way I am trying to design it is so that if there's an error, the error message will appear directly in the lightbox without closing it or redirecting the user. I am basically checking to things. If the 'username' and 'password' field have been filled and if the 'username' and 'password' fields can be validated. Javascript works perfectly when I check to see if the fields have been filled out. The 'return false' works, the error message appears inside the lightbox and everything is 'honky dory'. but when it comes to validation, I use ajax to check the database and if there's a problem it does not return false.
Actually what's happening is that the error message 'will' appear at the top of the lightbox for a split second and then it submits to PHP and PHP is redirecting it.
So here is the breakdown of the code.
$('body').on('click','[name=submit11]',function(){
$('.error').remove();
var req = ['username','password'];
var div = '#login_form';
validate(div,req);
if($('.error').length == 0){
var login = true;
var username = $(this).siblings('[name=username]').val();
var password = $(this).siblings('[name=password]').val();
$.post('../ajax/multipurpose.php', {login:login,username:username,password:password},function(data){
if($.trim(data) != ''){
$('#login_form').prepend("<div class='error'>"+data+"</div>");
}
});
}
if($('.error').length > 0){
event.stopPropagation();
return false;
}
});
The validate function is a custom function I am using in jquery and that's working perfectly. The problem begins inside the second if statement after the ajax has been performed. In this if statement, there will be an error if ajax finds an error. Here is the code that's inside the multipurpose.php page.
//Used to validate the username and password via ajax
if(isset($_POST["login"])):
$username = trim($_POST["username"]);
$password = trim($_POST["password"]);
if(!$found_user = User::authenticate($username,$password)):
echo "Username/Password combination is invalid.";
endif;
endif;
Another problem that I noticed is that if there is an error and I type alert($('.error').length) the value of 0 will show in the alert box and then after I click on "OK" in the alert box the value will appear in the lightbox and then submit to PHP. This is only for the ajax portion, not for the validate() custom function. Here is the code for the validate() function just in case anyone needs to see it.
function validate(div,fields){
var boxes = ['pounds_or_kilos','activity'];
$(div+' .error').remove();
$(fields).each(function(key,value){
if($.inArray(value,boxes) == -1){
text = $('[name='+value+']').val();
if($.trim(text) == ''){
removeLoader();
addError(div,value);
}
}else if(!$('[name='+value+']:checked').length){
addError(div,value);
}
});
}
I've tried EVERYTHING inside that second if statement to stop it from submitting. I've tried return false...in which I use in MANY areas of the site without problems, I tried event.preventDefault(), I've tried putting an e inside the click function and using e.preventDefault(), I've also tried the event.stopPropagation() and still nothing. Someone please help me.
$.post is async. So if there is error, you append it after the second check if($('.error').length > 0) and so you didn't prevent form submit behaviour.
What you can do is prevent this behaviour in all cases and if no error regarding ajax request, then submit form manually (using native DOM method), e.g:
$('body').on('click', '[name=submit11]', function() {
var form = $(this).closest('form').get(0);
$('.error').remove();
var req = ['username', 'password'];
var div = '#login_form';
validate(div, req);
if ($('.error').length == 0) {
var login = true;
var username = $(this).siblings('[name=username]').val();
var password = $(this).siblings('[name=password]').val();
$.post('../ajax/multipurpose.php', {
login: login,
username: username,
password: password
}, function(data) {
if ($.trim(data) != '') {
$('#login_form').prepend("<div class='error'>" + data + "</div>");
}
else {
form.submit();
}
});
}
return false;
});

Jquery Login Control in Php

I have a problem with jQuery. I'm checking the password and username with the code above.
It's working but the issue here is how can I send the data from this HTML form to my PHP file, or how can I start a session here and transfer it to PHP?
$("#girisButon").click(function (giris) {
if ($("#kadi").val() == "" || $("#sifre").val() == "")
alert('Username or Password is empty');
else
$.post($("#login").attr("action"),
$("#login :input").serializeArray(),
function (data) {
if (data == "1") {
$("#mesaj").removeClass("mesaj").addClass("basarili").text("OK").fadeIn(300);
// window.location.replace("index.php");
} else {
$("#mesaj").removeClass("basarili").addClass("mesaj").text("WRONG").fadeIn(300);
$("#giris").effect("shake", {
times: 2
}, 300);
}
});
$("#login").submit(function () {
return false;
});
});
$("#login").submit(function () {
window.location = 'phpprocessingpage.php';
});
Then, in phpprocessingpage.php, use POST variables to access any <input> elements that were part of the #login form:
$_POST['input1']
I like to save POST variables to my own local variables in this manner:
$input1 = (isset($_POST['$input1'])) ? $_POST['$input1'] : '';
You can't start a session on javascript and transfer it to PHP. You need to call PHP file on background with necessary parameters and start the session.
According to your script, you are currently making a request to your PHP file using $.post method, which takes URL from #login's action attribute.
Simply edit the PHP file and create sessions. After that, echo 1 to browser so javascript can understand your response.
Finally, this is the block that runs if server returns 1
if (data == "1") { }
Do whatever you want here. Sessions should be created.

Jquery form plugin

I am using the Jquery form plugin to submit a login form data. This works well but I have problem redirecting a successful logged in user to the client panel from the login page in my PHP script, that is whenever the user is logged in successfully, I redirect using header("location:panel.php") in my php script, this page is sent back to the login page as a response and it will be embedded in the login page instead of showing as a whole page.
jquery code;
$(document).ready(function(){
$("#loginform").ajaxForm({
target: '#responselogin'
}).submit();
});
php code;
<?php
$username=$_POST['username'];
$password=$_POST['password'];
if($username=="tarhe" && $password=="oweh") {
header("location:panel.php");
} else {
echo"login failed";
}
?>
Please I need help, thanks in advance
your using ajax, so your 301 location header will have no effect to the overall browser window. you will have to return a structured data to your javascript and have javascript redirect instead.
$(document).ready(function(){
$("#loginform").ajaxForm({
success: function (data) {
if (data == "login failed") {
$("#responselogin").html("Login Failed");
} else {
window.location.href = "panel.php";
}
}
).submit();
});
its actually better if you use json response for this. Since it's formatted better for browser consumption.
for handling this using json you can do the following. first change your php code to return a json response
$success = 0;
if($username=="tarhe" && $password=="oweh") {
$success = 1;
}
echo json_encode(array('success' => $success));
Then in your javascript code
$(document).ready(function(){
$("#loginform").ajaxForm({
type: 'json',
success: function (data) {
if (data.success == 0) {
$("#responselogin").html("Login Failed");
} else {
window.location.href = "panel.php";
}
}
).submit();
});
I don't think you can use the location flag inside the http header with ajax. Think about it: You submit a form with ajax, so you're getting the response back in Javascript, and not into the browser.
Bind a success handler to the .submit() form, and set window.location.href=http://your-url.com
You are using ajax so make a response data and on success redirect the user.
window.location.href = "somewhere.html";

Call Javascript function from within PHP block [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to call a JavaScript function from PHP?
I'm working on a project for school, and I'm struggling with the login page. In my PHP code, if the user enters an incorrect username or password, I want to call a Javascript function that displays a message and briefly changes the background colour where the message is shown. Here are my JS and PHP code blocks:
<script>
var flashContent = function () {
document.getElementById("outputlogin").style.backgroundColor = "#ffff00";
document.getElementById("outputlogin").innerHTML = "Incorrect login.";
function proxy() {
updateColor(0);
}
setTimeout(proxy, 50);
}
var updateColor = function (newColor) {
var hexColor = newColor.toString(16);
if (hexColor.length < 2)
hexColor = "0" + hexColor;
var colorString = "#ffff" + hexColor;
document.getElementById("outputlogin").style.backgroundColor = colorString;
function proxy() {
updateColor(newColor);
}
if (newColor < 255) {
newColor = newColor + 5;
setTimeout(proxy, 50);
}
}
</script>
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if(($username == "Ben") && ($password == "thepassword")){
//echo "SUCCESS";
session_start();
$_SESSION['bensedmgallerysesh'] = session_id();
header("Location:../index.php");
}else{
if($username != "" && $password != ""){
javascript:flashContent();
}
}
?>
Right now, after hitting the login button, I get the error message:
Fatal error: Call to undefined function flashContent()
How do I fix this?
You're trying to call a client side function in a server side script. You COULD do this:
if($username != "" && $password != ""){
?>
<script type="text/javascript">
flashContent();
</script>
<?php
}
But it might be smarter to actually separate the logic in a way that prevents you from trying to write server side processing like this. Organizational skills go a long way in this business.
Have you tried doing this:
echo '<script type="text/javascript"> flashContent(); </script>';
Instead of:
javascript:flashContent();
I dont think there is such thing like javascript: functionName()..
Javascript runs in user space, interpreted by the browser.
PHP runs in server space, and is processed by a preprocessor.
What you should do there is test the username and password in PHP, and if they are wrong send back a JSON reply to the client. In the client, parse the JSON data and show the corresponding message. You may want to do this with AJAX.
Hope that works
You cannot call a Javascript function like that with php, you would need to echo out the script calling the function in javascript. Something like this might work:
<?php
echo '<script> window.onload = function(){ flashContent(); } </script>';
?>
But that might not be a great way to do it. Php runs on the server before javascript runs on the browser. One better way to have the two languages communicate is to send AJAX calls to the php script.
EDIT
To clarify: You can echo out a call to a Javascript function in the script, and it will be run where you echoed it. But here, php will still just treat Javascript as a string to be printed on the document.

JQuery and PHP validation problem?

I want to do the validation on my PHP side and then have my JQuery code display your changes have been saved when the submit button is clicked but the JQuery code states that the changes have been saved even when the validation fails.
How can i fix this so that PHP can do the validation and then JQuery can do its thing when PHP has finished its validation?
Here is my Jquery code.
$(function() {
$('#changes-saved').hide();
$('.save-button').click(function() {
$.post($('#contact-form').attr('action'), $('#contact-form').serialize(), function(html) {
$('div.contact-info-form').html(html);
$('#changes-saved').hide();
$('#changes-saved').html('Your changes have been saved!').fadeIn(4000).show();
});
$('a').click(function () {
$('#changes-saved').empty();
$('#changes-saved').hide();
});
return false; // prevent normal submit
});
});
Here is part of my PHP code.
// Check for an email address:
if (preg_match ('/^[\w.-]+#[\w.-]+\.[A-Za-z]{2,6}$/', $_POST['email'])) {
$email = mysqli_real_escape_string($mysqli, strip_tags($_POST['email']));
} else {
echo '<p class="error">Please enter a valid email address!</p>';
}
in the jquery you can add a if statment that check if the php validation pass,
in the php you need to return a value like 1\0 or true \ false.
and check this parameter in jquery
i add example its using json but is the same issue
jquery :
$.post($('#contact-form').attr('action'), $('#contact-form').serialize(), function(data_pack){
if(data_pack.msg ==1){
# success do something ....
.........
}
alert(data_pack.html);
}, 'json');
the php code like :
if($validation_ok){
$arr = array('msg'=>1,'html'=>$html);
}
else {
$arr = array('msg'=>0,'html'=>$error_msg);
}
echo json_encode($arr);
exit;
You should validate it with both client-side and server-side (ie. with both JavaScript and PHP). If this is not possible, I'd consider posting the form asynchronously and parsing the reply from the server with javascript to determine whether the changes were saved.

Categories