Ajax dynamic select from 2 fields - javascript

I am doing bank account validation using ajax dynamic select. onkeyup after the acc number is entered, it runs a check from external file. Right now, I can only check the account number, I want it to be able to check the bank and acc number. I simple want to GET the value of bank and account to be used for the validation in validate_acc.php.
<script>
function dynamic_Select3(ajax_page, account) {
$.ajax({
type: "GET",
url: ajax_page,
data: "ch=" + account,
//data: "ch2=" + bank,
dataType: "html",
//dataType: "text/html", //<--UPDATE: DELETING THIS LINE FIXES EVERYTHING
//<--UPDATE2: DON'T DELETE; REPLACE "test/html" with "html"
success: function(html){ $("#txtResult3").html(html); }
});
}
</script>
my html form
<td class="body_text_normal_npt">Select your Bank</td>
<td><span class="body_text_normal_npt">
<select name="bank" id="bank">
<option value="Select Values" selected="selected">-------------------------------</option>
<?php
$sql4="SELECT bankName FROM banks WHERE status = 'active'";
$banks = $mydb->query($sql4) or die(mysqli_error($mydb));
$row_banks = mysqli_fetch_assoc($banks);
$totalRows_banks = mysqli_num_rows($banks);
do {
?>
<option value="<?php echo $row_banks['bankName']?>"><?php echo $row_banks['bankName']?></option>
<?php
} while ($row_banks = mysqli_fetch_assoc($banks));
$rows = mysqli_num_rows($banks);
if($rows > 0) {
mysqli_data_seek($banks, 0);
$row_banks = mysqli_fetch_assoc($banks);
}
?>
</select>
</span></td>
</tr>
<tr>
<td class="body_text_normal_npt">Acc Number</td>
<td><p>
<input name="account" type="text" id="account" size="25" onKeyPress="return isNumberKey(event)" onKeyUp="dynamic_Select3('validate_acc.php', this.value)" />
</p>
</td>
</tr>
The validation page
//$bank= $_GET['modepayment'];
$bank= $_GET['ch2'];
$accnum = $_GET['ch'];
$query_bcode = "SELECT bankCode,abbr FROM banks WHERE bankName = '$bank'";
$bcode = $mydb->query($query_bcode) or die(mysqli_error($mydb));
$row_bcode = $bcode->fetch_assoc();
$bankCode = $row_bcode['bankCode'];
//echo $bankCode;
//echo $accnum;
$json = file_get_contents("https://api.bank.codes/ng-nuban/?format=json&api_key=2d112c21e1c5844f*******154&bank=$bankCode&nuban=$accnum");
$obj = json_decode($json);

Possible to try this? You can have multiple parameters in this way.
var request = $.ajax({
url: "ajax_page",
method: "POST",
data: { ch: account, ch2: bank},
dataType: "html"
});
Code is based on an example from http://api.jquery.com/jquery.ajax/

Related

PHP and jQuery insert into MySQL

I am trying to insert data into mySQL using jQuery. The code does not return any error and no any result as well. Please help me to sort this out.
$(document).ready(function() {
$("#submit").click(function() {
var data;
var eid = 101;
data = "eid=" + eid;
for (i = 0; i <= 10; i++) {
data += "&Text_" + (i + 1) + "=" + $("#Text_" + (i + 1)).val();
data += "&Amount_" + (i + 1) + "=" + $("#Amount_" + (i + 1)).val();
}
$.ajax({
type: "POST",
url: "process.php",
cache: false,
data: data,
dataType: "json",
success: function(response) {
if (!response.error) {
$("#msg").addClass('alert-success').html(response.msg);
} else {
$("#msg").addClass('alert-danger').html(response.msg);
}
}
});
});
});
<tr>
<td><input type="text" value="Allowance1 " name="Text[]" id="Text_1" /></td>
<td><input type="text" value="1001.00" name="Amount[]" id="Amount_1" /></td>
</tr>
<tr>
<td><input type="text" value="Allowance 2" name="Text[]" id="Text_2" /></td>
<td><input type="text" value="1002.00" name="Amount[]" id="Amount_2" /></td>
</tr>
<tr>
<td><input type="text" value="Allowance 3" name="Text[]" id="Text_3" /></td>
<td><input type="text" value="1003.00" name="Amount[]" id="Amount_3" /></td>
</tr>
I am adding the process.php snippet also in order to know where is the error.
process.php
$eid=$_POST['eid'];
$length = sizeof($_POST["Text"]);
$i=1;
while ($i<=$length){
if(!empty($_POST['Text'][$i])) {
$Text = $_POST['Text'][$i];
$Amount = $_POST['Amount'][$i];
$msg = array('status' => !$error, 'msg' => 'Failed! updation-1');
if(!$error) {
$sql = "UPDATE TblCustom SET Text='" . $Text . "', Amount='" . $Amount ."' WHERE ID='$eid'";
$status = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
$msg = array('error' => $error, 'msg' => 'Success! updation : '. $sql );
}
else {
$msg = array('error' => $error, 'msg' => 'Failed! updation-2 ');
}
}
echo json_encode($msg);
}
Thanks
You have 3 problems.
Problem number one and two are related. Firstly, you are specifying dataType: 'json', but you are passing your data in application/x-www-form-urlencoded format. Secondly, your php script expects data to be in the following format:
$_POST = [
'Text' => ['text_1', 'text_2', 'text_3'],
'Amount' => ['amount_1', 'amount_2', 'amount_3']
];
While your data looks something like this:
$_POST = [
'Text_1' => 'text_1',
'Text_2' => 'text_2'
// and so on
];
The single fix to this problem is as follows:
$(document).ready(function() {
$("#submit").click(function() {
const data = {
// we are grabbing all inputs with name=Text[]
// and mapping them to array containing their values.
// The `...` is a spread operator introduced
// with the new js standard (ES6),
// that converts jQuery object to regular javascript
// array of inputs.
// you can do all of this with a for loop, but the map way
// is prefered
Text: [...$('input[name="Text[]"]')].map(input => input.value),
Amount: [...$('input[name="Amount[]"]')].map(input => input.value)
}
$.ajax({
type: "POST",
url: "process.php",
cache: false,
data: data,
dataType: "json",
success: function(response) {
if (!response.error) {
$("#msg").addClass('alert-success').html(response.msg);
} else {
$("#msg").addClass('alert-danger').html(response.msg);
}
}
});
});
});
The third problem is that have created an SQL Injection vulnerability. That means some bad guy can inject and SQL statement into Text variable, which then you are putting directly into your sql update, thus he can do whatever he wants (for example drop all database).
More on SQL Injection
The solution is simple: use PDO and bindValue method.
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$conn = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
// 500 means internal server error
// that's handy information for the client-side
http_send_status(500);
echo json_encode([
'error' => [
'message' => 'Unable to connect to database'
]
]);
exit;
}
$eid = $_POST['eid'];
$Text = $_POST['Text'][$i];
$Amount = $_POST['Amount'][$i];
$sql = "UPDATE TblCustom SET Text = :text, Amount = :amount WHERE ID = :id";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':text', $Text);
$stmt->bindValue(':amount', $Amount);
$stmt->bindValue(':id', $eid);
if (!$stmt->execute()) {
// 400 means something went wrong when updating
// also a handy information for the client-side
http_send_status(400);
echo json_encode([
'error' => [
'message' => 'Unable to update'
]
]);
exit;
}
// 204 measn everything went okay, and we don't return anything
http_send_status(204);
exit;
Hint: if you are sending correct status codes the jQuery lets you handle errors like this:
$.ajax({
// ...
success: function(response) {
// this code will be executed
// only when status code == 2xx
},
error: function(response) {
// this code will be executed
// only when status code == 4xx | 5xx (if I remember correctly)
},
always: function(response) {
// this code will be executed no matter what
// as the name implies
},
});
So there is no need for additional if statements.
index.php
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form id="form_signup" name="form_signup">
<tr>
<td><input type="text" value="Allowance1 " name="Text[]" id="Text_1" /></td>
<td><input type="text" value="1001.00" name="SAmount[]" id="Amount_1" /></td>
</tr>
<tr>
<td><input type="text" value="Allowance 2" name="Text[]" id="Text_2" /></td>
<td><input type="text" value="1002.00" name="SAmount[]" id="Amount_2" /></td>
</tr>
<tr>
<td><input type="text" value="Allowance 3" name="Text[]" id="Text_3" /></td>
<td><input type="text" value="1003.00" name="SAmount[]" id="Amount_3" /></td>
</tr>
<input type="submit" name="signup" value="Sign Up!"/>
</form>
<script>
$(document).ready(function() {
$("#form_signup").click(function() {
$.ajax({
type: "POST",
url: "process.php",
cache: false,
data: $(this).serialize(),
success: function(response) {
alert(response);
if (!response.error) {
$("#msg").addClass('alert-success').html(response.msg);
} else {
$("#msg").addClass('alert-danger').html(response.msg);
}
}
});
});
});
</script>
</body>
</html>
process.php
<?php
print_r($_POST);
?>

Ajax form submission inside modal box

Ok here is a strange little problem:
Here is a test page, which user clicks to open:
When user clicks view results I have 3 selectboxes inside the modal box.
box1 => populates =>Box 2 => populates Box 3
My problem
When user clicks submit, instead of results being displayed from the query based on selectbox selections, the test page opens again inside the modalbox... as you can see in below image
On submit
Any idea why when form is submitted current page opens inside modalbox?
Submit Form
<script type="text/javascript">
jQuery(document).click(function(e){
var self = jQuery(e.target);
if(self.is("#resultForm input[type=submit], #form-id input[type=button], #form-id button")){
e.preventDefault();
var form = self.closest('form'), formdata = form.serialize();
//add the clicked button to the form data
if(self.attr('name')){
formdata += (formdata!=='')? '&':'';
formdata += self.attr('name') + '=' + ((self.is('button'))? self.html(): self.val());
}
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: formdata,
success: function(data) { $('#resultForm').append(data); }
});
}
});
</script>
Populate Textboxes
<script type="text/javascript">
$(document).ready(function()
{
$(".sport").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_sport.php",
dataType : 'html',
data: dataString,
cache: false,
success: function(html)
{
$(".tournament").html(html);
}
});
});
$(".tournament").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_round.php",
data: dataString,
cache: false,
success: function(html)
{
$(".round").html(html);
}
});
});
});
</script>
<label>Sport :</label>
<form method="post" id="resultForm" name="resultForm" action="result.php">
<select name="sport" class="sport">
<option selected="selected">--Select Sport--</option>
<?php
$sql="SELECT distinct sport_type FROM events";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
?>
<option value="<?php echo $row['sport_type']; ?>"><?php echo $row['sport_type']; ?></option>
<?php
}
?>
</select>
<label>Tournamet :</label> <select name="tournament" class="tournament">
<option selected="selected">--Select Tournament--</option>
</select>
<label>Round :</label> <select name="round" class="round">
<option selected="selected">--Select Round--</option>
</select>
<input type="submit" value="View Picks" name="submit" />
</form>
<?php
Display result
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo $sport=$_POST['sport'];
echo $tour=$_POST['tournament'];
echo $round=$_POST['round'];
$sql="Select * FROM Multiple_Picks WHERE tournament ='$tour' AND round='$round' GROUP BY member_nr";
$result = mysql_query($sql);
?>
<?php
while($row=mysql_fetch_array($result)){
$memNr = $row['member_nr'];
$pick = $row['pick'];
$score = $row['score'];
?>
echo $memNr;
echo $pick;
echo $score;
}
}
?>
It would appear that:
success: function(data) { $('#resultForm').append(data); } you are telling it to put the ajax response in the resultForm, which appears to be inside your modal. Is that not what is happening. Hard to tell from your question and code what SHOULD be happening vs what IS happening now.

How to populate Bootstrap Multiselect with selected values in php?

I am trying to populate Bootstrap multiselect , I used the following code
html
<form>
<tr>
<td><label>Code Planteur :</label></td>
<td> <input type="text" id="code_planteur" name="code_planteur" class="code_planteur"></td>
</tr>
<tr>
<td><label>Numero de Ticket :</label></td>
<td><select id="num_ticket" name="num_ticket" class="num_ticket">
<option value="0"> numero de ticket </option>
</select></td>
</tr>
</form>
and my php file ticket.php
<?php
require 'conn.php';
if($_POST['id'])
{
$id=$_POST['id'];
$req="select column from table where code_planteur='".$id."' ";
$req = $pdo->query($req);
$results = array();
while($row=$req->fetch())
{
$data=$row['column'];
echo "<option value=".$data.">".$data."</option>";
}
}
?>
my javascript
$(document).ready(function(){
$(".code_planteur").change(function(){
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax({
type: "POST",
url: "ticket.php",
data: dataString,
cache: false,
success: function(html){
$(".num_ticket").html(html);
}
});
});});
how can i transforme my code to use with bootstrap multiselect
example https://jsfiddle.net/j086fkdf/
it work with this javascript
$(document).ready(function()
{
$(".code_planteur").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax({type: "POST",
url: "ticket1.php",
data: dataString,
cache: false,
dataType: "json",
success: function(data)
{
$("#num_ticket").empty();
$.each(data, function (key, val) {
$("#num_ticket").append('<option value="' + val + '">' + val + '</option>');
});
$("#num_ticket").attr('multiple', 'multiple');
$("#num_ticket").multiselect();
}
}
);
}
);
});
and my ticket1.php
<?php
require "conn.php";
if($_POST['id']){
$id=$_POST['id'];
$req="select num_ticket from paiement where code_planteur='".$id."' ";
$req = $pdo->query($req);
while ($row=$req->fetch() ){
$resultat[] = $row['num_ticket'];
}
echo json_encode($resultat);
}
?>
Modify your form
<form>
<tr>
<td><label>Code Planteur :</label></td>
<td> <input type="text" id="code_planteur" name="code_planteur" class="code_planteur"></td>
</tr>
<tr>
<td><label>Numero de Ticket :</label></td>
<td>
<select id="num_ticket" name="num_ticket" class="num_ticket">
<option> numero de ticket </option>
</select>
</td>
</tr>
</form>
For your ticket.php, i suggest you to use prepare query for more security
if($_POST['id']){
$id=$_POST['id'];
$req="select num_ticket from paiement where code_planteur=:id";
$stmt=$pdo->prepare($req);
$stmt->bindValue(":id",$id);
$stmt->execute();
$retour = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($retour as $key => $value) {
echo "<option value = '".$value['num_ticket']."'>".$value['num_ticket']."</option>\n";
}
}
And the ajax query
$(function(){
$("#code_planteur").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax({type: "POST",
url: "ticket1.php",
data: dataString,
cache: false,
dataType: "json",
success: function(data)
{
$("#num_ticket").empty();
$("#num_ticket").html(data);
});
$("#num_ticket").attr('multiple', 'multiple');
$("#num_ticket").multiselect();
}
}
);
}
);
});
If you want the value to be populated as selected then just write the selected tag with option.
For more details please refer:http://www.jqueryscript.net/demo/jQuery-Multiple-Select-Plugin-For-Bootstrap-Bootstrap-Multiselect/

Passing javascript value to php and back

I am having some trouble with passing a javascript value to php and back.
The idea is that I have a form where a user fills out a postal code and is then (onBlur) presented with the correct street and city in two different input fields. The street and city are collected by POST method from an external php file (getAddress.php).
I know that the php script returns the correct values and the complete() function is called onBlur, but I don't know whether the value gets passed onto the php script and back.
Javascript
<script language="javascript">
function complete() {
var postalCode = document.getElementsByName("postalCode")[0].value;
if(postalCode.length === 6) {
var dataString = "postalCode=" + postalCode;
$.ajax({
type: "POST",
url: "getAddress.php",
dataType: "html",
data: dataString,
success: function(results) {
var json = JSON.parse(results);
document.getElementById("street").value = json.street;
document.getElementById("city").value = json.city;
}
});
}
}
</script>
getAddress.php
<?php
$postalCode = $_POST['postalCode'];
$postalCode = substr_replace($postalCode, ' ', 4, 0);
$sql = 'SELECT * FROM postalCodes WHERE postalCode="'.$postalCode.'"';
$res = $con->query($sql);
$res->data_seek(0);
while($row = $res->fetch_assoc()) {
$ID = $row['ID'];
$street = $row['street'];
$city = $row['city'];
$results[] = array('ID' => $ID, 'street' => $street, 'city' => $city);
}
echo json_encode($results);
?>
HTML
<input name="postalCode" type="text" maxlength="6" onBlur="complete()" /><br />
<input name="street" id="street" type="text" disabled /><br />
<input name="number" type="text" maxlength="6" /><br />
<input name="city" id="city" type="text" disabled /><br />
Change dataType: "html", to dataType: "json", and your $results is array so you need to use index
Try this:
function complete() {
var postalCode = document.getElementsByName("postalCode")[0].value;
if (postalCode.length === 6) {
var dataString = "postalCode=" + postalCode;
$.ajax({
type: "POST",
url: "getAddress.php",
dataType: "json",
data: dataString,
success: function(results) {
document.getElementById("street").value = results[0].street;
document.getElementById("city").value = results[0].city;
}
});
}
}
As you are getting 500 internal server error message one of the reason can be that
$con->query($sql) is failing, make sure $con is initialized and table and field name are correct.

How to display the data came from controller/model using Ajax process?

I have a problem here about ajax. Actually I'm a beginner in using Ajax that's why I can't figure out my problem. I have a form that have 4 select boxes. The initial or main selectbox is the country selector. Second is the state next is city and last is barangay. My goal is like this. After the user select his'her country the second selectbox which is state will automatically change according to the user's country. And after selecting the state it will automatically change also the city and last is the barangay. It is just like a dynamic address fields. I am using codeigniter. Here's what I did. This is the process for getting the state.
In my PHP form I have this:
<tr>
<td><label style="font-weight: normal">State / Province: </label></td>
<td >
<select class="form-control" name="c_state" id="c_state">
<option value="">--Select State--<option>
</select>
</td>
</tr>
<tr>
<td><label style="font-weight: normal">Country: </label></td>
<td >
<select class="form-control" name="c_country" id="c_country">
<option value="">--Select Country--</option>
<?php
foreach($countries as $country){
if($country['country'] == 'Philippines'){
echo "<option value='".$country['code']."'selected='selected'>".$country['country']."</option>";
}else{
echo "<option value='".$country['code']."'>".$country['country']."</option>";
}
}
?>
</select>
</td>
</tr>
....
$("#c_country").on('change',function(){
var c_country = $("#c_country").val();
var var_country_selection = '<?php echo site_url("alliance_controller/get_provinces/'+c_country+'"); ?>';
console.log(c_country);
$.ajax({
type: 'POST',
url: var_country_selection,
data: { id: $(this).val() },
dataType: 'json',
success: function(d){
alert(d['c_country']);
}
});
});
In my controller I have this:
public function get_provinces($id){
$country = $this->alliance_model->hhj_provinces($id);
echo json_decode($country);
}
In my model I have this:
public function hhj_provinces($id) {
$query = "SELECT * FROM ref_region_province WHERE country_code = '".$id."'";
$result = $this->db->query($query);
echo json_encode($result->result_array());
}
The output in the success in jquery which is in alert is 'undefined'. And I also use the developer tool in Chrome and I looked in the Network tab it shows the URL of my ajax together the Code. But in my preview I have something like this.
[]
No Properties
That's all guys. I just want to get the state of the country selected.
you must return a JSON object in the controller like this
public function get_provinces(){
$id = $this->input->post('id');
$country = $this->alliance_model->hhj_provinces($id);
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode( $country));
}
then in the View
$.ajax({
type: 'POST',
url: var_country_selection,
data: { id: $(this).val() },
dataType: 'json',
success: function(data){
$.each(data, function (key, value) {
console.log(value.field)
}
});

Categories

Resources