how checking multiple field using ajax & mysql - javascript

how to check multiple field using ajax & mysql
for example, I Want to check or validate if an email exist in my database
my code is
jquery_append.js
$(document).ready(function() {
var count = 0;
$("#add_btn").click(function(){
count += 1;
$('#container').append(
'<div class="s"><tr class="records">'
+ '<td ><div id="'+count+'">No : ' + count + '</div></td></tr>'
+ '<tr class="records"><td><label>Email</label><input id="email_' + count + '" name="email_' + count + '" type="text" class="email" required><label>Nama Depan</label><input id="nama_depan_' + count + '" name="nama_depan_' + count + '" type="text"><label>Nama Belakang</label><input id="nama_belakang_' + count + '" name="nama_belakang_' + count + '" type="text"></td></tr>'
+ '<tr class="records"><td><label>Tipe Operasi</label><select name="tipe_operasi_' + count + '"><option value="0">-Pilih-</option></select></td><tr>'
+ '<tr class="records"><td><label>Lokasi</label><select name="lokasi_' + count + '"><option value="0">-Pilih-</option></select></td><tr>'
+ '<tr class="records"><td><label>Alamat</label><input id="alamat_' + count + '" name="alamat_' + count + '" type="text"></td><tr>'
+ '<br><tr class="records"><td><a class="remove_item" href="#" >Delete</a>'
+ '<input id="rows_' + count + '" name="rows[]" value="'+ count +'" type="hidden"></td></tr><tr><td><hr></td></tr></div>'
);
});
$(".remove_item").live('click', function (ev) {
if (ev.type == 'click') {
$(this).parents(".s").fadeOut();
$(this).parents(".s").remove();
}
});
});

Write a function and trigger it on blur of your email field. Pass your email as a parameter of your function and check it into your database.
This is your email field:
<input type="text" class="form-control" name="email" id="email" value="" />
This is your JavaScript code:
$(document).ready(function() {
$("#email").blur(function(){
var email = $("#email").val();
if(email != ""){
$.ajax({
url: 'ajax_function_url',
data: {email:email},
type: 'post',
complete: function(output) {
var isExist = output.responseText;
if(isExist === '1'){
alert('This email is already in use.');
}else{
alert('success!!');
}
}
});
}else{
alert('Email should not be empty');
}
});
}
This is your PHP function which is called by Ajax:
function CheckEmailExist() {
$conn = new mysqli($servername, $username, $password, $dbname);
if (isset($_POST['email']) && $_POST['email'] != "") {
$sql = "SELECT id FROM `table` WHERE `email` = '" . $_POST['email'] . "'";
$result = $conn->query($sql);
echo mysql_num_rows($result);
}
exit();
}
This way you can check if your data exists in your database or not via ajax.

Related

how to filter data on button click and display on the same tab without reloading the page

i have three tabs. in one i want to load data from database and have a filter by email. when i click the button i want the data of only the user with the email to be displayed in the table in the same tab.
this is my script in view
<script>
jQuery('.savedata').click(function (e) {
e.preventDefault();
jQuery.post('/gettabdata', {
_token: window.csrf_token,
email: jQuery('input[name="email"]').val()
}
function (data) {
var $tableBody = jQuery('#filtered-data tbody');
$tableBody.html('');
jQuery.each(data, function (i) {
$tableBody.append(
'<tr>' +
'<td>' + data[i].User_id + '</td>' +
'<td>' + data[i].email + '</td>' +
'<td>' + data[i].status + '</td>' +
'<td>' + data[i].date + '</td>' +
'<td>' + data[i].time + '</td>' +
'</tr>'
);
});
}
'json');
});
</script>
this is my controller
for the tab in which i want to see the result
else {
$user = \Auth::guard('api')->user();
$post = $request->all();
$email = $request->input('email');
$cond = ' 1=1 ';
if(!empty($post['email'])){
$cond .= " and email like '".$post['email']."'";
}
$qry = 'SELECT User_id, email, status, date, time FROM profile WHERE '.$cond.' ';
$data = DB::select($qry);
$response = $this->analysis($post);
//$getdata=$this->userdata($post);
$data = [
'data'=>$data,
'response'=>$response,
//'getdata'=>$getdata
];
return response()->json($data);
}
try this
Route
Route::get('/get-record-by-email','Controller#getRecord');
//controller
public function getRecord(Request $request)
{
$emailid= Input::get('email_id');
$jsondata= DB::table(your-table)->where('email',$emailid)->get();
return response()->json($jsondata);
}
//Ajax call
$("#btnClick").change(function(e){
//console.log(e);
var email_id = e.target.value;
//alert(email_id);
//$token = $("input[name='_token']").val();
//ajax
$.get('/get-record-by-email?email_id='+email_id, function(data){
$('#filterdata').empty();
//console.log(data);
$.each(data, function(index, obj){
$('#filterdata').append( '<tr>'
'<td>' + obj.User_id + '</td>' +
'<td>' + obj.email + '</td>' +
'<td>' + obj.status + '</td>' +
'<td>' + obj.date + '</td>' +
'<td>' + obj.time + '</td>' +
'</tr>' );
});
})
});

How to clear last generated table with new one on radio select

I am working on a module with 3 radio buttons. Clicking one radio button lists data related to it and so on. I have applied ajax call on radio buttons click and return an array in the response. My problem here is for each radio button click the data keeps on adding into the list. For e.g. if I click on 'All users' radio it displays the data related to "All" but again if I click on "Unapproved Users" radio, the list adds up to the 'All users ' listing at the bottom. So how can I reset the $_POST variable each time the data is rendered so that new list appears for new radio selection, I would really appreciate the help or advice for this.
<script>
$('#selection').change
(
function()
{
var selected_value = $("input[name='users']:checked").val();
//till here the code works fine.
$.ajax
(
{
url: "approval_ajax.php",
dataType : "json",
type: "POST",
cache: false,
data: { selected_value : selected_value },
success: function(response)
{
console.log(response);
var len = response.length;
for(var i=0; i<len; i++){
var id = response[i].id;
var email = response[i].email;
var employee_id = response[i].employee_id;
var first_name = response[i].first_name;
var middle_name = response[i].middle_name;
var last_name = response[i].last_name;
var mobile = response[i].mobile;
var created_on = response[i].created_on;
var disabled = response[i].disabled;
var tr_str = "<tr>" +
"<td>" + (i+1) + "</td>" +
"<td>" + email + "</td>" +
"<td>" + employee_id + "</td>" +
"<td>" + first_name + " " + middle_name + " " + last_name + "</td>" +
"<td>" + mobile + "</td>" +
"<td>" + created_on + "</td>" +
"<td><input type='checkbox' name='check[]'" + disabled + "value= '" + id + "' class='checkbox' id='select_all' ></td>" +
"<input type='hidden' value='" + id + "' name='user_id' id='user_id' >" +
"</tr>";
$("#example").append(tr_str);
}
alert("AJAX was a success");
}
}
);
}
);
</script>
approval_ajax.php
session_start();
require("../includes/config.php");
require("../classes/Database.class.php");
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
$return_arr = array();
$status='';
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$value = filter_input(INPUT_POST, "selected_value");
if (isset($value))
{
$users=$value;
}else{
$users='';
}
switch ($users)
{
case "all":
$sqlQuery = "SELECT * FROM tbl_user WHERE type =3";
break;
case "approved":
$sqlQuery = "SELECT * FROM tbl_user WHERE type =3 AND status =1";
break;
case "unapproved":
$sqlQuery = "SELECT * FROM tbl_user WHERE type =3 AND status =0";
break;
}
$sq = $db->query($sqlQuery);
if ($db->affected_rows > 0) {
while ($row = mysql_fetch_array($sq)) {
$disabled = '';
if ($status == '1') {
$disabled = "disabled = 'disabled' checked='checked' ";
}
$id = $row['id'];
$email = $row['email'];
$employee_id = $row['employee_id'];
$first_name = $row['first_name'];
$middle_name = $row['middle_name'];
$last_name = $row['last_name'];
$mobile = $row['mobile'];
$created_on1 = $row['created_on'];
$created_on = date("d-m-Y", strtotime($created_on1));
$return_arr[] = array("id" => $id,
"email" => $email,
"employee_id" => $employee_id,
"first_name" => $first_name,
"middle_name" => $middle_name,
"last_name" => $last_name,
"mobile" => $mobile,
"created_on" => $created_on,
"disabled" => $disabled
);
}
}
header('Content-Type: application/json', true, 200);
echo json_encode($return_arr);
}
An append() jQuery function adds html content to requested element. In your case, you want to refresh users list on click of radio select. You need to use html() jQuery function to clear old result and add new result to requested element.
So please modify following line of your code:
$("#example").append(tr_str);
to
$("#example").html(tr_str);
Let me know if it helps.

Bind event for dynamic added elements in Jquery not working

I have added Address,city and locality using jQuery in a dynamic added div element where the binding event is not working as expected:
I have below jQuery code:
<script type="text/javascript">
$(document).ready(function () {
var counter = 0;
$(document).on('click', '#addButton', function (e) {
if (counter > 19) {
alert("Only 20 Address allowed");
return false;
}
e.preventDefault();
var elems = '<div class="col-lg-5" id="Address' + counter + '">' +
'<textarea class="form-control" name="alt_address[]" rows="3" placeholder="Address' + (counter + 1) + '"/><div class="col-lg-6 form-group col-lg-offset-6"> </div>' +
'<div class="col-lg-3 form-group" id="city' + counter + '">' +
'<select name="city_name[]" id="city_name' + counter + '" class="form-control"><option value="" selected ="selected">Select City</option></select>' +
'</div><div class="col-lg-3 form-group"><select name="locality_name[]" id="locality_name' + counter + '" class="form-control"><option value="" selected="selected" >Select Locality</option></select></div></div>' +
'<div class="col-lg-1 form-group">' +
'<button type="button" class="removebtn" id="removeButton' + counter + '">' +
'<span class="glyphicon glyphicon-minus"></span></button>' +
'</div><div class="col-lg-6 form-group col-lg-offset-6"> </div>';
//('#addressDiv').append(elems);
$('#addressDiv').append(elems);
$.ajax({
type: "Post",
url: "city_load.php",
success: function (html) {
$('#city_name' + counter).html(html);
}
});
$(document).on('change', '#city_name' + counter, function (ev) {
ev.preventDefault();
$city_id = $(this).val();
$.ajax({
type: "Post",
url: "ajax-dd3ck.php",
data: "city_id=" + $city_id,
cache: "false",
success: function (html) {
$('#locality_name' + counter).html(html);
}
});
});
//counter++;
return false;
});
$(document).on('click', '.removebtn', function () {
if (counter == 0)
{
alert("No more textbox to remove");
return false;
}
counter--;
$("#Address" + counter).remove();
$("#removeButton" + counter).remove();
});
});
</script>
My PHP Code for adding city in dropdown
city_load.php:
<?php
include("db.php");
$sql = "select * from city";
echo "<select name='city_name[]' id='city' class='city1'><option value='' selected ='selected'>Select City</option>";
$res = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($res)) {
echo "<option value='$row[city_id]'>$row[city_name]</option>";
}
echo "</select>";
?>
locality_load.php
<?php
include("db.php");
$city_id = $_POST['city_id'];
$sql = "select locality_id,locality_name,city_id from locality where city_id=$city_id";
$res = mysqli_query($con, $sql);
$result = mysqli_query($con, $sql) or die("query error");
while ($rows = mysqli_fetch_array($result)) {
$locality_id = $rows['locality_id'];
$locality_name = $rows['locality_name'];
echo "<option value=" . $locality_id . ">" . $locality_name . "</option>";
//echo '<option value="'.$locality_id.'">'.$locality_name.'</option>';
}
?>
The issue I am getting is that the first dynamic div is getting added and data is loading properly but for 2nd dynamic div it is not working.
Please have a look on screenshot:
save the counter value as a data-attr
eg
var elems = '<div class="col-lg-5 Address" data-id="' + counter + '">' +
'<textarea class="form-control" name="alt_address[]" rows="3" placeholder="Address' + (counter + 1) + '"/><div class="col-lg-6 form-group col-lg-offset-6"> </div>' +
'<div class="col-lg-3 form-group city" data-id="' + counter + '">' +
'<select name="city_name[]" data-id="' + counter + '" class="form-control city_name"><option value="" selected ="selected">Select City</option></select>' +
'</div><div class="col-lg-3 form-group"><select name="locality_name[]" data-id="' + counter + '" class="form-control locality_name"><option value="" selected="selected" >Select Locality</option></select></div></div>' +
'<div class="col-lg-1 form-group">' +
'<button type="button" class="removebtn" data-id="' + counter + '">' +
'<span class="glyphicon glyphicon-minus"></span></button>' +
'</div><div class="col-lg-6 form-group col-lg-offset-6"> </div>';
use a class for each element , bind events on class .
like
$(document).on('change','.city_name', function (ev) {
counter_id = $(this).attr('data-id');
}
so you will get the counter value and hope it will work for every div you created. (code not tested )
$(document).ready(function () {
var counter = 0;
$(document).on('click', '#addButton', function (e) {
if (counter > 19) {
alert("Only 20 Address allowed");
return false;
}
e.preventDefault();
var $elems = $('<div class="col-lg-5" id="Address' + counter + '">' +
'<textarea class="form-control" name="alt_address[]" rows="3" placeholder="Address' + (counter + 1) + '"/><div class="col-lg-6 form-group col-lg-offset-6"> </div>' +
'<div class="col-lg-3 form-group" id="city' + counter + '">' +
'<select name="city_name[]" id="city_name' + counter + '" data-index="' + counter + '" class="form-control"><option value="" selected ="selected">Select City</option></select>' +
'</div><div class="col-lg-3 form-group"><select name="locality_name[]" id="locality_name' + counter + '" class="form-control"><option value="" selected="selected" >Select Locality</option></select></div></div>' +
'<div class="col-lg-1 form-group">' +
'<button type="button" class="removebtn" id="removeButton' + counter + '">' +
'<span class="glyphicon glyphicon-minus"></span></button>' +
'</div><div class="col-lg-6 form-group col-lg-offset-6"> </div>');
//('#addressDiv').append(elems);
$('#addressDiv').append($elems);
$.ajax({
type: "Post",
url: "city_load.php",
success: function (html) {
$elelms.find('select').html(html);
}
});
counter++;
return false;
});
$(document).on('change', 'select', function (ev) {
var cc = $(this).attr('data-index');
ev.preventDefault();
$city_id = $(this).val();
$.ajax({
type: "Post",
url: "ajax-dd3ck.php",
data: "city_id=" + $city_id,
cache: "false",
success: function (html) {
$('#locality_name' + cc).html(html);
}
});
});
$(document).on('click', '.removebtn', function () {
if (counter == 0)
{
alert("No more textbox to remove");
return false;
}
counter--;
$("#Address" + counter).remove();
$("#removeButton" + counter).remove();
});
});
There are maybe some problem!

jQuery not pushing JSON-data

I have the following script which is supposed to pull data and display it in a HTML table:
$('#search_filter_button').click(function (e) {
e.preventDefault(); // Stop form submission
var county = $('#filter_county').val(),
kp_type = $('#filter_kp_type').val(),
getUrl = window.location,
baseUrl = getUrl.protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
html_tr = '';
$.ajax({
type: 'GET',
url: baseUrl + "/reports/get_report.php?county=" + county + "&kp_type=" + kp_type,
dataType: "JSON",
success: function (data) {
console.log(data);
for (i = 0; i < data.length; i++) {
html_tr += '<tr>\n\
<td>' + data[i].name + '</td>\n\
<td>' + data[i].Abbrv + '</td>\n\\n\
<td>' + data[i].partner_name + '</td>\n\\n\
<td>' + data[i].facility_name + '</td>\n\\n\
<td>' + data[i].county + '</td>\n\\n\
<td>' + data[i].no_kps + '</td>\n\\n\
<td>' + data[i].activity_stamp + '</td>\n\</tr>';
}
$('#tbody_append').empty();
$('#tbody_append').append(html_tr);
}, error: function (data) {
}
});
});
My get_report.php file looks like this:
include '../database/db_connect.php';
$mysqli = mysqli_connect($host_name, $user_name, $password, $database);
$county = $_GET['county'];
$kp_type = $_GET['kp_type'];
// get the records from the database
$result = mysqli_query($mysqli, "SELECT * FROM `no_individaul_kps_contacted` where county='$county'");
$count_row = mysqli_num_rows($result);
if ($count_row >= 1) {
// display records if there are records to display
while ($user_data = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo json_encode($user_data);
}
} else {
// show an error if there is an issue with the database query
echo "Error: " . $mysqli->error;
}
// close database connection
mysqli_close($mysqli);
This pulls the information and echoes it back in JSON ENCODE format. But my JavaScript is not returning a success.
Please advise what am I doing wrong.
Collect the user data into array inside the while loop and move json_encode($data) outside the while loop:
$select = "SELECT * FROM `no_individaul_kps_contacted` where county='$county'";
$result = mysqli_query($mysqli, $select);
$data = [];
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$data[] = $row;
}
echo json_encode($data);

how to insert correctly in javascript and php

Hello. I have a function to add row. I just added a second input but I don't know how to insert it correctly.
My JS code:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var counter = 0;
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong> No. ' + counter + '</strong>'
+
'<strong> ........................ Client ' + counter + '</strong><br />'
+
'<input id="field_' + counter + '" name="dynfields[]' + '" type="text" />'
+
'<input id="field_' + counter + '" name="dynfieldstest[]' + '" type="text" /><br />'
);
});
});
</script>
How I insert:
if (isset($_POST['submit_val'])) {
if ($_POST['dynfields']) {
// HERE WHERE IT'S DOEST WORK //
foreach (array_combine( $_POST['dynfields,dynfieldstest'] as $key=>$value, $key=>$value1 )) {
$values = mysql_real_escape_string($value);
$values1 = mysql_real_escape_string($value1);
$query = mysql_query("INSERT INTO recherche (hobbies,client) VALUES ('$values', '$values1')", $connection );
}
}
echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Info Added</h2></i>";
mysql_close();
}
Thanks for help!
I'm guessing that you're looking for a solution that will scale as more and more inputs are added to the form. Here's a simpler way. It assumes that for each dynfields there will be a corresponding dynfieldstest, and we can count the number of dynfields in order to control the loop.
if (isset($_POST['submit_val'])) {
if ($_POST['dynfields']) {
$post_count = count($_POST['dynfields']);
for ($i=0;$i<$post_count;$i++) {
$values = mysql_real_escape_string($_POST['dynfields'][$i]);
$values1 = mysql_real_escape_string($_POST['dynfieldstest'][$i]);
$query = mysql_query("INSERT INTO recherche (hobbies,client) VALUES ('$values', '$values1')", $connection );
}
}
echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Info Added</h2></i>";
mysql_close();
}
Also, it's time to stop using the deprecated mysql functions. Switch to mysqli for MySQL only, or if you switch to PDO you can interface with MySQL and lots of other database types (MSSQL, Oracle, PostgreSQL, SQLite, etc...).
You should insert all new rows at once.
And use mysqli or PDO in the future, not the old mysql_* functions.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var counter = 0;
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong> No. ' + counter + '</strong>'
+
'<strong> ........................ Client ' + counter + '</strong><br />'
+
'<input id="field_' + counter + '" name="dynfields[]' + '" type="text" />'
+
'<input id="field_' + counter + '" name="dynfields[]' + '" type="text" /><br />'
);
});
});
</script>
PHP:
if (isset($_POST['submit_val'])) {
if (is_array($_POST['dynfields'])) {
foreach($_POST['dynfields'] as $key=>$value)
{
$hobbies = mysql_real_escape_string($value);
$client = mysql_real_escape_string($key);
$queryStr[] = "('$hobbies', '$client')";
}
$query = mysql_query("INSERT INTO recherche (hobbies,client) VALUES ".implode(',',$queryStr), $connection );
}
echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Info Added</h2></i>";
mysql_close();
}
To add new input simply add
+
'<input id="field_' + counter + '" name="dynfields[]' + '" type="text" /><br />'
to the js

Categories

Resources