if(isset($_POST['btn-save'])) doesn't return true - javascript

Yep, this old chesnut I'm afraid. I've read through a lot of the previous answers to this question but I cannot get into this if statement even though 'btn-save' is definitely set as the name attribute on my submit button.
I'm using the code from this tutorial to post form data to my database: http://www.phpzag.com/ajax-registration-script-with-php-mysql-and-jquery/
My site structure is like this:
- root
- public_html
- js
app.js
register.php
db_connect.php
form_page.php
My register.php file looks like this and I've added an echo inside the if statement:
<?php
include_once("db_connect.php");
if(isset($_POST['btn-save'])) {
echo "in if";
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email_id = $_POST['email_id'];
$address_1 = $_POST['address_1'];
$address_2 = $_POST['address_2'];
$address_3 = $_POST['address_3'];
$city_town = $_POST['city_town'];
$county = $_POST['county'];
$post_code = $_POST['post_code'];
$entrant_type = $_POST['entrant_type'];
$chosen_store = $_POST['chosen_store'];
$chosen_charity = $_POST['chosen_charity'];
$agree_terms = $_POST['agree_terms'];
$sql = "SELECT user_email FROM tbl_big_challenge_registrations WHERE user_email='$email_id'";
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
$row = mysqli_fetch_assoc($resultset);
if(!$row['user_email']){
$sql = "INSERT INTO tbl_big_challenge_registrations('uid', 'first_name', 'last_name', 'user_email', 'address_1', 'address_2', 'address_3', 'town_city', 'county', 'postcode', 'entrant_type', 'crew_store', 'charity', 'agree_terms') VALUES (NULL, '$first_name', '$last_name', '$email_id', '$address_1', '$address_2', '$address_3', '$city_town', '$county', '$post_code', '$entrant_type', '$chosen_store', '$chosen_charity', 'agree_terms', NULL)";
mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn)."qqq".$sql);
echo "registered";
} else {
echo "1";
}
}
?>
My db_connect.php file looks like this (with dummy values for purpose of this post):
<?php
/* Database connection start */
$servername = "servername.com";
$username = "username";
$password = "password";
$dbname = "my_database";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
My form_page.php form looks like this:
<form id="2017-challenge-form" method="post" data-abide>
<!-- form fields are here -->
<input id="btn-submit" type="submit" name="btn-save" value="submit">
</form>
And finally my app.js looks like this:
$('document').ready(function() {
/* handle form submit */
function submitForm() {
var data = $("#2017-challenge-form").serialize();
$.ajax({
type : 'POST',
url : 'register.php',
data : data,
beforeSend: function() {
$("#error").fadeOut();
$("#btn-submit").val('Submitting...');
},
success : function(response) {
if(response==1){
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> Sorry email already taken !</div>');
$("#btn-submit").val('Submit');
});
} else if(response=="registered"){
$("#btn-submit").html('<img src="ajax-loader.gif" /> Signing Up ...');
setTimeout('$(".form-signin").fadeOut(500, function(){ $(".register_container").load("welcome.php"); }); ',3000);
} else {
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> '+data+' !</div>');
$("#btn-submit").val('Submit');
});
}
}
});
return false;
}
$("#2017-challenge-form").submit(function(event){
// cancels the form submission
event.preventDefault();
// jumps into ajax submit function
submitForm();
});
});
I have a breakpoint set just inside the ajax success and on submission of the form I would expect the response to have a value of 'registered' (just like the Demo from the PHPZag site: http://phpzag.com/demo/ajax-registration-script-with-php-mysql-and-jquery/
But I get an empty string:
Can anybody see what I'm doing wrong or am missing?

I changed the input to a button as per the demo site and this worked. As per the comment by #frz3993 the btn-save wasn't getting added to the data so the if(isset($_POST['btn-save'])) was never true as it wasn't finding it.

Related

Ajax call for the Bootstrap Modal not working

I'm trying to make a simple Ajax call for a Bootstrap login modal. The main HTML code of the login Modal looks like this:
<form method="post" id="loginForm">
<div id="loginMessage"></div>
<div class="modal-footer">
<button type="button" class="btn btn-success mr-auto" data-target="#signupModal" data-toggle="modal" data-dismiss="modal">Register</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<input class="btn" name="login" type="submit" id="inputButton" value="Login">
</div>
</form>
In case the whole HTML code for the modal would help : https://jsfiddle.net/aslah/hykxLqd5/2/
The jQuery code looks like this:
$('#loginForm').submit(function(event){
//prevent default php processing
event.preventDefault();
//collect user inputs:
var datatopost = $(this).serializeArray();
//send the user data to login.php using AJAX
$.ajax({
url: "login.php",
type : "POST",
data : datatopost,
success : function(data){
if(data == 'success'){
window.location = "mainpage.php";
}else{
$('#loginMessage').html(data);
}
},
error : function(){
$('#loginMessage').html('<div class="alert alert-danger">There was an error with the AJAX call. Please, try again later!</div>');
}
});
});
This is my login.php code :
<?php
//starting the session
session_start();
//connecting to database
include('connection.php');
//check user inputs
// DEFINE ERROR MESSAGES //
$missingEmail = '<p><strong>Please enter your email address!</strong></p>';
$missingPassword = '<p><strong>Please enter a password!</strong></p>';
// $email = $_POST["loginEmail"]
// $password = $_POST["loginPassword"]
if(empty($_POST["loginEmail"])){
$error .= $missingEmail;
}else{
$email = filter_var($_POST["loginEmail"], FILTER_SANITIZE_EMAIL);
}
if(empty($_POST["loginPassword"])){
$error .= $missingPassword;
}else{
$password = filter_var($_POST["loginPassword"], FILTER_SANITIZE_STRING);
}
//If there are any ERRORS
if($error){
$resultMessage = '<div class="alert alert-danger">'. $error .'</div>' ;
echo $resultMessage ;
}else{
$email = mysqli_real_escape_string($link, $email);
$password = mysqli_real_escape_string($link, $password);
// $password = md5($password); no secure
$password = hash('sha256', $password);
//check if the user is registered by matching EMAIL & PASSWORD
$sql = "SELECT * FROM users WHERE email = '$email' AND password = '$password' AND activation='activated' ";
$result = mysqli_query($link, $sql);
//if any errors while running the query
if(!$result){
echo '<div class="alert alert-danger"> Error running the query!</div>';
exit;
}
//if login failed print ERROR
$count = mysqli_num_rows($result);
if($count !== 1){
echo '<div class="alert alert-danger">Wrong username or password</div>';
}else{
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['username'] = $row['username'];
$_SESSION['email'] = $row['email'];
//if remember me is not checked
if(empty($_POST['rememberme'])){
echo "success";
}else{
// if rememberme is checked
}
}
}
?>
On submit of the the Login button I want to redirect the user to the mainpage.php. I tried all the different fixes I found here but nothing worked. I can't figure out what I'm doing wrong. Any help is highly appreciated.
This is what I get when I submit the form
Aslah P Hussain
I have tested your code. The first thing that caught my attention is Notice about the undefined variable $error. Possibly you have defined it in include('connection.php'); but if not, this can cause problems with PHP output that you are expecting.
Additionally, if you are 100% sure that the console returns the message success - you can change your check in JavaScript to:
if(data.indexOf('success') >= 0){
window.location = "mainpage.php";
}else{
$('#loginMessage').html(data);
}
Possibly not the best solution to the problem, but at least will show you that redirect is working

How to add links to search results from Ajax?

I have a search bar which uses Ajax implementation to search my database and query the input data.view of results generated My question is how do I make the results show up as clickable link so that when clicked they go straight to the view which holds more information about them? I have added the code for database query and the script used for accessing the database based on what was entered by the user in the search box.
<script>
$(document).ready(function() {
$('#search-data').unbind().keyup(function(e) {
var value = $(this).val();
if (value.length>3) {
//alert(99933);
searchData(value);
}
else {
$('#search-result-container').hide();
}
}
);
}
);
function searchData(val){
$('#search-result-container').show();
$('#search-result-container').html('<div><img src="preloader.gif" width="50px;" height="50px"> <span style="font-size: 20px;">Searching...</span></div>');
$.post('controller.php',{
'search-data': val}
, function(data){
if(data != "")
$('#search-result-container').html(data);
else
$('#search-result-container').html("<div class='search-result'>No Result Found...</div>");
}
).fail(function(xhr, ajaxOptions, thrownError) {
//any errors?
alert("There was an error here!");
//alert with HTTP error
}
);
}
</script>
<form>
<div class="manage-accounts" id="users">
<div id="search-box-container" >
<label > Search For Any Event:
</label>
<br>
<br>
<input type="text" id="search-data" name="searchData" placeholder="Search By Event Title (word length should be greater than 3) ..." autocomplete="off" />
</div>
<div id="search-result-container" style="border:solid 1px #BDC7D8;display:none; ">
</div>
</div>
</form>
database query:
<?php
include("fetch.php");
class DOA{
public function dbConnect(){
$dbhost = DB_SERVER; // set the hostname
$dbname = DB_DATABASE ; // set the database name
$dbuser = DB_USERNAME ; // set the mysql username
$dbpass = DB_PASSWORD; // set the mysql password
try {
$dbConnection = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbConnection->exec("set names utf8");
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbConnection;
}
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
public function searchData($searchVal){
try {
$dbConnection = $this->dbConnect();
$stmt = $dbConnection->prepare("SELECT * FROM events WHERE title like :searchVal");
$val = "%$searchVal%";
$stmt->bindParam(':searchVal', $val , PDO::PARAM_STR);
$stmt->execute();
$Count = $stmt->rowCount();
//echo " Total Records Count : $Count .<br>" ;
$result ="" ;
if ($Count > 0){
while($data=$stmt->fetch(PDO::FETCH_ASSOC)) {
$result = $result .'<div class="search-result">'.$data['title'].'</div>';
}
return $result ;
}
}
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
}
?>
If all you want is making the search result clickable and browser loads the hyperlink clicked on, just echo the hyperlink from your database or JSON file depends on where they are into the html anchor element such as this:
<?php echo $row['page_title'] ?>
Note: I echoed the page link in the anchor href attribute, that should solve the problem.
You can simply add some code to make a hyperlink into the HTML your PHP is generating:
$result = $result .'<div class="search-result">'.$data['title'].'</div>';
I have made an assumption about the name of your ID field but you can see the pattern you need to use.

Ajax always returning null value

I'm new on PHP and now i'm learning about how to use AJAX, i just want to get the return value that passed from PHP(webservice.php) to JS. I dont know why it always return null value when im trying to alert it with the "alert(result)" on my JS Login function.
I'm sorry for my bad English, hope u guys understand what i mean
HTML :
<input class="button btnlogin" type="button" class="alt" id="btn_submit_data" value="Log In" onclick="login()" />
JS :
function login() {
var id = document.getElementById('login_email').value;
var pass = document.getElementById('login_pass').value;
$.get("http://localhost/project/dist/bin/webservice.php", {
ajx: "login",
email: id,
password: pass
}, function (result) {
if (result == true) {
window.location.href = "http://localhost/project/index.php";
} else {
alert(result);//This is where i want to get the value but it always returning the null value
}
});
}
PHP (connection.php) :
<?php
session_start();
function getConnection(){
$servername ="127.0.0.1";
$username = "root";
$password = "";
$database = "project";
$conn = new mysqli($servername, $username, $password,$database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
getconnection();
?>
PHP (webservice.php) :
<?php
include 'connection.php';
if($_GET['ajx'] == "login"){
$email = $_GET['email'];
$password = $_GET['password'];
Login($email,$password);
}
function Login($email,$password){
return $email;
}
?>
Because your PHP code does not return anything. What you get in your browser is defined by what PHP returns in output buffer.
As many said you should use:
$output = Login($email,$password);
echo json_encode($output);
You should also include:
header('Content-type:application/json;charset=utf-8');
See also this question.

PHP/JS: cannot get

All I want to do is print 'win!' if they log in with their details in the Database (working correctly) and 'loss' if for some reason their info was not found in the DB.
So my issue is that for some reason my line of code 'echo $email;' doesn't work. It seems be set to NULL.
At the moment it only ever prints 'loss' regardless what i enter, but, if I add a row in the database that has a blank email and password (email = "", password="") then the php script returns 'win!'.
PHP CODE:
<?php
// echo "php test";
//server info
$servername = "localhost";
$username = "root";
$dbpassword = "root";
$dbname = "personal_data";
//Establish server connection
$conn = new mysqli($servername, $username, $dbpassword, $dbname);
//Check connection for failure
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//Read in email & password
echo "reading in email & password...";
$email = mysqli_real_escape_string($conn, $_POST['email1']);
$password = mysqli_real_escape_string($conn, $_POST['password1']);
echo $email; //this prints blank
echo $password; //this also prints blank
$sql = "SELECT Name FROM personal_data WHERE Email='$email' AND Password='$password' LIMIT 1";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){
echo "win!!";
} else {
echo "loss";
}
mysqli_close($conn);
?>
JS CODE:
$(document).ready(function(){
// alert("js working");
$('#login_button').click(function(){
var email = $('#email').val(); //prints the correct value
var password = $('#password').val(); //prints the correct value
var dataString = 'email1=' + email
+ '&password1=' + password;
$.ajax({
type: "POST",
url: "http://localhost:8888/php/login.php",
data: dataString, //posts to PHP script
success: success()
});
});//eo login_button
function success(){
alert("success");
}
});//eof
Apart from the fact that that is completely, insanely useless and with no security whatsoever, you can just exchange $.ajax() for $.post() and do like this:
var loginEmail = $('#email').val();
var loginPassword = $('#password').val();
$.post('login.php',{email:loginEmail,password1:loginPassword},function(data) {
console.log(data);
})

Ajax database insert isnt working

I am trying to insert values from an input field into a database with ajax as part of a conversation system.I am using an input form as follows.
<input data-statusid="' .$statuscommentid. '" id="reply_'.$statusreplyid.'" class="inputReply" placeholder="Write a comment..."/>
with the following jquery I carry out a function when the enter key is pressed by the user.
$(document).ready(function(){
$('.inputReply').keyup(function (e) {
if (e.keyCode === 13) {
replyToStatus($(this).attr('data-statusid'), '1',$(this).attr("id"));
}
});
});
within this function is where I am having the problem ,I have no problems calling the function with jquery but I have done something wrong with the ajax and I don't know what?
$.ajax({ type: "POST", url: $(location).attr('href');, data: dataString, cache: false, success: function(){ $('#'+ta).val(""); } });
Additionally this is the php I am using to insert into the database
<?php //status reply input/insert
//action=status_reply&osid="+osid+"&user="+user+"&data="+data
if (isset($_POST['action']) && $_POST['action'] == "status_reply"){
// Make sure data is not empty
if(strlen(trim($_POST['data'])) < 1){
mysqli_close($db_conx);
echo "data_empty";
exit();
}
// Clean the posted variables
$osid = preg_replace('#[^0-9]#', '', $_POST['sid']);
$account_name = preg_replace('#[^a-z0-9]#i', '', $_POST['user']);
$data = htmlentities($_POST['data']);
$data = mysqli_real_escape_string($db_conx, $data);
// Make sure account name exists (the profile being posted on)
$sql = "SELECT COUNT(userid) FROM user WHERE userid='$userid' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
if($row[0] < 1){
mysqli_close($db_conx);
echo "$account_no_exist";
exit();
}
// Insert the status reply post into the database now
$sql = "INSERT INTO conversation(osid, userid, postuserid, type, pagetext, postdate)
VALUES('$osid','$userid','$postuserid','b','$pagetext',now())";
$query = mysqli_query($db_conx, $sql);
$id = mysqli_insert_id($db_conx);
// Insert notifications for everybody in the conversation except this author
$sql = "SELECT authorid FROM conversation WHERE osid='$osid' AND postuserid!='$log_username' GROUP BY postuserid";///change log_username
$query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$participant = $row["postuserid"];
$app = "Status Reply";
$note = $log_username.' commented here:<br />Click here to view the conversation';
mysqli_query($db_conx, "INSERT INTO notifications(username, initiator, app, note, date_time)
VALUES('$participant','$log_username','$app','$note',now())");
}
mysqli_close($db_conx);
echo "reply_ok|$id";
exit();
}
?>
Thanks in advance for any help it will be much appreciated
Why didn't you set the proper URL for Ajax calls instead of using location.href?
var ajax = ajaxObj("POST", location.href);
In additional, I guess ajaxObj is not defined or well coded. You are using, jQuery, why don't you try jQuery ajax?
http://api.jquery.com/jquery.ajax/
var ajax = ajaxObj("POST", location.href);
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if(datArray[0] == "reply_ok"){
var rid = datArray[1];
data = data.replace(/</g,"<").replace(/>/g,">").replace(/\n/g,"<br />").replace(/\r/g,"<br />");
_("status_"+sid).innerHTML += '<div id="reply_'+rid+'" class="reply_boxes"><div><b>Reply by you just now:</b><span id="srdb_'+rid+'">remove</span><br />'+data+'</div></div>';
_("replyBtn_"+sid).disabled = false;
_(ta).value = "";
alert("reply ok!");
} else {
alert(ajax.responseText);
}
ajax.send("action=status_reply_ok&sid="+sid+"&user="+user+"&data="+data);
}
}

Categories

Resources