I am enable to get the success message..! - php

i am trying to get the user details into database and data is stored..i want a success message to fade in i have tried out some code but sadly its not working...plzz help me out of this..beg u pardon if am wrong..
here gose my register.php code
<?php
require_once 'DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => false);
if (!empty($_POST['fname']) && !empty($_POST['lname']) && !empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['mobile'])){
// receiving the post params
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$email = trim($_POST['email']);
$password = $_POST['password'];
$mobile = trim($_POST['mobile']);
// validate your email address
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
// valid email address
if ($db->isUserExisted($email)) {
// user already existed
$response["error"] = true;
$response["error_msg"] = "User already existed with " . $email;
echo json_encode($response);
} else {
// create a new user
$user = $db->storeUser($fname, $lname, $email, $password, $mobile);
if ($user) {
// user stored successfully
$response["error"] = false;
$response["uid"] = $user["id"];
$response["user"]["fname"] = $user["fname"];
$response["user"]["lname"] = $user["lname"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = true;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
} else {
// invalid email address
$response["error"] = true;
$response["error_msg"] = "invalid email address";
echo json_encode($response);
}
} else {
$response["error"] = true;
$response["error_msg"] = "Required parameters are missing!";
echo json_encode($response);
}
?>
and here gose the .html file with jquery..
<html>
<head>
<title>jQuery Test</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src = "register.js"></script>
</head>
<body>
<!--html body-->
<form name = "register" id = "register" method = "POST">
<label>First name:</label>
<input type = text name = "fname" id = "fname" required>
<label>Last name:</label>
<input type = "text" name = "lname" id = "lname" required>
<label>E-mail:</label>
<input type = "email" name = "email" id = "email" required>
<label>Password</label>
<input type = "password" name = "password" id = "password" required>
<label>Mobile no:</label>
<input type = "number" name = "mobile" id = "mobile" required>
<input type="submit" value="Insert" name="submit" id = "submit">
</form>
<div id = "result" align = "right"></div>
</body>
</html>
here gose me /.js/ file
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
$.ajax({
url: "register.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val()
},
dataType: "JSON",
success: function (json) {
$("#result").html(json.user.email); // like that you can display anything inside #result div
$("#result").fadeOut(1500);
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});

There's no need to use JSON.stringify(jsonStr) because jQuery has already parsed the response object for you. jQuery will look at the Content-Type of the response and, if it's application/json, it will parse it, and provide the parsed result to your success handler.
Your jQuery should be like this:
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
$.ajax({
url: "register.php",
type: "POST",
data: {
fname: $("#fname").val(),
lname: $("#lname").val(),
email: $("#email").val(),
password: $("#password").val(),
mobile: $("#mobile").val()
},
dataType: "JSON",
success: function (json){
if(json.error){
$("#result").html(json.error_msg); // display error message
}else{
$("#result").html(json.user.email); // like that you can display anything inside #result div
}
$("#result").fadeOut(1500);
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});

Related

send data to a PHP file

i am trying to send data to a php file but its not working.
Here is my code:
App.js:
.controller('sign_up', function ($scope, $http) {
$scope.login = function () {
var request = $http({
method: "post",
url: "js/login.php",
data: {
email: $scope.email,
password: $scope.password
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
/* Successful HTTP post request or not */
request.success(function (data) {
if(data == '1'){
$scope.responseMessage = "Successfully Logged In";
}
else {
$scope.responseMessage = "Username or Password is incorrect";
}
});
}
});
index.html:
<div ng-controller='sign_up'>
<input class="form-control" type="text" ng-model="email" name="email"
placeholder="Enter Your Email">
<br>
<input class="form-control" type="password" ng-model="password"
name="password" placeholder="Enter Your Password"><br>
<button class="btn btn-success" ng-click="login()">Login</button><br>
<span>{{responseMessage}}</span>
</div>
login.php:
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$email=$_POST['email']
$password=$_POST['password']
$email = $request->email;
$password = $request->password;
echo json_encode($email);
echo "email=".$email;
if($email == "two" && $password== "one"){
echo "1";
}
else {
echo "0";
}
?>
use $request = json_decode($postdata,TRUE);
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata,TRUE);
$email = $request->email;
$password = $request->password;
if($email == "two" && $password== "one"){
echo "1";
}
else {
echo "0";
}
?>
also change the content type to json
var request = $http({
method: "post",
url: "js/login.php",
data: {
email: $scope.email,
password: $scope.password
},
headers: { 'Content-Type': 'application/json' }
});

Executing PHP function on click of a link

I want to trigger a PHP function on click of a link or button. How can I do it? I have used javascript onclick functionality but is there any way to do so ?
Better go for jquery, ajax for sending data in json format.! Like
code.js
$(document).ready(function(){
$("#submit").click(function(e){
var status = $('form')[0].checkValidity();
if(status){
var formData = new FormData($('form')[0]);
$.ajax({
url: "code.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
async: false,
dataType: "JSON",
success: function(json){
if(json.error){
alert(json.error_msg);
e.preventDefault();
}else{
alert("Data stored successfully!");
}
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
}
});
});
code.php
<?php
define('HOST','localhost');
define('USER','***');
define('PASS','***');
define('DB','***');
$response = array();
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
if(!mysqli_connect_errno()){
$error_flag = false;
/*foreach($_POST as $value){
if(empty($value)){
$error_flag = true;
break;
}
}*/
if(!$error_flag){
//receiving post parameters
$sdn =$_POST['sdn'];
// create a new user profile
$sql = "INSERT INTO safety(sdn, created_at) VALUES ('$sdn',NOW())";
if(mysqli_query($con,$sql)){
$response["error"] = false;
echo json_encode($response);
}else{
$response["error"] = true;
$response["error_msg"] = "INSERT operation failed";
echo json_encode($response);
}
}else{
$response["error"] = true;
$response["error_msg"] = "Few fields are missing";
echo json_encode($response);
}
}else{
$response["error"] = true;
$response["error_msg"] = "Database connection failed";
echo json_encode($response);
}
?>
And lastly use jquery link inside
code.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src = "code.js"></script>
</head>
<body>
<form id="form" name ="form" method = "POST" action="Next_page.html" class="wizard-big" autocomplete = "off">
<div class="col-sm-3 form-group">
<input type="text" placeholder="sdn" class="form-control" id="sdn" name="sdn">
<div class="col-sm-12 form-group">
<input style="width:100%" type="submit" name = "submit" id = "submit" value = "Save and continue" class="btn btn-success">
</div>
</div>
</form>
</body>
</html>

Using JQuery AJAX to submit a form to PHP, return data is empty

When I run this code below, the "data" returned is an empty string "[]". (At least viewed through the Chrome Console Viewer)
If I comment out the "event.preventDefault();" line in the JS I get a page reload, as expected, and a JSON string with results that passes JSONLint. I know the PHP is working as I am getting new inserts into the mySQL database and the return values make sense.
Everything seems to run correctly even with "data" is returned empty... (i.e. I am getting the console.log of FIRST first and SECOND second followed by the empty string.) I just can't get the returned "data" values in the JS context.
I'm kinda new to web development, not to programming... but does anyone spot a rookie mistake? I have read over about 12 similar questions and tried many things, but nothing is helping...
Thanks in advance.
$(document).ready(function() {
$('form').submit(function(event) {
var formData = {
'firstName': $('input[name=firstName]').val(),
'lastName': $('input[name=lastName]').val(),
'email': $('input[name=email]').val(),
'password': $('input[name=password]').val()
};
$.ajax({
type: 'POST',
url: 'createaccount.php',
data: formData,
dataType: 'json'
})
.done(function(data) {
console.log("SECOND");
console.log(data);
});
console.log("FIRST");
event.preventDefault();
});
});
input {
border-radius: 5px;
border-width: 1px;
margin: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-lg-12 text-center">
<div class="col-lg-4"></div>
<div class="col-lg-4 text-right">
<h1>Join website</h1>
<form action="createaccount.php" method="post">
<label>First Name:</label><input type="text" name="firstName" /><br/>
<label>Last Name:</label><input type="text" name="lastName" /><br/>
<label>Email:</Label><input type="email" name="email" /><br/>
<label>Password:</label><input type="password" name="password" /><br/>
<input type="submit" value="Sign Up" name="submit" />
</form>
</div>
<div class="col-lg-4"></div>
</div>
</div>
<?php
$firstName = $_POST["firstName"];
$lastName = $_POST["lastName"];
$email = $_POST["email"];
$password = $_POST["password"];
$submit = $_POST["submit"];
$errors = array();
$data = array();
if ($submit) {
if (!$email) {
$errors['email'] = "Email is required.";
}
else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['validemail'] = "Valid email is required.";
}
if (!$password) {
$errors['password'] = "Password is required.";
}
else {
if (strlen($password) < 8) {
$errors['passwordlength'] = "Password must be at least 8 characters long";
}
if (!preg_match("#[A-Z]+#", $password)) {
$errors['passwordcaps'] = "Password must contain at least one Capital Letter";
}
}
if (empty($errors)) {
require 'dbconnect.php';
$query="SELECT * FROM Users WHERE email='".mysqli_real_escape_string($link, $email)."'";
$result = mysqli_query($link, $query);
$results = mysqli_num_rows($result);
if ($results) {
$errors['exists'] = "That email address is already registered.";
}
else {
$firstName = mysqli_real_escape_string($link, $firstName);
$lastName = mysqli_real_escape_string($link, $lastName);
$email = mysqli_real_escape_string($link, $email);
$password = md5(md5($email).$password);
$query="INSERT INTO `Users` (`FirstName`, `LastName`, `Email`, `Password`, `IsRater`, `IsRatee`) VALUES('$firstName', '$lastName', '$email', '$password', '1', '1');";
if(!mysqli_query($link, $query)) {
$errors['SQLQuery'] = "Failed SQL Insert" . mysqli_error($link);
}
else
{
$data['success'] = true;
$data['message'] = 'Your account has been created!';
}
}
}
if(!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
}
}
echo json_encode($data);
?>
The PHP code checks whether $_POST['submit'] is set before doing anything with the form data, but you never set that in formData. Try:
var formData = {
'firstName': $('input[name=firstName]').val(),
'lastName': $('input[name=lastName]').val(),
'email': $('input[name=email]').val(),
'password': $('input[name=password]').val(),
'submit': 'on'
};

Json response not showing in div

Hopefully someone can help me here, I am tired of banging my head on the desk. I am not sure why the json response isn't showing up on the div below the form. I can see the response in my firebug debugger(Firefox debugger), but nothing shows up in div.
I've the main register.php that contains the form and javascript and calls another register.php file with the php code that calls the registration function. I can create new account and data files to the database without any problem, but I am unable to get the response back in my div. Please help!
register.php
<body>
<div class="logo"></div>
<div class="form">
<form id="register" method="post">
<input type="text" name="email" id="email" placeholder="Email Address" /><br/><br/>
<input type="text" name="username" id="username" placeholder="Username" />
<input type="password" name="password" id="password" placeholder="Password" />
<input type="submit" id="register" value="Register" />
</form>
</div>
<div class="small">
I already have an account<br/>
</div>
<div id="message"></div>
<script type="text/javascript">
$(document).ready(function(){
var myForm = $('#register');
myForm.validate({
errorClass: "errormessage",
onkeyup: false,
errorClass: 'error',
validClass: 'valid',
rules: {
email: { required: true, email: true, minlength: 3, maxlength: 100 },
username: { required: true, minlength: 3, maxlength: 30 },
password: { required: true, minlength: 3, maxlength: 100 }
},
errorPlacement: function(error, element)
{
var elem = $(element),
corners = ['right center', 'left center'],
flipIt = elem.parents('span.right').length > 0;
if(!error.is(':empty')) {
elem.filter(':not(.valid)').qtip({
overwrite: false,
content: error,
position: {
my: corners[ flipIt ? 0 : 1 ],
at: corners[ flipIt ? 1 : 0 ],
viewport: $(window)
},
show: {
event: false,
ready: true
},
hide: false,
style: {
classes: 'ui-tooltip-red'
}
})
.qtip('option', 'content.text', error);
}
else { elem.qtip('destroy'); }
},
success: $.noop,
})
});
$("#register").submit(function(event) {
if($("#register").valid()) {
event.preventDefault();
var $form = $( this ),
mail = $form.find('input[name="email"]').val(),
user = $form.find('input[name="username"]').val(),
pass = $().crypt({method:"sha1",source:$().crypt({method:"sha1",source:$form.find('input[name="password"]').val()})});
$.post("inc/action.php?a=register", {email: mail, username: user, password: pass},
function(data) {
$("#message").html('<p> code: ' + data.error + '</p>');
$("#message").append('<p> message: ' + data.message + '</p>');
}, "json"
);
}
else
{
$("[id^=ui-tooltip-]").effect("pulsate", {times: 3}, 300);
return false;
}
});
</script>
</body>
register.php
<?php
if(isset($_POST['email'])) { $email = $_POST['email']; } else { echo 1; exit(); }
if(isset($_POST['username'])) { $username = $_POST['username']; } else { echo 1; exit(); }
if(isset($_POST['password'])) { $password = $_POST['password']; } else { echo 1; exit(); }
$register = $auth->register($email, $username, $password);
$return = array();
switch($register['code'])
{
case 0:
$return['error'] = 1;
$return['message'] = "You are temporarily locked out of the system. Please try again in 30 minutes.";
break;
case 1:
$return['error'] = 1;
$return['message'] = "Username / Password is invalid";
break;
case 2:
$return['error'] = 1;
$return['message'] = "Email is already in use";
break;
case 3:
$return['error'] = 1;
$return['message'] = "Username is already in use";
break;
case 4:
$return['error'] = 0;
$return['message'] = "Account created ! Activation email sent to " . $register['email'];
break;
default:
$return['error'] = 1;
$return['message'] = "System error encountered";
break;
}
$return = json_encode($return);
echo $return;
Add header('Content-Type: application/json') before returning the json-encoded data.
in json.php
<?php
$data['error']=1;
$data['msg']="error";
header('Content-Type: application/json');
echo json_encode($data);
?>
in index.php
<script type="text/javascript">
$.ajax({
url:'json.php',
success:function(data){
$('body').html(data.msg);
}
});
</script>

Ajax Login return modified headers error [duplicate]

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
I am using wordpress as my base and made a custom login form.
ajax:
(function ( $ ) {
jQuery(document).ready(function() {
$("#login_form").submit(function(event){
//check the username exists or not from ajax
jQuery.ajax({
type: 'POST',
url: my_ajax.ajaxurl,
data: $('#login_form').serialize(),
cache: false,
//dataType: 'json',
success: function(result) {
var result=trim(result);
if( result == 'success' ){
window.location='/my-dashboard';
} else {
$('#message').html(result);
}
console.log(result);
}
});
return false;
});
});
function trim(str){
var str=str.replace(/^\s+|\s+$/,'');
return str;
}
}( jQuery ));
login form:
<p id="message" style="color:red;"></p>
<form method="post" action="" id="login_form">
<div align="center">
<div >
Email : <input name="email" type="text" id="email" value="" />
</div>
<div style="margin-top:5px" >
Password :
<input name="password" type="password" id="password" value="" />
</div>
<div class="buttondiv">
<input type="hidden" name="action" value="my_ajax_callback" />
<input type="hidden" name="func" value="check_login" />
<input name="submit" type="submit" id="submit" value="Login" style="margin-left:-10px; height:23px" /> <span id="msgbox" style="display:none"></span>
</div>
</div>
</form>
functions.php
// Ajax
add_action( 'wp_ajax_nopriv_my_ajax_callback', 'my_ajax_callback' );
add_action( 'wp_ajax_my_ajax_callback', 'my_ajax_callback' );
// Your Login function
function check_login( $params ){
require_once('lib/hash.php');
$session = new SC_Session;
// now you can use $session here
$message=array();
if(isset($_POST['email']) && !empty($_POST['email'])){
mysqli_real_escape_string($mysqli, $params['email']);
}else{
$message[]='Please enter email';
}
if(isset($_POST['password']) && !empty($_POST['password'])){
$password= mysqli_real_escape_string($mysqli, $params['password']);
}else{
$message[]='Please enter password';
}
$countError=count($message);
if($countError > 0){
for($i=0;$i<$countError;$i++){
echo ucwords($message[$i]).'<br/><br/>';
}
} else {
$hc=$mysqli->query("SELECT password FROM %table% email='".$email."' AND active=1");
while($hp = $hc->fetch_object()) {
$stored_hash = $hp->password;
}
$hasherd = new PasswordHash(8, false);
$check = $hasherd->CheckPassword($password, $stored_hash);
if($check) {
//now validating the username and password
$result=$mysqli->query("SELECT id, first_name, last_name, zip, email, password FROM %table% WHERE email='".$email."' AND active=1");
while($row = $result->fetch_object()) {
//if username exists
if($result->num_rows > 0)
{
$date = date('Y-m-d h:i:s');
$update_sql = $mysqli->query("UPDATE %table% SET last_login='".$date."'");
$firstname = $row->first_name;
$lastname = $row->last_name;
$zip = $row->zip;
$user_id = $row->id;
$sex = $row->sex;
$session->set_userdata( 'user_id', $user_id );
$session->set_userdata( 'email', $email );
$session->set_userdata( 'firstname', $firstname );
$session->set_userdata( 'lastname', $lastname );
$session->set_userdata( 'zip', $zip );
$session->set_userdata( 'sex', $sex );
}
}
echo ucwords('success');
//return $params;
} else{
echo ucwords('please enter correct user details');
}
}
}
/**
* Ajax Submit
*/
function my_ajax_callback() {
$response = call_user_func($_POST['func'], $_POST);
header( "Content-Type: application/json" );
echo json_encode($response);
exit;
}
The login currently works great, but whenever a error is thrown from $message it displays along with the header warnings.
Warning: Cannot modify header information - headers already sent by (output started at /%wordpresslocation%/wp-content/themes/%theme%/functions.php:77) in /%wordpresslocation%/wp-content/themes/%theme%/functions.php on line 86
null
ANSWER
I feel like an idiot, figured it out, I kept mixing php with javascript as I am proficient in php.
(function ( $ ) {
jQuery(document).ready(function() {
$('#message').slideUp();
$("#login_form").submit(function(event){
$('#message').slideUp();
//check the username exists or not from ajax
jQuery.ajax({
type: 'POST',
url: my_ajax.ajaxurl,
data: $('#login_form').serialize(),
dataType: 'json',
success: function(params) {
if( params == 'success' ){
$('#message').html(params).fadeIn();
document.location='/my-dashboard';
} else {
$('#message').html(params).fadeIn();
}
}
});
return false;
});
});
}( jQuery ));
and changed
echo ucwords('success');
//return $params;
} else{
echo ucwords('please enter correct user details');
}
to this
$params = 'success';
return $params;
}else{
$params = 'fail';
return $params;
and sent back the params
function check_login( $params ){
Thats because an error was printed (echo ucwords('please enter correct user details');)
Then, you try to set a header. That's not possible, headers always have to be set before anything else (that's how http works)
You will have to rewrite the parts that print text before the header is send. Also it doesn't send valid json so it wont work anyway

Categories