JQuery Display Alert Message on Form Submit - javascript

I am trying to display alert messages on jquery from the client side. The jquery will be called once the submit button is clicked. The form then will call the server side php. Here is my code:
FORM
<form action="branch_add_verifier.php" method="POST" id="formAdd">
<input type="text" name="id" id="id">
<input type="submit" value="submit">
</form>
JQUERY
$(document).ready(function(){
var $form = $('#formAdd');
$form.submit(function(){
var id= $("#id").val();
if (id.length < 12) {
alert("INPUT ERROR");
return false;
}
$.post($form.attr('action'), $(this).serialize(), function(response){
alert("DATA SUCCESSFULLY ADDED");
},'json');
return false;
});
});
But the alert message does not pop up inside the $.postmethod
And I also want to know how I can pop up the alert message from the server side. Here is my sample code:
SERVER SIDE
<?php $query = mysqli_query($conn, "SELECT * FROM table1
INNER JOIN table2
ON table1.col1= table2.col1
WHERE table2.col3= '".$_REQUEST['id']."'");
if (mysqli_num_rows($query) != 0) {
echo "<script>alert('ERROR')</script>";
return false;
} ?>
In summary, the code above works but I need to display messages that would tell me if the query is successful or not. Thanks
My new problem is that the code below bring me to another page:
FORM
<form action="branch_add_verifier.php" method="POST" id="formAdd">
<input type="text" name="id" id="id">
<input type="submit" value="submit">
</form>
JQUERY
$(document).ready(function(){
$('#formAdd').on('submit', function (e) {
e.preventDefault();
var id= $("#id").val();
if (id.length < 12) {
alert("INPUT ERROR");
return false;
}
$.ajax({
context: this,
url: $(this).attr('action'),
type: 'POST',
data: new FormData(this),
dataType: 'json'
}).done(function (data) {
if(data == 'ok') {
alert("DATA SUCCESSFULLY ADDED");
}
if(data == 'no') {
alert("ERROR");
}
}).fail(function (data) {
console.log('failed');
});
});
});
SERVER
$query = mysqli_query($conn, "SELECT * FROM table1
INNER JOIN table2
ON table1.col1= table2.col1
WHERE table2.col3= '".$_REQUEST['id']."'");
if (mysqli_num_rows($query) != 0) {
mysqli_close($conn);
echo json_encode('no');
return false;
}
I need to return after the json_encode because there are still methods below that.

HTML Form
<form action="branch_add_verifier.php" method="POST" id="formAdd">
<input type="text" name="id" id="id">
<input type="submit" value="submit">
</form>
Script :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(function() {
$(document).on('submit', "#formAdd", function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
type: "post",
data: $(this).serialize(),
error:function(){
alert("ERROR : CANNOT CONNECT TO SERVER");
},
success: function(data) {
alert(data);
}
});
return false;
});
});
</script>
PHP server side like this:
<?php
$insert = mysqli_query($conn, "insert query here");
if($insert) {
echo json_encode('ok');
} else {
echo json_encode('no');
}
?>

Just you need to put id="id" in input type text.
<input type="text" name="id">
Working Code
$(document).ready(function(){
var $form = $('#formAdd');
$form.submit(function(){
var id= $("#id").val();
if (id.length < 12) {
alert("INPUT ERROR");
return false;
}
$.post($form.attr('action'), $(this).serialize(), function(response){
alert("DATA SUCCESSFULLY ADDED");
},'json');
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="branch_add_verifier.php" method="POST" id="formAdd">
<input type="text" id="id" name="id">
<input type="submit" value="submit">
</form>

Related

get data back from ajax php script

hello i am trying to add live search functionality to my website i used ajax php to do so
i would like when i click on a live search result to change the value of the live search field and to put the id of the selected result in a hidden form field to be used in insert later
i tried doing it in the code below but it gives the following error:
Uncaught SyntaxError: missing ) after argument list
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"search.php",
method:"GET",
data:{textbook:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
<script>
selectxt(id, textbood_adress){
$('#search').val(textbood_adress);
}
</script>
<div class="form-group input-group" id="textbook">
<input type="text" name="search" id="search" placeholder="Search" class="form-control">
<span class="input-group-btn">
<button class="btn btn-default" type="button"><i class="fa fa-search"></i>
</button>
</span>
</div>
<div id="result"></div>
and for the php
include ("../../includes/config.php");
$output = '';
if(isset($_GET['textbook'])){
$key=$_GET['textbook'];
$key = $db->escape($key);
$results = $db->rawQuery("SELECT * from textbook where textbook_address like '%{$key}%' ");
if($db->count > 0){
$output .= '
<div class="table-responsive">
<table class="table table bordered">
<tr>
<th>Textbook address</th>
<th>select?</th>
</tr>';
foreach ($results as $result) {
$output .= '
<tr>
<td>'.$result["textbook_address"].'</td>
<td><a id="selectclick" href="#" onclick="selectxt('.$result['id'].','.$result['textbook_address'].')">select</a></td>
</tr>
';
}
echo $output;
}else{
echo "<span>No results for your search</span>";
}
}
?>
Your function declaration is wrong. Change your javascript code
from
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"search.php",
method:"GET",
data:{textbook:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
<script>
selectxt(id, textbood_adress){
$('#search').val(textbood_adress);
}
</script>
to
<script>
function load_data(query) {
$.ajax({
url: "search.php",
method: "GET",
data: {textbook: query},
success: function (data) {
$('#result').html(data);
}
});
}
function selectxt(id, textbood_adress) {
$('#search').val(textbood_adress);
}
$(document).ready(function () {
load_data();
$('#search').keyup(function () {
var search = $(this).val();
if (search != '') {
load_data(search);
}
else {
load_data();
}
});
});
</script>
Your javascript function declaration were wrong and also misplaced. Here's an example on CodePen.
Please check and make sure that $result['textbook_address'] doesn't have ' in it. This will break your html output as the browser will try to interpret it wrong

How to get only the newest value response from Ajax?

I have the issue with AJAX response and display errors.
For example, when I submit my form, I see 1 in console, but If I write something in first input and submit again, then
I see:
1
2
Ajax below read 1 and 2 as both responses, so I see 2 errors but I should see only the newest, so it should be only 2.
Also, I getting value when I try to use search (invite), but Ajax skipping everything and showing only success message after Submit.
ajax.js
$(document).ready(function() {
$('#form_create_circle').submit(function(event){
event.preventDefault();
$.ajax({
url: 'form-create-circle.php',
type: 'POST',
data: $('#form_create_circle').serialize(),
dataType: 'json',
success: function(response) {
console.log(response);
if (response == 1) {
$('#title').addClass('is-invalid');
$('#invalid_title').append('<div class="invalid-feedback"><p>This field is required.</p></div>');
} else if (response == 2) {
$('#invite').addClass('is-invalid');
$('#invalid_invite').append('<div class="invalid-feedback"><p>This field is required.</p></div>');
} else if (response == 3) {
$('#color').addClass('is-invalid');
$('#invalid_color').append('<div class="invalid-feedback"><p>This field is required.</p></div>');
} else {
// success message
$('#_noti-container').append('<div class="noti noti-success noti-top-right noti-close-on-click noti-on-leave" style="z-index:100000"><div class="noti-content-wrapper"><div class="noti-content">Circle has been created!</div><div class="noti-close">×</div></div></div>');
}
}
});
return false;
});
});
form-create-circle.php
require_once($_SERVER['DOCUMENT_ROOT'].'/system/mysql/config.php');
$title = $db->EscapeString($_POST['title']);
$invite = $db->EscapeString($_POST['invite']);
$color = $db->EscapeString($_POST['color']);
$time = date('Y-m-d H:i:s');
$search = $db->QueryFetchArrayAll("SELECT * FROM user_about WHERE firstname LIKE '%".$invite."%' OR lastname LIKE '%".$invite."%'");
foreach ($search as $key) {
echo "
<div class='invite_search_cont'>
<div class='invite_search_img'><img src='{$key['profile_image']}'></img></div>
<div class='invite_search_name'>{$key['firstname']} {$key['lastname']}</div>
</div>
";
}
if ($title == '' || (!preg_match('/^[a-zA-Z0-9]+$/', $title))) {
echo 1;
} elseif ($search == '') {
echo 2;
} elseif ($color == '') {
echo 3;
} else {
$db->Query("INSERT INTO user_circle (user_id, user_added, title, color, time_added) VALUES ('{$user['id']}', '$invite', '$title', '$color', '$time')");
}
HTML
<form method='POST' id='form_create_circle'>
<div class='modal-body'>
<div>
<div class='form-group'>
<input type='text' name='title' id='title' placeholder='Family' class='form-control'>
<div id='invalid_title'></div>
</div>
<div class='form-group'>
<input type='text' name='invite' id='invite' placeholder='Search' class='form-control'>
<div id='invite_search_result'></div>
<div id='invalid_invite'></div>
</div>
<div class='form-group'>
<select name='color' id='color' class='form-control'>
<option value='0'>white</option>
<option value='1'>yellow</option>
<option value='2'>red</option>
</select>
<div id='invalid_color'></div>
</div>
</div>
</div>
<button type='submit' class='btn btn-primary' id='ajax_create_circle'>Submit</button>
</form>
<div id='_noti-container' class='noti-t-right'></div>
Sounds to me you just need to add $('#invalid_...').empty() to the start of the script before the ajax or change .append to .html
Also removeClass on all the divs involved:
$('#form_create_circle').submit(function(event) {
event.preventDefault();
$.ajax({
url: 'form-create-circle.php',
type: 'POST',
data: $('#form_create_circle').serialize(),
dataType: 'json',
success: function(response) {
console.log(response);
$('#title, #invite, #color').removeClass('is-invalid');
$("[id^=invalid]").empty(); // empty all error divs
if ("123".indexOf(response) > -1) {
var type = ["", "title", "invite", "color"][response];
$('#' + type).addClass('is-invalid');
$('#invalid_' + type).html('<div class="invalid-feedback"><p>This field is required.</p></div>');
} else {
// success message
$('#_noti-container').html('<div class="noti noti-success noti-top-right noti-close-on-click noti-on-leave" style="z-index:100000"><div class="noti-content-wrapper"><div class="noti-content">Circle has been created!</div><div class="noti-close">×</div></div></div>');
}
}
});
});

Using AJAX to authorise form with database value

I have a form that requires 'authorization' - where the user needs to enter one of the authorization codes stored in a database to be able to submit the form (basically a password). I'm trying to use AJAX with PHP to both display (using Bootstrap's feedback glyphicons) a tick or cross depending on whether or not the user entered a valid value and allow or prevent form submission. If the user did not enter a valid value, form submission is prevented.
My code below currently isn't working, any help would be greatly appreciated.
HTML:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.5/validator.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.5/validator.min.js"></script>
<form name="auth_form" id="auth_form" method="post" action="action.php">
<p>Please enter authorisation code.</p>
<div class="form-group has-feedback" name="auth_code" id="auth_code">
<input class="form-control" id="auth_code_input" autocomplete="new-password" name="auth_code_input" type="password" required>
<span class="form-control-feedback glyphicon" id="statusIcon"></span>
</div>
<button class="btn btn-success btn-ok" name="Submit" id="submit" type="Submit">Submit</button>
</form>
JS:
<script>
$(document).ready(function() {
// Validate on blur and display 'cross' icon in span if invalid, tick if valid
$('#auth_code_input').blur(function() {
if (!ValidateInput()) {
e.preventDefault();
}
});
// Validate on submit and prevent form submission if invalid
$('#auth_form').on('submit', function(e) {
if (!ValidateInput()) {
e.preventDefault();
}
})
});
// AJAX to check the auth-code server-side
function ValidateInput() {
var given_code = document.getElementById('auth_code_input').value;
$.ajax({
url: 'checkauth.php',
type: 'POST',
data: given_code
});
.done(function(response) {
var response = valid;
if valid = '1' {
$('#statusIcon').removeClass('glyphicon-remove').addClass('glyphicon-ok');
IsValid = true;
} else {
$('#statusIcon').removeClass('glyphicon-ok').addClass('glyphicon-remove');
IsValid = false;
}
}
.fail(function() {
IsValid = false;
$('#auth_code_input').val('Something went wrong, please try again.');
});
return IsValid;
});
</script>
checkauth.php
<?php
error_reporting(E_ALL);
ini_set( 'display_errors', 1);
$given_code = $_REQUEST['given_code'];
include 'pdo_config.php';
$valid = '0';
try {
$conn = new PDO($dsn, $user, $pass, $opt);
$stmt = $conn->prepare("SELECT instructor_id, auth_code FROM tbl_instructors WHERE auth_code = :given_code;");
$stmt->bindParam(':given_code', $given_code);
$stmt->execute();
$row = $stmt->fetchColumn();
if ($row == 1) { // row equals one, means auth-code corresponds to an instructor and is valid
$valid = '1';
} else {
$valid = '0';
}
echo valid;
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
found some errors in your js, function ValidateInput() {, plz update your code from below one.
function ValidateInput() {
var given_code = document.getElementById('auth_code_input').value;
$.ajax({
url: 'checkauth.php',
type: 'POST',
data: given_code
});
.done(function(response) {
if (response == '1') {
$('#statusIcon').removeClass('glyphicon-remove').addClass('glyphicon-ok');
IsValid = true;
} else {
$('#statusIcon').removeClass('glyphicon-ok').addClass('glyphicon-remove');
IsValid = false;
}
}
.fail(function() {
IsValid = false;
$('#auth_code_input').val('Something went wrong, please try again.');
});
return IsValid;
});
if it still not work, then plz add async: true in your ajax call like this,
$.ajax({
url: 'checkauth.php',
type: 'POST',
data: given_code,
async: true
});
It will work definitely

JQuery Ajax does not response to Node JS

I have the following form (in the client side):
<html>
<body>
<script>
$(document).ready(function() {
$.ajax({
url: "Search.html",
type: "POST",
dataType : "json",
success: function (result) {
console.log(result);
if(result.status == 200 && result.validationFailed ){
alert(result.message);
}
},
error: function(result){
console.log(result);
if(error.responseText == 'showAlert'){
alert( "Sorry, there was a problem!" );
}
}
})
});
}
</script>
<form action="/process_post" method="POST">
<select name="SearchTypes">
<option value="Author" selected>Author</option>
<option value="Mention">Mention</option>
<option value="Tag">Tag</option>
</select>
<input type="text" name="term">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
In the server side, I am using Node JS to validate data against the database and reply back to the client. I have one case where there is no data in the database and I want to tell the user using Ajax data are not available:
var query = connection.query(queryString, [term,term], function(err, rows) {
var res1 = {};
console.log(rows);
var tweet = JSON.parse(JSON.stringify(rows));
if (tweet.length == 0){
res1.status = 200;
res1.validationFailed = true;
res1.message = 'Empty data';
res.send(JSON.stringify(res1));
}else{
for(var i in tweet){
res.write("Author: ");
......
When I run the code, I do not get an alert. I actually get the following:
{"status":500,"validationFailed":true,"message":"Empty data"}
Can you please help me with this
You forgot to set the data in $.ajax.

PHP/JavaScript login script refreshing when form is submitted

I've created a login page using the following JavaScript:
function handleLogin() {
var form = $("#loginForm");
//disable the button so we can't resubmit while we wait
//$("#submitButton",form).attr("disabled","disabled");
var e = $("#username", form).val();
var p = $("#password", form).val();
console.log("click");
if(e != "" && p != "") {
//var str = form.serialize();
//alert(str);
$.ajax({
type: 'POST',
url: 'http://localhost/php/log.php',
crossDomain: true,
data: {username: e, password :p},
dataType: 'json',
async: false,
success: function (response){
alert ("response");
if (response.success) {
alert("you're logged in");
window.localStorage["username"] = e;
window.localStorage["password"] = md5(p);
//window.localStorage["UID"] = data.uid;
window.location.replace("http://www.google.co.uk");
}
else {
alert("Your login failed");
//window.location("main.html");
}
},
error: function(error){
//alert(response.success);
alert('Could not connect to the database' + error);
window.location = "index.html";
}
});
}
else {
//if the username and password is empty
alert("You must enter username and password");
}
return false;
}
and the PHP in log.php is:
$link = mysql_connect("$host", "$username", "$password") or die("Could not connect to host.");
mysql_select_db("$db_name", $link) or die("Could not find database.");
$uname = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
$sql = "SELECT * FROM user WHERE username = '$uname' AND password = '$password'";
$result=mysql_query($sql);
$num_row=mysql_num_rows($result);
$row=mysql_fetch_array($result);
if (is_object($result) && $result->num_rows == 1) {
$response['success'] = true;
}
else
{
$response['success'] = false;
}
echo json_encode($response);
//echo 'OK';
I would expect the page to show some error if the combination is wrong, or redirect to a different page if it's correct. However it just refreshes with the username/password in the url.
Log in form
<form id="loginForm" method="post">
<div data-role="fieldcontain" class="ui-hide-label">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="" placeholder="Username" />
</div>
<div data-role="fieldcontain" class="ui-hide-label">
<label for="password">Password:</label>
<input type="password" name="password" id="password" value="" placeholder="Password" />
</div>
<input type="submit" value="Login" id="submitButton">
</form>
Since you're using jQuery (version 1.10.1), you can bind the click event directly to your forms submit button
$(document).on('click', '#submitButton', function(e) {
e.preventDefault();
... See detailed jsFiddle example ...
return false;
});
With preventDefault(), you remove the default submit behavior of the Submit button, so the page won't be reloaded after form submit.
Also use form attributes like action to provide ajax URL, or method, for setting ajax request type.
P.S This type of binding won't work for jQuery 1.6
jsFiddle example
Please change your html container as follows
<div data-role="fieldcontain" class="ui-hide-label">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="" placeholder="Username" />
</div>
<div data-role="fieldcontain" class="ui-hide-label">
<label for="password">Password:</label>
<input type="password" name="password" id="password" value="" placeholder="Password" />
</div>
<input type="button" value="Login" id="submitButton" onclick="handleLogin()">
Since, you are submitting data using ajax, then you dont need to writt "form" tag in your html
Total page would be refresh when click "Submit" button. so I have changed as "button" and provide the ajax method in "onclick" attribute
Sample PHP file (index.php) that I tried without connecting DB for testing yours scenario
<?php
if($_POST){
if($_POST['username'] == "admin" && $_POST['password'] == "admin"){
$response['success'] = true;
}else{
$response['success'] = false;
}
echo json_encode($response);
exit;
}
?>
modified your js code
function handleLogin() {
var e = $("#username").val();
var p = $("#password").val();
if(e != "" && p != "") {
$.ajax({
type: 'POST',
url: 'index.php',
crossDomain: true,
data: {username: e, password :p},
dataType: 'json',
async: false,
success: function (response){
alert ("response");
if (response.success) {
alert("you're logged in");
}
else {
alert("Your login failed");
}
},
error: function(error){
alert('Could not connect to the database' + error);
}
});
}
else {
alert("You must enter username and password");
}
return false;
}
Try this: if(response.responseText)

Categories

Resources