Ajax submit Form serialized data in php are null - javascript

I ve been searching all relative questions here and still cant figure out the problem I have.
I am using a simple modal form :
<p id="messages">Let's make today a great day!</p>
<form id="myloginform" name="myloginform" action="scripts/login.php" method="post" >
<div class="form-group">
<label for="username" class="">Enter username</label>
<input type="text" class="form-control input-lg c-square" id="username" name="username" placeholder="Username" required> </div>
<div class="form-group">
<label for="password" class="">Enter pass</label>
<input type="password" class="form-control input-lg c-square" id="password" name="password" placeholder="Password" required> </div>
<div class="form-group">
<div class="c-checkbox">
<input type="checkbox" id="login-rememberme" class="c-check">
<label for="login-rememberme" class="c-font-thin c-font-17">
<span></span>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn c-theme-btn btn-md c-btn-uppercase c-btn-bold c-btn-square c-btn-login" id="check">login</button>
</div>
</form>
I am using ajax to pass the form to a php file :
<script>
$(document).ready(function(){
$('form#myloginform').submit(function(e) {
var my_data = $('form#myloginform').serialize();
$.ajax({
type : 'POST',
url : 'scripts/login.php',
cache : false,
data : my_data,
contentType : false,
processData : false,
dataType: 'json',
success: function(response) {
//TARGET THE MESSAGES DIV IN THE MODAL
if(response.type == 'success') {
$('#messages').addClass('alert alert-success').text(response.message);
} else {
$('#messages').addClass('alert alert-danger').text(response.message);
}
}
});
e.preventDefault();
});
});
</script>
The login.php file is very simple and returns an json $output response
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if($username == "Test"){
$success = true;
}
if($success == true) {
$output = json_encode(array('type'=>'success', 'message' => $username));
} else {
$output = json_encode(array('type'=>'error', 'message' => $username));
}
die($output);
?>
The $output in every case returns null. I checked with firebug, and everything is OK , no errors, POST perfect still I cannot get the variables in php to work. Any ideas ??? Is something wrong with my approach or do I need to deserialize the data in the php file , somehow...???

Don't use die.
Use echo or print.
Also set contentType to true.

Related

Ajax Login Response Error

i'm traying to login with ajax and php, in that situation i'm logging succesfuly actually. But i'm trying to make an alert and refresh the page when logged in.
When i attempt to login, its gives me error and no refreshing. But if i refresh the page, i see i have session in php. I don't understand why.
Here is my code;
<script>
$(document).ready(function(){
$('#login_btn').click(function(){
var email = $('#email').val();
var password = $('#password').val();
if(email == '' || password == ''){
$("#login_error").html("*** Please enter your email / password");
}else{
$('#login_error').html("<strong class='text-success'>Validating...</strong>");
$.ajax({
url: "login.php",
method: "post",
data:{email:email, password:password},
success: function(data){
if (data === 'yes') {
window.location.reload();
}else{
$('#login_error').html("<strong class='text-danger'>ERROR...</strong>");
}
}
});
}
});
});
</script>
login php:
<?php
session_start();
include ('../config/setup.php'); #database connection
if(isset($_POST['email'])){
$q = "SELECT * FROM users WHERE email = '$_POST[email]' AND password = '$_POST[password]'";
$r = mysqli_query($dbc, $q);
if(mysqli_num_rows($r) > 0){
$_SESSION['email'] = $_POST['email'];
echo "yes";
}else{
echo "no";
}
}
?>
Html: (Using login form inside a modal)
<div class="modal-body">
<div class="form-horizontal">
<div class="form-group">
<label for="email" class="col-sm-4 control-label">Email</label>
<div class="col-sm-8">
<input type="email" class="form-control" name="email" id="email" placeholder="Account Email">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-4 control-label">Password</label>
<div class="col-sm-8">
<input type="password" class="form-control" name="password" id="password" placeholder="Account Password" >
</div>
</div>
<div class="form-group">
<div class="col-sm-1"></div>
<div align="center" class="col-sm-10">
<button name="login_btn" id="login_btn" class="btn btn-success btn-block text-center"><span id="loader_before" class="glyphicon glyphicon-log-in" aria-hidden="true"></span><i id="loader" class="fa fa-spinner fa-spin fa-x fa-fw"></i> Log in to Account</button>
</div>
<div class="col-sm-1"></div>
</div>
</div>
<div align="center" class="container-fluid">
<h6><strong class="text-danger">Forgot your password? Click here..</strong></h6>
</div>
<h5><div id="login_error" class="text-warning"></div></h5>
</div>
You just need to update your if block in response as below
`
if (data === 'yes') {
alert("You message here!");
window.location.reload();
}else{
$('#login_error').html("<strong class='text-danger'>ERROR...</strong>");
}
`
When you call echo on php, it will write the value, but not return it. That's the problem.
You are not returning "yes" or "no" from login.php, you're just doing echo, which will only write the value but not return it to the caller.
The ajax call is waiting for a response to process it with the 'success' callback. Since login.php is not returning anything, it will always fall into the else clause.
The solution is to change this on login.php
if(mysqli_num_rows($r) > 0){
$_SESSION['email'] = $_POST['email'];
return "yes";
}else{
return "no";
}

How to Update/Edit data in database with AngularJS

Working on a web app , I just added the below update code and it's not working .
The summary of all the below code is :
Click a Button called update
It brings out the FORM which should contain the values of the clicked/current product.
Now when I hit save in this form it should update the database but it is not.
I am using $_GET in PHP file (update.php) to get the current Product ID.And then getting all data of that product via that ID.
PS: There is no error in console.
UPDATE CODE:
<?php
include "includes/connection.php";
switch($_GET['action']) {
case 'update_entry' :
$data = json_decode(file_get_contents("php://input"));
$index = $data->id;
$productname = $data->pname;
$company = $data->company;
$price = $data->price;
$quantity = $data->quantity;
if(isset($productname) && !empty($productname) && isset($company) && !empty($company) && isset($price) && !empty($price) && isset($quantity) && !empty($quantity)){
$query = "UPDATE `product` SET `id`='$index',`name`='$productname',`company`='$company',`price`='$price',`quantity`='$quantity' WHERE id= $index";
if(mysqli_query($con, $query)) {
return true;
} else {
echo "Error: " . $sql . "<br />" . mysqli_error($con);
}
break;
}
}
?>
Controller :
myApp.controller("updateCtrl",['$scope','$http','$routeParams','$location',function($scope,$http,$routeParams,$location){
$scope.update = function(){
var currentId = $routeParams.id;
$http.post("update.php?action=update_entry",{'id':currentId})
.then(function(data){
$location.path('/viewproduct');
});
}
}]);
HTML:
<form style="padding:10px" ng-controller="updateCtrl">
<div class="form-group">
<label for="ProductName">Product Name</label>
<input type="text" class="form-control" placeholder="{{product.name}}" ng-model="productname" required>
</div>
<div class="form-group">
<label for="company">Company </label>
<input type="text" class="form-control" placeholder="{{product.company}}" ng-model="company" required>
</div>
<div class="form-group">
<label for="company">Price </label>
<input type="text" class="form-control" placeholder="{{product.price}}" ng-model="price" required>
</div>
<div class="form-group">
<label for="company">Quantity </label>
<input type="text" class="form-control" placeholder="{{product.quantity}}" ng-model="quantity" required>
</div>
<button type="submit" class="btn btn-default" ng-click="update()">Save updated data</button>
Cancel
<h1 ng-if="successMessage == 0">Great Data is Updated!</h1>
</form>
Update Button:
<td ng-controller="updateCtrl"><a class="btn btn-primary" href="#/updateproduct/action={{product.id}}" >Update</a></td>
Do like below
your view part
<form style="padding:10px" ng-controller="updateCtrl">
<div class="form-group">
<label for="ProductName">Product Name</label>
<input type="text" class="form-control" placeholder="{{product.name}}" ng-model="productname" required>
</div>
<div class="form-group">
<label for="company">Company </label>
<input type="text" class="form-control" placeholder="{{product.company}}" ng-model="company" required>
</div>
<div class="form-group">
<label for="company">Price </label>
<input type="text" class="form-control" placeholder="{{product.price}}" ng-model="price" required>
</div>
<div class="form-group">
<label for="company">Quantity </label>
<input type="text" class="form-control" placeholder="{{product.quantity}}" ng-model="quantity" required>
</div>
<button type="submit" class="btn btn-default" ng-click="update()">Save updated data</button>
Cancel
<h1 ng-if="successMessage == 0">Great Data is Updated!</h1>
</form>
<td><a class="btn btn-primary" ng-click="addProductData();" >Update</a></td>
Inside your controller do like below
$scope.addProductData=function(){
var updatedata=$.param({'action':'update','productname':$scope.productname,'company':$scope.company,'price':$scope.price,'quantity':$scope.quantity,'id':currentId});
$http({
method:'POST',
url:'update.php',
data:updatedata,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
alert(response.data['msg']);
},function errorCallback(response) {
alert(response.data['msg']);
});
}
your update.php file should like below.
<?php
include "includes/connection.php";
$result=array();
if(isset($_REQUEST["action"]) && $_REQUEST["action"] !=""){
if($_REQUEST["action"]=="update"){
$productname = $_POST['productname'];
$company = $_POST['company'];
$price = $_POST['price'];
$quantity = $_POST['quantity'];
$id=$_POST['id'];
$query = "UPDATE `product` SET `name`='$productname',`company`='$company',`price`='$price',`quantity`='$quantity' WHERE id= $id";
if(mysqli_query($con, $query)) {
$result['msg']="updated successfully";
}else{
header("HTTP/1.0 401 Unauthorized");
$result['msg']="unable to updated";
}
echo json_encode($result);
}
}
?>
i think you may basic idea.now you can implement in your way.
Try to use ng-model="{{product.name}}}" and not the placeholder in HTML.
And in your controller pass that model:
$http.post("update.php?action=update_entry",$scope.product)
Then you should get some data in your PHP.
Have you checked your php alone to make sure that you can fetch and update data using the php without angular? I would use post as it is more friendly for retrieving and updating data.
I would also b separate your call to the php endpoint into a service (factory). I would also just pass the entire object back through to ensure that you aren't missing something unless you have a concern about bandwidth.
I would unit test php first. Then separate logic in angular. Then b step through in debug to see what's being passed from the view.
I think you should check this: https://github.com/eliarms/CustomerManagerApp
This is a simple customer management app using Angularjs and PHP. The goal of the application is to highlight a lot of the different features offered by AngularJS and demonstrate how they can be used together.

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"])

AJAX instant check with php and javascript

I am developing a little webiste where I need to handle User registration. As usual, if a user requests a username that is already being used, the system should not allow to proceed with the registration.
I want to verify that during the register as most modern websites do. How do I do that using AJAX?
Register form:
<div class="container">
<form id="register_form" action="actions/register_action.php" method="post">
<div class="form-group">
<label for="name_area">Name</label>
<input type="text" name="name" class="form-control" placeholder="Name">
</div>
<div class="form-group">
<label for="username_area">Username</label>
<input type="text" name="username" class="form-control" id="username_id" placeholder="Username">
</div>
<div class="form-group">
<label for="email_area">Email</label>
<input type="email" name="email" class="form-control" placeholder="Email">
</div>
<div class="form-group">
<label for="pass_area">Password</label>
<input type="password" name="pass" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<label for="conf_pass_area">Confirm password</label>
<input type="password" name="conf_pass_area" class="form-control" placeholder="Confirm password">
</div>
<br>
<div class="form-group">
<input type="submit" class="btn btn-primary" id="button_area" placeholder="Submit">
<!--action to:register_action!-->
</div>
</div>
</form>
</div>
users.php (where I do my php function regarding users):
<?php
//checks if username inserted is already in use
function check_username($username_pretended) {
global $conn;
$stmt = $conn->prepare('SELECT * FROM CommonUsers WHERE username=?');
$stmt->execute(array($username_pretended));
$res = $stmt->fetch();
if($res['username'] == "") {
return false;
}
else return true;
}
//inserts an user in the database
function insertUser($name, $username, $email, $password) {
global $conn;
$stmt = $conn->prepare('INSERT INTO CommonUsers(name, username, email, password) VALUES (?, ?, ?, ?)');
$stmt->execute(array($name, $username, $email, $password));
}
?>
From top of my head:
$("#username_id").on("change", function()
{
$.ajax(
{
method: "get", // or maybe post?
url: "yoururlhere",
data:
{
username: $(this).val()
},
success: function(data)
{
if (data == "0")
{
// Hide warning
}
else
{
// Warn user that username is already taken
}
}
});
});
This is the most simple way of doing this. Its sending the username to a server url for checking. Of course you will need an element to show the warning(which I could not find in your DOM).
You can check the ajax() method docs for detailed options.
In your PHP file:
$username = $_GET["username"];
if (check_username($username))
{
return "1";
}
else
{
return "0";
}

Form with ajax: JS not executing

I've got one big problem on only 1 page of a web site: Javascript doesn't want to be executed.
I tried to copy and paste from another web site i've done where it works perfectly... but not here. Maybe you can help me to figure out why it doesn't work...
I tried many ways, no ajax seems to work here.
Here is one of them, when i try to send a mail, i got no alert but {"reponse":"Mail sent corretly!"} instead, and the mail is corretly sent.
The submit button works! The page is refreshing, so i think the js is not executed. (i'd like to have the information without refreshing the page, like a normal ajax request).
I've tried to put the script (and the link to librairies) in the head, nothing changed.
Here is my code:
<--! Some HTML -->
<form class="form-horizontal myForm" method="post" action="contact.php">
<div class="form-group col-md-6">
<input type="text" class="form-control" name="prenom" id="prenom" placeholder="First Name" pattern="[a-zA-ZÀ-ÿ._-\s]{1,30}" required>
</div>
<div class="form-group col-md-6" style="margin-left:14px">
<input type="text" class="form-control" name="nom" id="nom" placeholder="Name" pattern="[a-zA-ZÀ-ÿ._-\s]{1,30}" required>
</div>
<div class="form-group col-md-6">
<input type="email" class="form-control" name="email" id="email" placeholder="Mail" required >
</div>
<div class="form-group col-md-6" style="margin-left:14px">
<input type="text" class="form-control" name="objet" id="objet" placeholder="Object" pattern="[a-zA-ZÀ-ÿ._-\s]{1,30}" required >
</div>
<div class="form-group col-md-12">
<input type="text" class="form-control" name="message" id="message" placeholder="Your message" required>
</div>
<div class="form-group">
<label for="captcha" class="col-xs-12 col-sm-2 control-label">Captcha</label>
<div class="col-xs-6 col-sm-2">
<input type="text" class="form-control" id="captcha" name="captcha" required>
</div>
<div class="col-xs-2 col-sm-1">
<img src="form.php">
</div>
</div>
<div class="form-group col-md-12">
<button type="submit" class="btn btn-default">Submit</button>
</div>
<div class="the-return"> </div>
</form>
<--! Some HTML -->
<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/main.js"></script> <!-- Gem jQuery -->
<script>
$(document).ready(function() {
// On submit
$('.myForm').on('submit', function(e) {
e.preventDefault(); // Prevent default submit
var $this = $(this);
// Getting values
var name = $('#nom').val();
var fname = $('#prenom').val();
var objet = $('#objet').val();
var mail = $('#email').val();
var msg = $('#msg').val();
// Looking for errors
if(name === '' || fname === '' || objet === '' || mail === '' || msg === '') {
alert('Les champs doivent êtres remplis');
} else {
// Sending Ajax query
$.ajax({
url: $this.attr('action'), // form's action
type: $this.attr('method'), // form's method
data: $this.serialize(), // Serializing data
success: function(html) { // php's file response
alert(html); // Print the result
}
});
}
});
});
And my php file:
session_start();
if(isset($_GET['err']))
{
$reponse = 'Mail not sent corretly!';
echo json_encode(['reponse' => $reponse]);
echo 'An error occurred, please try again
<form .... /form>'; //Same form
}
if(isset($_POST["captcha"]) && $_POST["captcha"]!="" && $_SESSION["captcha"]==$_POST["captcha"])
{
if(isset($_POST["nom"]))
{
if(preg_match("/^[a-zA-Z][a-zA-Z]*[a-zA-Z]$/",$_POST['nom']))
{
if(isset($_POST["prenom"]))
{
if (preg_match("/^[a-zA-Z][a-zA-Z]*[a-zA-Z]$/",$_POST['prenom']))
{
if(isset($_POST["objet"]))
{
if (preg_match("/^[a-zA-Z][a-zA-Z]*[a-zA-Z]$/",$_POST['objet']))
{
if(isset($_POST["email"]))
{
if (preg_match("/^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/",$_POST['email']))
{
$passage_ligne = "\r\n";
$emailAdmin = 'benjamin#parisbeaute.fr';
// Subject
$subject = $_POST['objet'];
// Headers
$headers = 'FROM: "'.$_POST['nom'].' '.$_POST['prenom'].'" <'.$_POST['email'].'>'.$passage_ligne;
$headers .= 'MIME-Version: 1.0'.$passage_ligne;
$headers .= 'Content-type: text/html; charset=UTF-8'.$passage_ligne;
$message = $_POST['message'];
// Formulaire
// Fonction mail()
mail($emailAdmin, $subject, $message, $headers);
echo '<div>Thanks a lot !</div>';
$reponse = 'Mail sent corretly!';
echo json_encode(['reponse' => $reponse]);
}}}}}}}}}
?>
Thanks in advance, sorry for my poor English, it's not my native language as you can see in my code.
Not sure why it did't work, but If you want sending the data using the $.ajax request, then stick to click event. Try change the code into this :
$(document).ready(function() {
// On button click
$('#my_button').on('click', function(e) {
var $this = $('.myForm');
// Getting values
var name = $('#nom').val();
var fname = $('#prenom').val();
var objet = $('#objet').val();
var mail = $('#email').val();
var msg = $('#msg').val();
// Looking for errors
if(name === '' || fname === '' || objet === '' || mail === '' || msg === '') {
alert('Les champs doivent êtres remplis');
} else {
// Sending Ajax query
$.ajax({
url: $this.attr('action'), // form's action
type: $this.attr('method'), // form's method
data: $this.serialize(), // Serializing data
success: function(html) { // php's file response
alert(html); // Print the result
}
});
}
});
});
And change button type into :
<button type="button" class="btn btn-default" id="my_button">Submit</button>

Categories

Resources