After submitting a form with ajax the returned result appears on a new page. The chrome console returns me an error in almost every element: it is not a function validates, but php insert them and shows the result displayed in this new page.
$(document).ready(function () {
$('#newsletter').submit(function(e){
var $this = $(this);
e.preventDefault();
$response = $('#response'),
$mail = $('#email'),
testmail = /^[^0-9][A-z0-9._%+-]+([.][A-z0-9_]+)*[#][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/,
hasError = false;
$response.find('p').remove();
if (!testmail.test($mail.val())) {
$response.html('<p class="error">Please enter a valid email</p>');
hasError = true;
}
if (hasError === false) {
$response.find('p').remove();
$response.addClass('loading');
$.ajax({
type: "POST",
dataType: 'json',
cache: false,
url: $this.attr('action'),
data: $this.serialize()
}).done(function (data) {
console.log(data);
$response.removeClass('loading');
$response.html('<p>'+data.message+'</p>');
}).fail(function() {
$response.removeClass('loading');
$response.html('<p>An error occurred, please try again</p>');
})
}
return false;
});
});
php code
<?php
$host = "";
$dbname = "";
$user = "";
$pass = "";
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$datetime = date('Y-m-d H:i:s');
try {
$db = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
if (empty($email)) {
$status = "error";
$message = "The email address field must not be blank";
} else if (!preg_match('/^[^0-9][A-z0-9._%+-]+([.][A-z0-9_]+)*[#][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/', $email)) {
$status = "error";
$message = "You must fill the field with a valid email address";
} else {
$existingSignup = $db->prepare("SELECT COUNT(*) FROM signups WHERE signup_email_address='$email'");
$existingSignup->execute();
$data_exists = ($existingSignup->fetchColumn() > 0) ? true : false;
if (!$data_exists) {
$sql = "INSERT INTO signups (signup_email_address, signup_date) VALUES (:email, :datetime)";
$q = $db->prepare($sql);
$q->execute(
array(
':email' => $email,
':datetime' => $datetime
));
if ($q) {
$status = "success";
$message = "You have been successfully subscribed";
} else {
$status = "error";
$message = "An error occurred, please try again";
}
} else {
$status = "error";
$message = "This email is already subscribed";
}
}
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
$db = null;
}
catch(PDOException $e) {
echo $e->getMessage();
}
The error displayed: undefinied is not a function in
$response = $('#response'),
$mail = $('#email'),
var $this = $(this);
Message displayed in blank page:
{"status":"success","message":"You have been successfully subscribed"}
Solved. Now works fine in another way, but I would like to know the mistake.
This works
(function ($, window, document, undefined) {
'use strict';
var $form = $('#newsletter');
var $response = $('#response');
$form.submit(function (e) {
var formData = {
'news' : $('input[name="news"]').val(),
'email' : $('input[name="email"]').val(),
};
$.ajax({
type : 'POST',
url : 'news.php',
data : formData,
dataType : 'json',
encode : true
}).done(function (data) {
if (!data.success) {
$('#response').html(data);
$response.html('<div class="alert alert"><button class="close" data-dismiss="alert">x</button>' + data.message + '</div>');
} else {
$('#response').html(data);
$response.html('<div class="alert alert"><button class="close" data-dismiss="alert">x</button>' + data.message + '</div>');
}
}).fail(function (data) {
response.html('<div class="alert alert-error"><button class="close" data-dismiss="alert">x</button>' + data.message + '</div>');
// for debug
console.log(data)
});
e.preventDefault();
});
}(jQuery, window, document));
Related
I have a form. When I submit and try to insert a duplicate record in the database, the page reloads and the error message is logged in the console. However, after* the page reloads, a question mark is already appended to the end of the URL. Why is that so?
Like from this:
http://localhost/project/home
to this (after database error occurred due to duplicate record):
http://localhost/project/home?
Controller:
public function loadBoardManagement()
{
$role = $this->session->userdata('role');
$user_id = $this->session->userdata('user_id');
$board_id = $this->uri->segment(3);
$role = 'Admin';
$user_id = 1;
if ($this->uri->segment(3) == null)
{
$board_id = 178;
}
if ($this->session->userdata('first_board_id') !== null && $board_id == 0)
{
$board_id = $this->session->userdata('first_board_id');
}
$data['boards'] = $this->Board_model->getBoards($role, $user_id);
$data['board_assignees'] = $this->Team_model->getBoardAssignees($board_id);
$data['all_teams'] = $this->Team_model->getAllTeams();
$data['team_quantity'] = $this->Team_model->getBoardTeamsQuantity($board_id);
$data['board_name'] = $this->Board_model->getBoardName($board_id);
$data['board_id'] = $board_id;
$this->load->view('board_management', $data);
}
public function fast_signup()
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$first_name = $this->input->post('first_name');
$last_name = $this->input->post('last_name');
$email = $this->input->post('email');
$role = $this->input->post('role');
$fast_signup = $this->User_model->fastSignup($username, $password, $first_name, $last_name, $email, $role);
if ($fast_signup)
{
echo 'success';
}
else
{
echo $fast_signup;
}
}
javascript:
function addMember()
{
var username = $('#username').val();
var password = $('#password').val();
var first_name = $('#first_name').val();
var last_name = $('#last_name').val();
var email = $('#email').val();
var role = $('#role option:selected').val();
console.log('Role: ' + role);
console.log(username + password + first_name + last_name + email);
$.ajax({
type: 'POST',
url: base_url + 'user/fast_signup', //controller for inserting new members, but the current page is localhost/project/board/loadBoardManagement
data: {
'username': username,
'password': password,
'first_name':first_name,
'last_name': last_name,
'email': email,
'role' : role
},
success: function(msg)
{
if (msg == 'success')
{
console.log('Member created');
window.location.href = window.location.href;
}
else
{
console.log('Failed to create member!' + msg);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log('Response: ' + jqXHR.responseText);
console.log('Status code: ' + textStatus);
console.log('Error thrown: ' + errorThrown);
}
});
}
$('#create_user_member').click(function() {
addMember();
});
So I have these codes wherein I want a notification to appear in every event. I want to check if the record exists, then a notification will appear, saying the college already exists. But that doesn't happen tho. I keep on inputting duplicate input, but the notification still says it's successful. Is there a mistake in my code?
add-college.php
<?php
function findDuplicate($code) {
try {
include($_SERVER['DOCUMENT_ROOT']."/config/db-config.php");
$sql = "SELECT * FROM colleges WHERE collegecode = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $code);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
return true;
}
else {
return false;
}
}
catch (Exception $e) {
return false;
}
}
try {
include($_SERVER['DOCUMENT_ROOT']."/config/db-config.php");
$code = $_POST['code'];
$name = $_POST['name'];
$result = array();
if (findDuplicate($code)) {
$result['message'] = 'duplicate';
}
else {
$sql = "INSERT INTO colleges(collegecode, collegename) VALUES(?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $code, $name);
if ($stmt->execute()) {
$result['message'] = 'success';
}
else {
$result['message'] = 'error';
}
}
echo json_encode($result);
}
catch (Exception $e) {
echo json_encode($result);
}
?>
script.js
$("#save-new").click(function() {
var form = $("#add-college");
var code = $("#code").val();
var name = $("#name").val();
$.ajax({
type: "POST",
data: {
code: code,
name: name
},
url: "../ajax/add-college.php",
dataType: "html",
success: function(data) {
if (data.message = "success") {
$.notify({
// options
message: 'College has been added.'
},{
// settings
type: 'success'
});
}
else if (data.message = "duplicate") {
$.notify({
// options
message: 'College already exists.'
},{
// settings
type: 'warning'
});
}
else {
$.notify({
// options
message: 'College cannot be added.'
},{
// settings
type: 'error'
});
}
$("#code").val("");
$("#name").val("");
$("#add-new").modal('hide');
showColleges();
}
});
});
data.message = "success" this is assignment operation, if you want to compare two string use == operator.
So, the correct statement would be for the if condition would be if(data.message == "success")
Similarly, if(data.message == "duplicate"). I am sure you are aware of all this!
After send my form data to php file its return if any error found. But its also return success before ajax redirect page. I want display error message only and if success, redirect another page.
ajax:
$("#msform").submit(function(){
$.ajax({
type:"post",
url:"pagesubmit.php",
data: $("#msform").serialize(),
dataType : 'json',
success: function(data){
if ( ! data.success) {
$(".help-block").fadeIn().html(data.error);
} else {
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + data.success;
}
}
});
});
php:
include_once ("db.php");
global $dbh;
function check($name){
if(!$name || strlen($name = trim($name)) == 0){
$error ="* Username not entered";
}
else{
$name = stripslashes($name);
if(strlen($name) < 5){
$error ="* Name below 5 characters";
}
else if(!preg_match("/^([0-9a-z])+$/i", $name)){
$error ="* Name not alphanumeric";
}
else {
return 1;
}
}
}
$name = mysqli_real_escape_string($dbh, $_POST['name']);
$thisname = strtolower($name);
$retval = check($thisname);
if($retval ==1){ // if no error found
$success ='upage/userpage?user='.$_SESSION['username'].'';
}
$data = array();
$data['error'] = $error;
$data['success'] = $success;
if (!empty($data)) {
echo json_encode($data);
}
Solved the problem, in this way:
Ajax:
$("#msform").submit(function(){
// collect input name
ver name = var catag=$('#name').val();
$.ajax({
type:"post",
url:"pagesubmit.php",
data: $("#msform").serialize(),
success: function(data){
if ( data != 'success') {
$(".help-block").fadeIn().html(data);
} else {
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + name;
}
}
});
});
php:
function check($name){
if(!$name || strlen($name = trim($name)) == 0){
echo "* Username not entered";
}
else{
$name = stripslashes($name);
if(strlen($name) < 5){
echo "* Name below 5 characters";
}
else if(!preg_match("/^([0-9a-z])+$/i", $name)){
echo "* Name not alphanumeric";
}
else {
return 1;
}
}
}
$name = mysqli_real_escape_string($dbh, $_POST['name']);
$thisname = strtolower($name);
$retval = check($thisname);
if($retval ==1){ // if no error found
echo 'success';
}
EDIT
Set your variables $success and $error
$success = "";
$error= "";
If you doesn't init them, you cannot use them and the .=operator is for concatenation not for set.
Then you should encode the response in php in JSON.
Something like
$response = json_encode(
array(
'success'=> true,
'route' => "mypage/info?user=$_SESSION['username']"
)
);
And return this, then access your response like you already do :
var success = response.success;
UPDATE
change this code to add an else statement :
if($retval ==1){ // if no error found
$success ='upage/userpage?user='.$_SESSION['username'].'';
}else{
$success = 'error';
}
and this line :
else {
return 1;
}
to :
else {
$error = 'none';
}
and in your javascript :
$("#msform").submit(function(){
$.ajax({
type :"post",
url :"pagesubmit.php",
data : $("#msform").serialize(),
dataType : 'json',
success : function(data){
if(data.success == 'error') {
$(".help-block").fadeIn().html(data.error);
}else{
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + data.success;
}
}
});
});
i want to make login form with session (with PHP + ajax), i send username from controller with json but it doesn't work. i don't know whats wrong, please help
this is the function in controller :
public function actionLogin()
{
$username = isset($_POST['username'])?$_POST['username']:null;
$password = isset($_POST['password'])?sha1($_POST['password']):null;
$json = new JsonHelper();
$result = array();
if($username && $password !=''){
$checkLogin = Administrator::model()->findByAttributes(
array('username'=>$username, 'password'=>$password));
$checkUser = Administrator::model()->findByAttributes(
array('username'=>$username));
$checkPass = Administrator::model()->findByAttributes(
array('password'=>$password));
$login = count($checkLogin);
$user = count($checkUser);
$pass= count($checkPass);
if($login==1)
{
$result['status'] = 'success';
$result['username'] = $username;
$json->addData('ajax', $result);
}
elseif($user == 1 && $pass == 0)
{
$result['status'] = 'wrongPass';
$json->addData('ajax', $result);
}
elseif($user == 0 && $pass == 1)
{
$result['status'] = 'wrongUser';
$json->addData('ajax', $result);
}
}
echo json_encode($json->getJson());
}
and this is the form_login.js file :
function login(){
var form = $('#login-form');
var formId = form.attr('id');
var action = form.attr('data-action');
var method = form.attr('data-method');
var formData = serializer(form); //don't mind this function
$.ajax(
{
url: action,
cache: false,
processData: false,
contentType: false,
type: method,
data: formData,
success: function(json)
{
// AJAX SUCCESS
var json = JSON.parse(result);
if(json['result']['ajax']['status']=='success')
{
//$_SESSION['username'] =json['username'];
window.location = baseUrl + "/appsterize/dashboard/index";
}
else if(json['result']['ajax']['status']=='wrongPass')
{
// Password wrong
alert("The password you entered is incorrect.");
}
else if(json['result']['ajax']['status']=='wrongUser')
{
// Username isn't exist
alert("Username isn't exist");
}
},
error: function(xhr, status, error)
{
// AJAX ERROR
var string = "<strong>Error!</strong> " + xhr['responseText'];
$(alertError).attr('data-text', string);
$(alertError).click();
},
});
}
some error is 'Uncaught ReferenceError: alertError is not defined'
Have an element with id = 'alertError'?
Could this be the solution:
$("#alertError").attr('data-text', string);
...
Basically, what #serakfalcon said above:
...
error: function(xhr, status, error)
{
// AJAX ERROR
var errorMsg = "<strong>Error!</strong> " + xhr['responseText'];
alert(errorMsg);
},
...
My problem is that I have two messages:
error message
success message
Here with the help of jQuery, I fetch the email field value and want to check whether email exits in the database or not.
If exits then show success message, otherwise show error message.
$('#email').blur(function(){
var err_msg_css={"background-color":"#FDE4E1","border":"1px solid #FBD3C6","border-radius":"10px 4px 4px 10px","color":"#CB4721","font-size": "14px","float":"left","font-family":"Arial, Helvetica, sans-serif","font-size":"small","font-style":"oblique","height":"22px","margin-left":"6px","padding":"3px","width":"196px"};
var sucess_msg_css={"background-color":"#D5FFC6","border":"1px solid #C0F0B9","border-radius":"10px 4px 4px 10px","color":"#48A41C","font-size": "14px","float":"left","font-family":"Arial, Helvetica, sans-serif","font-size":"small","font-style":"oblique","height":"22px","margin-left":"6px","padding":"3px","width":"196px"};
var text = /[a-z]$/;
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
var email=$('#email').val();
if(!$('#email').val()){
$('#err_msg_9').html('<img src="css/images/error.jpg">email field is empty').css(err_msg_css).show();
return false;
}else{
if(!pattern.test(email)){
//console.log('qwerty')
$('#err_msg_9').html('<img src="css/images/error.jpg">email is not valid').css(err_msg_css).show();
return false;
}else{
var Email=$("#email").val();
var datatype = 'email='+ Email;
$.ajax
({
type: "POST",
url: "ajax_centre.php",
data: datatype,
cache: false,
success: function(html)
{
$("#err_msg_9").html(html);
}
});
//$('#err_msg_9').html('<img src="css/images/success.jpg">sucessful').css(sucess_msg_css).show();
//
return false;
}
}
//$('#err_msg_1').hide();
return true;
});
PHP
if($_POST['email'])
{
$email=$_POST['email'];
$counter=0;
$sql=mysql_query("SELECT `email` FROM `form_value` WHERE `email`='$email'");
while($row = mysql_fetch_array($sql)){
if($email == $row['email']){
$counter = 1;
//echo "email is already in use";
}else{
//echo "email is unique";
}
}
}
//error message
$('#err_msg_9').html('<img src="css/images/error.jpg">email is not valid').css(err_msg_css).show();
//success message
$('#err_msg_8').html('<img src="css/images/success.jpg">sucessful').css(sucess_msg_css).show();
JSON is useful for this time.
Client code:
$.ajax
({
type: "POST",
url: "ajax_centre.php",
data: datatype,
cache: false,
success: function(html)
{
try{
json = $.parseJSON(html);
}catch(e){}
if( typeof json !== 'object' ){
alert(html);
return false;
}
if( ! json.success ){
var html = '<img src="css/images/error.jpg">' + json.message;
$("#err_msg_9").html(html).css(err_msg_css).show();
}else{
var html = '<img src="css/images/success.jpg">' + json.message;
$("#err_msg_8").html(html).css(sucess_msg_css).show();
}
}
});
Server Code:
$row = mysql_fetch_array($sql);
$response = array();
if( !empty($row) && $email === $row['email']){
$counter = 1;
$response['success'] = false;
$response['message'] = "email is already in use";
}else{
$response['success'] = true;
$response['message'] = "email is unique";
}
echo json_encode($response);