AJAX not sending post data - javascript

I am currently attempting to send form data via ajax to a php function but it does not appear to be sending it.
This is the HTML Form:
<form onSubmit="return registration();" id="registration_form">
<input type="email" id="email_address" name="email_address" class="inputTextFooter">
<input src="images/go.png" alt="Go" type="submit">
</form>
The AJAX:
function registration(){
if(!$('#email_address').val()){
alert("Empty");
}
else {
$.ajax( {
type: "POST",
url: "includes/registration_check.php",
data: $('#registration_form').serialize(),
success: function( response ) {
alert( response );
}
});
}
return false;
};
Finally the PHP:
$user_id = NULL;
$user_email = isset($_POST['email_address']) ? $_POST['email_address'] : '';
$distinct_query = "SELECT distinct user_email FROM user_emails";
$result=mysql_query($distinct_query, $connection);
$rows = mysql_num_rows($result) - 1;
$distinct_result_array = array();
while($fetched_array = mysql_fetch_assoc($result))
{
$distinct_result_array[] = $fetched_array;
}
for ($loop = 0; $loop <= $rows; $loop++) {
if (in_array($user_email, $distinct_result_array[$loop])) {
echo "Email taken.";
break;
}
else{
}
}
$query = "INSERT INTO user_emails (user_id, user_email) VALUES ('".$user_id."', '".$user_email."')";
mysql_query($query, $connection);
echo "You have successfully registered and will be checked by administration.";
When I send the form it adds to the database but the email field is blank.

Replace
$user_email = isset($_POST['email_address']) ? $_POST['email_address'] : '';
With
if(empty($_POST['email_address']))
{
echo "error";
exit;
}
else
{
$user_email = $_POST['email_address'];
}
And I advice you Use mysqli instead of mysql, also validate user input before inserting into database.

your function should have event.preventDefault() to restrict default form submit action
then only your ajax request get triggerred.
function registration(){
event.preventDefault();
if(!$('#email_address').val()){
alert("Empty");
}
else {
$.ajax( {
type: "POST",
url: "includes/registration_check.php",
data: $('#registration_form').serialize(),
success: function( response ) {
alert( response );
}
});
}
return false;
};

I think you might need to use PHP's parse_str() function to get serialized data
http://php.net/manual/en/function.parse-str.php

Related

[Ajax][PHP] - login form, response is always empty

I have a problem with my login form. Every time when i write (correct or incorrect) login and password in my login form, my JS script return error and when i try to print "response" it is empty.
Can anyone help?
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
var name = $("#name").val().trim();
var paw = $("#paw").val().trim();
$.ajax({
url: 'check.php',
type: 'POST',
data: {name:name, paw:paw},
success: function(response){
if(response == 1){
window.location= "home.php";
}
else{
alert("error");
}
}
});
});
});
<?php
session_start();
require_once 'dbconfig.php';
error_reporting(E_ALL ^ E_NOTICE);
if(isset($_POST['submit']))
{
$name = trim($_POST['name']);
$paw1 = trim($_POST['paw']);
$paw = md5($paw1);
try {
$stmt = $pdo->prepare("SELECT * FROM user WHERE login=:nazwa and haslo=:has");
$stmt->execute(array(':nazwa'=>$name, ':has'=>$paw));
$count = $stmt->rowCount();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['haslo']==$paw){
echo 1;
$_SESSION['user_session'] = $row['login'];
}
else {
echo 0;
}
} catch (\Exception $e) {
echo $e->getMessage();
}
}
?>
Remove the if(isset($_POST['submit'])) line. The reason is that the button key value is not sent via the AJAX call. To verify, do a print_r($_POST);
instead verify that name and password variables are not empty()
if (!empty($_POST['name']) && !empty($_POST['paw'])) {
}
Also do not use md5() for your passwords. use php's password_hash() to hash and password_verify() to verify that the posted password via the form matches the hash stored in the database for that user.

How to handle success with 'if - else' in ajax call and response?

I have a written code in AJAX which checks whether password exists or not. if yes it sends "OK" as output else "Incorrect " as output . i want to success handler in AJAX call's response to do task based on that. How can handle it? I want if password is correct , to remove Attribute of disabled in a form element else i want i want that form element's attribute remained back as disabled.
AJAX code goe like this :
$("#currentpassword").keyup(function() {
var name = $(this).val();
if (name.length > 5) {
$("#result").html('checking...');
$.ajax({
type: 'POST',
url: 'checkPassword.php',
data: $(this).serialize(),
success: function(data) {
if (data == "1") {
$("#result").html(data);
$("#newpassword").removeAttr("disabled");
$("#confirmpassword").removeAttr("disabled");
} else {
$("#result").html(data);
}
}
});
return false;
} else {
$("#result").html('');
}
});
checkpassword php file looks like below :
<?php
include_once 'includes.php';
// Submitted form data
$currentpassword=$_POST['currentpassword'];
$result = mysqli_query($db,"SELECT * FROM `users` WHERE `password`='$currentpassword' AND `username`='$session_username'");
$row = mysqli_num_rows($result);
if($row!=1) {
echo "<span style='color:red;'>Incorrect Password !!!</span>";;
}
else {
echo "OK";
}
// Output status
?>
The Good way is The PHP file should look like this
<?PHP
header('Content-type:application/json;charset=utf-8');
include_once 'includes.php';
$currentpassword=$_POST['currentpassword'];
$result = mysqli_query($db,"SELECT * FROM `users` WHERE `password`='$currentpassword' AND `username`='$session_username'");
$count = mysqli_num_rows($result);
if($count! = 1) {
header('HTTP/1.1 401 Unauthorized', true, 401);
echo json_encode('In Correct Password');
} else {
header('HTTP/1.1 404 Not Found', true, 404);
echo json_encode('Not Found');
}
And your Jquery will be
$.ajax({
type: 'POST',
url: 'checkPassword.php',
data: $(this).serialize(),
success: function(data) {
// Only 200 comes here
}, error(jqXHR, exception) {
// All errors except 200 comes here.
}
});
Hope this helps

php/jQuery get primary key for selected value

I am trying to get key(primary key) for selected value in my form, so I can add key into joining table. I change my form to autocomplete from drop down list. but do not how to do map with jquery.
This is my php for autocomplete
<?php
if (isset($_POST['type']) && $_POST['type'] == 'faculty_id') {
$type = $_POST['type'];
$name = $_POST['name_startsWith'];
$nameID = $_POST['nameID'];
$query = "SELECT FirstName, LastName, FacultyId FROM Test.Faculty where UPPER(FirstName) LIKE '" . strtoupper($name) . "%'";
$result = mysqli_query($con, $query);
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$name = $row['FirstName'] . ' ' . $row['LastName'];
$nameID = $row['FacultyId'];
array_push($data, $name);
}
mysqli_close($con);
echo json_encode($data);
exit;
}
?>
this is form and jQuery page
<form action="Form.php" method="post">
<input type='text' id="faculty_id" placeholder="Instructor" name="faculty_id" value='' />
<input type="submit" value="submit" name="submit" />
</form>
<script type="text/javascript">
$('#faculty_id').autocomplete({
source: function (request, response) {
$.ajax({
url: 'Form.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
nameID: request.term,
type: 'faculty_id'
},
success: function (data) {
response($.map(data, function (item) {
console.log(item);
//var code = item.split("|");
return {
label: item,
value: item,
data: item
}
}));
}
});
},
autoFocus: true,
minLength: 1,
});
</script>
and php insert query
<?php
if (isset($_POST)) {
$faculty_id = $_POST['faculty_id'];
try {
$stat = $db->prepare("Insert into ATCTest.Schedule
(Faculty )
VALUE (':faculty_id' )");
$stat->bindParam(":faculty_id", $faculty_id);
if ($stat->execute()) {
echo "<h5>Faculty-js: " . $faculty_id . "</h5>";
} else {
echo "Problem!!!";
}
} catch (PDOException $e) {
echo $e->getMessage();
}
}
Stay consistent. Choose either PDO or MySQLi. Not both. Your autocomplete script uses MySQLi, but then in your insert script, you use PDO. Pick one and stick with it.
I'll use PDO as I find it much easier to use than MySQLi.
Use the appropriate request methods. If you are getting something, use GET not POST. If you are adding or updating, use POST.
Let's rewrite your autocomplete script to use PDO:
if (isset($_GET['type']) && $_GET['type'] == 'faculty_id') {
// this will hold your response that gets sent back
$data = null;
$name = trim($_GET['name']);
try {
// because you are passed untrusted data, use prepared statement
$sth = $db->prepare("
SELECT FirstName, LastName, FacultyId
FROM Test.Faculty
WHERE UPPER(FirstName) LIKE UPPER(?)
");
$sth->execute(array($name . '%'));
// set the results (array of objects) as your JSON response
$data['faculties'] = $sth->fetchAll(PDO::FETCH_OBJ);
} catch(PDOException $e){
echo $e->getMessage();
}
// send the results i.e. response
header('Content-Type: application/json');
echo json_encode($data);
exit;
}
I've never used the autocomplete plugin before but I'll take a crack at it based on other answers I've seen.
$('#faculty_id').autocomplete({
source: function (request, response) {
// short syntax for .ajax() using GET method that expects a JSON response
$.getJSON('Form.php', { type: 'faculty_id', name: request.term }, function (data) {
// data.faculties (your AJAX script's response) should now be an array of objects
console.log(data.faculties);
response($.map(data.faculties, function (faculty) {
console.log(faculty);
return {
label: faculty.FirstName + ' ' + faculty.LastName,
value: faculty.FacultyId
}
}));
});
},
autoFocus: true,
minLength: 1,
});
Lastly, when you insert
// check if form was POSTed
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$faculty_id = $_POST['faculty_id'];
try {
// VALUES not VALUE
// don't wrap your placeholders with quotes in your prepared statement
// simplified
$sth = $db->prepare("INSERT INTO ATCTest.Schedule(Faculty) VALUES(?)");
// simplified way to bind parameters
$sth->execute(array($faculty_id));
// use rowCount() not execute() to determine if the operation was successful or not
if ($sth->rowCount()){
echo "<h5>Faculty-js: $faculty_id</h5>";
} else {
echo "Problem!!!";
}
} catch (PDOException $e) {
echo $e->getMessage();
}
}

Convert ajax response array object to javascript array?

I am using ajax to submit a login form in Yii. Here is my ajax function:
$("#login-form").submit(function() {
var email = $("#email").val();
var password = $("#password").val();
$.ajax({
url: "<?php echo Yii::app()->request->baseUrl; ?>/site/validatelogin",
type: "post",
data: "email=" + email + "&password=" + password,
success: function(response) {
if (response === "1") {
window.location.href = "<?php echo Yii::app()->getBaseUrl(true); ?>/dashboard";
}
else
{
//Dispaly response errors above login form
}
},
error: function() {
alert("Could not perform the requested operation due to some error.");
return false;
}
});
});
My PHP controller function is validatelogin as follows:
$email = $_POST['email'];
$password = $_POST['password'];
$model = new LoginForm();
$model->email = $email;
$model->password = $password;
if ($model->validate() && $model->login()) {
echo "1";
} else {
print_r($model->getErrors());
}
If the user enters correct credentials I send 1 as response to view and user is redirected to dashboard.
But if user enters incorrect credentials then different errors are received in ajax response depending upon the type of error.
I want to display those errors above login form in else part of success function through a loop.
But when I run the loop over response then that array has very large length i.e for example if the error in response was "Incorrect password" then the response array has length of 18(the number of characters) in the error message. In short the response array is like:
array('I','n','c','o','r','r'....)
rather than
array([0]=>"Incorrect password")
How do I convert response array in the latter format and iterate over each index to display error message to the user above the login form?
Encode it to JSON.
In your php:
echo json_encode($model->getErrors());
In your js (in the else):
var errors = $.parseJSON(response);
Edit:
In your case it would be better to always return JSON.
Your JS could be changed to:
var jqxhr = $.post("<?php echo Yii::app()->request->baseUrl; ?>/site/validatelogin", {
email: email,
password: password
}, 'json');
jqxhr.done(function(response) {
if (response.valid) {
window.location.href = "<?php echo Yii::app()->getBaseUrl(true); ?>/dashboard";
} else {
if (response.errors) {
...
}
}
});
jqxhr.error(function(response) {
alert("Could not perform the requested operation due to some error.");
});
Your PHP:
$response = array('valid' => false);
if ($model->validate() && $model->login()) {
$response['valid'] = true;
} else {
$response['errors'] = $model->getErrors();
}
header('Content-type: application/json');
echo json_encode($response);
In addition to #sroes's answer, use Yii library for JSON
echo CJSON::encode($response);
instead of
echo json_encode($response);
why ?
Why use CJSON encode when we have json_encode

The data entered in the fields doesn't go to database, but I get a success message

I have this form in a modal with only two fields. I used JavaScript function for PHP script. When I click on Submit, I get a Success Message, but the my database is blank.
<?php
require "database_connection.php";
$error = array();
if (isset($_POST['aid'], $_POST['eventList']))
{
if (empty($_POST['aid']))
$error[] = 'Please Enter a name';
else
{
$query = "INSERT INTO event (Memberid, events) VALUES (?, ?)";
if ($stmt = mysqli_prepare($dbc, $query))
{
mysqli_stmt_bind_param($stmt, 'is', $_POST['aid'], $_POST['eventList']);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo 'Success';
}
}
}
?>
JavaScript Submit code:
<script type="text/javascript" >
$(function() {
$(".submit").click(function(e) {
var aid = $("#aid").val();
var eventList = $("#eventList").val();
var dataString = 'aid='+ aid + '&eventList=' + eventList;
var data=$('#regPost').serialize()
if(aid=='' || eventList=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
console.log("ERROR");
}
else
{
console.log(dataString);
$.ajax({
type: "POST",
url: "ureg.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
HTML Code for forms:
<form method="post" id="regPost" class="registration_form">
<center>Event Name: <select style="width:200px;" name="eventList" tabindex="5"><br>
<option value="select">Select Event</option>
<optgroup label="X Y Z">
<option value="B Bs">Bas</option>
<option value="Ea">Eas</option>
<option value="So">So</option>
</optgroup>
</select> <br>
ID:<input type="text" name="aid"><br/>
<input type="submit" value="SUBMIT" class="submit"></center>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Registration Successfully</span>
</form>
you have written the following code
var data=$('#regPost').serialize();
pass this data in the ajax request instead of datastring as
$.ajax({
type: "POST",
url: "ureg.php",
data: data,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
Your code does not take into account if the query was successful. First, your PHP returns "success" after it attempts to query the database regardless of if it succeeds. You should look into mysqli_errno.
Secondly, your AJAX call assumes a success no matter what the response is. You could return "fail" or even an empty string "" and as long as it comes back with a 200 status header, the success function will fire. Consider adding a failure function on your AJAX call and returning a 400 status code from PHP in the event of failure.
http_response_code(400);
-- Edit --
This is not something I actually tested, but should get you going in the right direction.
Server-side:
if (isset($_POST['aid'], $_POST['eventList']))
{
if (empty($_POST['aid']))
$error[] = 'Please Enter a name';
else
{
$query = "INSERT INTO event (Memberid, events) VALUES (?, ?)";
if ($stmt = mysqli_prepare($dbc, $query))
{
mysqli_stmt_bind_param($stmt, 'is', $_POST['aid'], $_POST['eventList']);
mysqli_stmt_execute($stmt);
$error = mysqli_stmt_error($stmt);
mysqli_stmt_close($stmt);
if ( $error ){
http_response_code(400);
echo json_encode(array('error' => $error));
}else{
http_response_code(200);
}
}
}
}
?>
JavaScript:
<script type="text/javascript" >
$(function() {
$(".submit").click(function(e) {
var aid = $("#aid").val();
var eventList = $("#eventList").val();
var dataString = 'aid='+ aid + '&eventList=' + eventList;
var data=$('#regPost').serialize()
if(aid=='' || eventList=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
console.log("ERROR");
}
else
{
console.log(dataString);
$.ajax({
type: "POST",
url: "ureg.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
},
error: function(){
$('.success').fadeIn(200).hide();
$('.error').fadeOut(200).show();
}
});
}
return false;
});
});
</script>

Categories