Inserting Row into Database using HTML/PHP/AJAX - javascript

I have a button that can be clicked that will bring up a popup box with one textfield. Whenever, I enter something and click "Add", I want it to be inserted into my database.
Currently, when I click "Add", it will insert into the DB, but it will not read the value entered. Therefore, a null value is simply entered. I get no errors that I can see, however in my JavaScript I do a console.log(dict) and the output in the log is Object {} so it doesn't look like the entered value is being logged. I also am getting a successful row inserted message in the logs too so I would definitely think that it is just a matter of being able to get the values to be read.
So my question is how can I get it to read the value and successfully enter it into the database.
HTML of Add button:
<td><button class="create-user" id="insertButton">Add Group</button></td>
HTML of Popup Box:
<div id="dialog-form" title="Add Group">
<p class="validateTips">Please Add a Group</p>
<!-- Dialog box displayed after add row button is clicked -->
<form>
<fieldset>
<label for="sku_group">SKU Group</label>
<input type="text" name="group" id="group" class="text ui-widget-content ui-corner-all">
<!-- Allow form submission with keyboard without duplicating the dialog button -->
<input type="submit" id="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
JavaScript:
// ----- Dialog Box for adding a row -----
$( function() {
var dialog, form,
sku_group = $( "#group" ),
allFields = $( [] ).add( sku_group ),
tips = $( ".validateTips" );
console.log(allFields);
function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
}, 500 );
}
function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) ) {
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}
function addGroup() {
var valid = true;
allFields.removeClass( "ui-state-error" );
// ----- Validation for each input in add row dialog box -----
valid = valid && checkRegexp( sku_group, /^[a-z]([0-9a-z_\s])+$/i, "Please enter a valid SKU Group name" );
console.log(allFields);
if ( valid ) {
var $tr = $( "#skuTable tbody tr" ).eq(0).clone();
var dict = {};
var errors = "";
$.each(function(){
$tr.find('.' + $(this).attr('id')).html( $(this).val()+"-"+sku_group );
var type = $(this).attr('id');
var value = $(this).val();
console.log(type + " : " + value);
// ----- Switch statement that provides validation for each table cell -----
switch (type) {
case "group":
dict["SKU Group"] = value;
break;
}
});
$( "#skuTable tbody" ).append($tr);
dialog.dialog( "close" );
console.log(dict);
var request = $.ajax({
type: "POST",
url: "insert-group.php",
data: dict
});
request.done(function (response, textStatus, jqXHR){
if(JSON.parse(response) == true){
console.log("row inserted");
} else {
console.log("row failed to insert");
console.log(response);
}
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
});
}
return valid;
}
var dialog = $( "#dialog-form" ).dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Add Group": addGroup,
Cancel: function() {
dialog.dialog( "close" );
}
},
close: function() {
form[ 0 ].reset();
}
});
form = dialog.find( "form" ).on( "submit", function( event ) {
event.preventDefault();
addGroup();
});
$( ".create-user" ).button().on( "click", function() {
dialog.dialog({
show: 'blind',
hide: 'blind'
});
dialog.dialog("open");
});
});
insert-group.php script:
<?php
$SKU_Group = $_POST['SKU Group'];
$host="xxxxxxxxxxx";
$dbName="xxxxxxx";
$dbUser="xxxx";
$dbPass="xxxxxxxxxxxxxx";
$pdo = new PDO("sqlsrv:server=".$host.";Database=".$dbName, $dbUser, $dbPass);
$sql = "INSERT INTO SKU_Group_Dim ([SKU Group]) VALUES (?)";
$stmt = $pdo->prepare($sql);
$result = $stmt->execute(array($SKU_Group));
echo json_encode($result);
?>
EDIT
My html table:
<table id="skuTable" cellspacing="5" class="ui-widget ui-widget-content">
<thead>
<tr class="ui-widget-header">
<th class="skuRow">SKU Group</th>
<th class="skuRow">Group ID</th>
<th class="skuRow">Edit</th>
<th class="skuRow">Delete</th>
</tr>
</thead>
<tbody>
<?php foreach ($dbh->query($sql_table) as $rows) { ?>
<tr>
<td class="sku_group" id="sku_group-<?php echo intval ($rows['SKU Group'])?>"><?php echo $rows['SKU Group']?></td>
<td class="group_id" align="center" id="group_id-<?php echo intval ($rows['Group_ID'])?>"><?php echo $rows['Group_ID']?></td>
<td><button type="button" class="edit" name="edit">Edit</button></td>
<td><button type="button" class="delete" onclick="deleteRow(this)">Delete</button></td>
</tr>
<?php
}
?>
</tbody>
</table>

Your value does not good
Try to change
var value = $(this).val();
To
var value = $(this).find('input[type=text]').val();

Try changing your $.each function to $tr.each. I think you should provide something for it to iterate over. Here is the link to .each() documentation..
If you want to iterate over all 's you have to add td to jquery call.
My fix would look like this:
var $tr = $( "#skuTable tbody tr td" ).eq(0).clone(); //get all td of sku-table
var dict = {};
$tr.each(function(){
var type = $(this).attr('id'); // get value of current tr
var value = $(this).html(); // get html content inside of tr
switch (type) {
case "group":
dict["SKU Group"] = value;
break;
}
});
$('#group').val(dict['SKU Group']); // set value of the input field

Related

jQuery Autocomplete, pass parameters into database

Hlleo, please help me in figuring this our from an example i took this and is working fine,
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function() {
var availableTags = [
{key: "1",value: "NAME 1"},{key: "2",value: "NAME 2"},{key: "3",value: "NAME 3"},{key: "4",value: "NAME 4"},{key: "5",value: "NAME 5"}
];
$( "#project-name" ).autocomplete({
minLength: 0,
source: availableTags,
focus: function( event, ui ) {
$( "#project-name" ).val( ui.item.value );
return false;
},
select: function( event, ui ) {
$( "#project-name" ).val( ui.item.value );
$( "#project-id" ).val( ui.item.key );
return false;
}
});
});
</script>
<form action="search" method="post" >
<input id="project-name" name="project2" id="searchbox"/>
<input type="text" id="project-id" />
</form>
but for me i need it from database so i called the source as url and passed data to it as parameters like this
but in here only the console part works but the input is not populated,
What i want is to populate the input with label value(header Id) and store the id(task_summary_id) came along with it in another hidden input field when the item is selected from the list
So i did this to the original code
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function() {
// var output = '';
// $('#project-name').keyup(function(){
// var query = $(this).val();
// if(query != '')
// {
// console.log(query);
// $.ajax({
// url:"autoCompleteNew.php",
// method:"POST",
// data:{query:query,cl:4},
// success:function(data)
// {
// console.log(data);
// output = data;
//
//
//
//
// }
// });
// }
// });
$("#project_name").autocomplete({
//var output = '';
source: function(request, response) {
console.log(request.term);
$.ajax({
url: 'autoCompleteNew.php',
method:"POST",
data: {
query : request.term,
cl : 4
},
success: function(data) {
//response(data);
// output = data;
console.log(data); //here i am getting the correct log
// var parsed = JSON.parse(data);
},
// console.log(output);
});
},
focus: function( event, ui ) {
$( "#project_name" ).val( ui.item.value );// nothing here nothing in autocomplete
return false;
},
select: function( event, ui ) {
$( "#project_name" ).val( ui.item.value );// but nothing here
$( "#project-id" ).val( ui.item.key );
return false;
}
});
// $( "#project_name" ).autocomplete({
// minLength: 2,
// source: 'autoCompleteNew.php',
// data:{query:'gb',cl:4},
// focus: function( event, ui ) {
// $( "#project_name" ).val( ui.item.value );
// return false;
// },
// select: function( event, ui ) {
// $( "#project-name" ).val( ui.item.value );
// $( "#project-id" ).val( ui.item.key );
//
// return false;
// }
// });
// var availableTags = [
// {key: "1",value: "Mukund"},{key: "2",value: "Nandu"},{key: "3",value: "Dimble"},{key: "4",value: "Alisha"},{key: "5",value: "Parvathy"}
// ];
});
</script>
<form action="search" method="post" >
<input id="project_name" name="project2" id="searchbox"/>
<input type="text" id="project-id" />
</form>
please help me in figuring this out
my php code
$usr = $_POST['term'];
$cl = $_POST['cl'];
//$usr = 'm';
$output = '';
$usr = strtolower($usr);
//$retVar = array();
$db_handle = new DBController();
$query = "select task_summary_id as 'key',task_header_id as 'value' from gb_task_summary where LCASE(task_header_id) like '$usr%' and task_header_client_id = $cl";
//echo $query;
$i=0;
// $output = '<ul class="list-unstyled" id ="listUl">';
$results = $db_handle->runQuery($query);
if(!empty($results))
{
$retVar=$results;
}
else
{
$retVar = 'N';
}
// foreach ($retVar as $key => $value) {
// $output .= '<li id ="listLI">'.$value["task_header_id"].'</li>';
// $output .='<ul id ="listUl">';
// $output .= '<dd class="unselectable" id ="listDD">'.$value["task_header_name"].'</dd>';
// $output .='</ul>';
//
// }
//
// $output .= '</ul>';
echo json_encode($retVar);
my json response for '1111'
[{"key":"499","value":"1111"},{"key":"500","value":"1134"},{"key":"501","value":"1195"},{"key":"502","value":"1211"},{"key":"503","value":"1197"},{"key":"504","value":"1085"},{"key":"505","value":"1193"},{"key":"506","value":"1090"},{"key":"507","value":"1076"},{"key":"508","value":"1196"},{"key":"543","value":"1471"},{"key":"544","value":"1472"},{"key":"566","value":"1111"},{"key":"569","value":"1111"},{"key":"570","value":"1111"},{"key":"571","value":"1111"},{"key":"577","value":"1111"},{"key":"584","value":"1475"},{"key":"585","value":"1454"},{"key":"586","value":"1476"},{"key":"587","value":"1705"},{"key":"588","value":"1541"},{"key":"589","value":"1707"},{"key":"590","value":"1722"},{"key":"591","value":"1721"},{"key":"592","value":"1720"},{"key":"593","value":"1719"},{"key":"594","value":"1718"},{"key":"595","value":"1717"},{"key":"596","value":"1711"},{"key":"597","value":"1710"},{"key":"598","value":"1709"},{"key":"599","value":"1701"},{"key":"600","value":"1704"},{"key":"601","value":"1751"},{"key":"602","value":"1746"},{"key":"603","value":"1784"},{"key":"604","value":"1736"},{"key":"622","value":"1755"},{"key":"623","value":"1769"},{"key":"624","value":"1796"},{"key":"625","value":"1797"},{"key":"626","value":"1803"},{"key":"647","value":"1789"},{"key":"648","value":"1811"},{"key":"649","value":"1813"},{"key":"650","value":"1820"},{"key":"651","value":"1825"},{"key":"652","value":"1828"},{"key":"658","value":"1836"},{"key":"659","value":"1839"},{"key":"660","value":"1847"},{"key":"661","value":"1706"},{"key":"673","value":"1869"},{"key":"674","value":"1872"},{"key":"686","value":"1899"},{"key":"687","value":"1901"},{"key":"691","value":"1907"},{"key":"692","value":"1908"},{"key":"693","value":"1917"},{"key":"701","value":"1803"},{"key":"702","value":"1807"},{"key":"703","value":"1879"},{"key":"704","value":"1880"},{"key":"705","value":"1881"},{"key":"706","value":"1810"},{"key":"707","value":"1858"},{"key":"708","value":"1902"},{"key":"709","value":"1918"},{"key":"710","value":"1893"},{"key":"730","value":"1952"},{"key":"734","value":"1954"},{"key":"735","value":"1958"},{"key":"736","value":"1954"},{"key":"737","value":"1959"},{"key":"746","value":"1958"},{"key":"749","value":"1990"},{"key":"750","value":"1993"},{"key":"751","value":"1997"},{"key":"754","value":"1976"},{"key":"776","value":"1998"},{"key":"785","value":"1948"},{"key":"894","value":"1705"},{"key":"1008","value":"1111"},{"key":"1031","value":"1976"},{"key":"1375","value":"1111"},{"key":"1556","value":"1976"},{"key":"1819","value":"1624"},{"key":"1838","value":"1111"}]

Adding Row Using PHP/JavaScript/AJAX to Database

I have a button that can be clicked that will bring up a popup box with one textfield. Whenever, I enter something and click "Add", I want it to be inserted into my database.
Currently, when I click "Add", it will insert into the DB, but it will not read the value that was entered. Therefore, a null value is simply entered. I get no errors that I can see, however in my JavaScript I do a console.log(type + " : " + value); and it returns sku_group-0 : in the logs. I also do a console.log(dict) and the output in the log is Object {} so it doesn't look like the entered value is being logged. I also am getting a successful row inserted message in the logs too so it definitely looks like it is just a matter of being able to get the values to be read so they can then be processed in the insert-group.php script.
So my question is how can I get it to read the value in the JavaScript so that it can be successfully entered into the database?
HTML of Popup Box:
<div id="dialog-form" title="Add Group">
<p class="validateTips">Please Add a Group</p>
<!-- Dialog box displayed after add row button is clicked -->
<form>
<fieldset>
<label for="sku_group">SKU Group</label>
<input type="text" name="group" id="group" class="text ui-widget-content ui-corner-all">
<!-- Allow form submission with keyboard without duplicating the dialog button -->
<input type="submit" id="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
HTML of Add button:
<button class="create-user" id="insertButton">Add Group</button>
JavaScript:
$( function() {
var dialog, form,
sku_group = $( "#group" ),
allFields = $( [] ).add( sku_group ),
tips = $( ".validateTips" );
console.log(allFields);
function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
}, 500 );
}
function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) ) {
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}
function addGroup() {
var valid = true;
allFields.removeClass( "ui-state-error" );
// ----- Validation for each input in add row dialog box -----
valid = valid && checkRegexp( sku_group, /^[a-z]([0-9a-z_\s])+$/i, "Please enter a valid SKU Group name" );
console.log(allFields);
if ( valid ) {
var $tr = $( "#skuTable tbody tr td" ).eq(0).clone();
var dict = {};
var errors = "";
$tr.each(function(){
var type = $(this).attr('id');
var value = $(this).html();
console.log(type + " : " + value);
switch (type) {
case "group":
dict["SKU Group"] = value;
break;
}
});
$( "#skuTable tbody" ).append($tr);
dialog.dialog( "close" );
console.log(dict);
var request = $.ajax({
type: "POST",
url: "insert-group.php",
data: dict
});
request.done(function (response, textStatus, jqXHR){
if(JSON.parse(response) == true){
console.log("row inserted");
} else {
console.log("row failed to insert");
console.log(response);
}
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
});
}
return valid;
}
var dialog = $( "#dialog-form" ).dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Add Group": addGroup,
Cancel: function() {
dialog.dialog( "close" );
}
},
close: function() {
form[ 0 ].reset();
}
});
form = dialog.find( "form" ).on( "submit", function( event ) {
event.preventDefault();
addGroup();
});
$( ".create-user" ).button().on( "click", function() {
dialog.dialog({
show: 'blind',
hide: 'blind'
});
dialog.dialog("open");
});
});
insert-group.php script:
<?php
$SKU_Group = $_POST['SKU Group'];
$host="xxxxxxxxxxx";
$dbName="xxxxxxx";
$dbUser="xxxx";
$dbPass="xxxxxxxxxxxxxx";
$pdo = new PDO("sqlsrv:server=".$host.";Database=".$dbName, $dbUser, $dbPass);
$sql = "INSERT INTO SKU_Group_Dim ([SKU Group]) VALUES (?)";
$stmt = $pdo->prepare($sql);
$result = $stmt->execute(array($SKU_Group));
echo json_encode($result);
?>
REPLACE
"data: dict"
WITH
data:{ 'SKU_Group' : $('#group').val() }
AND
REPLACE
"$SKU_Group = $_POST['SKU Group'];"
WITH
$SKU_Group = $_POST['SKU_Group'];
You should get your input value with:
$('#group').val()

Alert Window after Insert Statement on Success/Fail

I have a dialog box that can will add a row to a database on submit. However, if there is an error with the insert, I want an alert window to display so that the user knows it didnt work. I tried to use javascript in my php but that returned an error and whenever I try something this is the error I always get: Uncaught SyntaxError: Unexpected token E in JSON.
How can I get around this and display an alert on submit?
Here is what my original Insert.php code looks like...
<?php
$MR_ID = $_POST['MR_ID'];
$Supp_ID = $_POST['Supp_ID'];
$host="xxxxxxxxx";
$dbName="xxxx";
$dbUser="xxxxxxxxxxx";
$dbPass="xxxxxxxxx";
$pdo = new PDO("sqlsrv:server=".$host.";Database=".$dbName, $dbUser, $dbPass);
$sql = "INSERT INTO Stage_Rebate_Index (MR_ID, Supp_ID) VALUES (?, ?)";
$stmt = $pdo->prepare($sql);
$result = $stmt->execute(array($MR_ID, $Supp_ID));
echo json_encode($result);
?>
EDIT:
JavaScript code:
// ----- Dialog Box for adding mr id and supplier id -----
$( function() {
$("#insertButton").on('click', function(e){
e.preventDefault();
});
var dialog, form,
mr_id_dialog = $( "#mr_id_dialog" ),
supplier_id = $( "#supplier_id" ),
allFields = $( [] ).add( mr_id_dialog ).add( supplier_id ),
tips = $( ".validateTips" );
console.log(allFields);
function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
}, 500 );
}
function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) ) {
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}
function addVendor() {
var valid = true;
allFields.removeClass( "ui-state-error" );
// ----- Validation for each input in add row dialog box -----
//valid = valid && checkRegexp( mr_id_dialog, /^(0|[1-9][0-9]*)$/, "Please enter a valid MR ID" );
valid = valid && checkRegexp( supplier_id, /^(0|[1-9][0-9]*)$/, "Please enter a valid Supplier ID" );
console.log(allFields);
if ( valid ) {
var $tr = $( "#index_table tbody tr" ).eq(0).clone();
var dict = {};
var errors = "";
$.each(allFields, function(){
$tr.find('.' + $(this).attr('id')).html( $(this).val()+"-"+supplier_id );
var type = $(this).attr('id');
var value = $(this).val();
console.log(type + " : " + value);
// ----- Switch statement that provides validation for each table cell -----
switch (type) {
case "mr_id_dialog":
dict["MR_ID"] = parseInt(value);
console.log(dict['MR_ID']);
break;
case "supplier_id":
dict["Supp_ID"] = value;
break;
}
});
$( "#index_table tbody" ).append($tr);
dialog.dialog( "close" );
console.log(dict);
var request = $.ajax({
type: "POST",
url: "insert.php",
data: dict
});
request.done(function (response, textStatus, jqXHR){
if(JSON.parse(response) == true){
console.log("row inserted");
} else {
console.log("row failed to insert");
console.log(response);
}
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
});
}
return valid;
}
var dialog = $( "#dialog-form" ).dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Add Supplier ID": addVendor,
Cancel: function() {
dialog.dialog( "close" );
}
},
close: function() {
form[ 0 ].reset();
allFields.removeClass( "ui-state-error" );
}
});
form = dialog.find( "form" ).on( "submit", function( event ) {
event.preventDefault();
addVendor();
});
$( "#insertButton" ).button().on( "click", function() {
dialog.dialog({
position: ['center', 'top'],
show: 'blind',
hide: 'blind'
});
dialog.dialog("open");
});
});

Taking a String and Inserting Only Numbers from that String

I have a dialog box that pops up after hitting an Add button. There are two inputs, one being a dropdown. The information in the dropdown for example looks like this, 1 - Company A, 2 - Company B, etc. It is a value made up of 2 concatenated values. I need MR_ID, not MR_Name. However, whenever I submit this and insert into the database, I only want those first few numbers, not the company name or anything like that. How can I do this? Would using str_replace or preg_replace work? And if so, how and where would I put it in my code?
Query that populates dropdown list inside dialog box
$sql1 = "WITH cte AS (
SELECT DISTINCT CONCAT(CAST(Stage_Rebate_Index.MR_ID AS INT),' - ', Stage_Rebate_Master.MR_Name) AS MR_ID
, Stage_Rebate_Index.MR_ID AS sort_column
FROM Stage_Rebate_Index
LEFT JOIN Stage_Rebate_Master
ON Stage_Rebate_Master.MR_ID=Stage_Rebate_Index.MR_ID
)
SELECT MR_ID
FROM
cte
ORDER BY
sort_column;";
JavaScript for dialog box and adding information:
$( function() {
$("#insertButton").on('click', function(e){
e.preventDefault();
});
var dialog, form,
mr_id_dialog = $( "#mr_id_dialog" ),
supplier_id = $( "#supplier_id" ),
allFields = $( [] ).add( mr_id_dialog ).add( supplier_id ),
tips = $( ".validateTips" );
console.log(allFields);
function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
}, 500 );
}
function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) ) {
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}
function addVendor() {
var valid = true;
allFields.removeClass( "ui-state-error" );
// ----- Validation for each input in add row dialog box -----
//valid = valid && checkRegexp( mr_id_dialog, /^(0|[1-9][0-9]*)$/, "Please enter a valid MR ID" );
valid = valid && checkRegexp( supplier_id, /^(0|[1-9][0-9]*)$/, "Please enter a valid Supplier ID" );
console.log(allFields);
if ( valid ) {
var $tr = $( "#index_table tbody tr" ).eq(0).clone();
var dict = {};
var errors = "";
$.each(allFields, function(){
$tr.find('.' + $(this).attr('id')).html( $(this).val()+"-"+supplier_id );
var type = $(this).attr('id');
var value = $(this).val();
console.log(type + " : " + value);
// ----- Switch statement that provides validation for each table cell -----
switch (type) {
case "mr_id_dialog":
dict["MR_ID"] = value;
break;
case "supplier_id":
dict["Supp_ID"] = value;
break;
}
});
$( "#index_table tbody" ).append($tr);
dialog.dialog( "close" );
console.log(dict);
var request = $.ajax({
type: "POST",
url: "insert.php",
data: dict
});
request.done(function (response, textStatus, jqXHR){
if(JSON.parse(response) == true){
console.log("row inserted");
} else {
console.log("row failed to insert");
console.log(response);
}
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
});
}
return valid;
}
var dialog = $( "#dialog-form" ).dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Add Supplier ID": addVendor,
Cancel: function() {
dialog.dialog( "close" );
}
},
close: function() {
form[ 0 ].reset();
allFields.removeClass( "ui-state-error" );
}
});
form = dialog.find( "form" ).on( "submit", function( event ) {
event.preventDefault();
addVendor();
});
$( "#insertButton" ).button().on( "click", function() {
dialog.dialog({
position: ['center', 'top'],
show: 'blind',
hide: 'blind'
});
dialog.dialog("open");
});
});
Insert.php
<?php
$MR_ID = $_POST['MR_ID'];
$Supp_ID = $_POST['Supp_ID'];
$host="xxxxxxxxx";
$dbName="xxxxx";
$dbUser="xxxxxxxxxxxx";
$dbPass="xxxxxxxxx";
$pdo = new PDO("sqlsrv:server=".$host.";Database=".$dbName, $dbUser, $dbPass);
$sql = "INSERT INTO Stage_Rebate_Index (MR_ID, Supp_ID) VALUES (?, ?)";
$stmt = $pdo->prepare($sql);
$result = $stmt->execute(array($MR_ID, $Supp_ID));
echo json_encode($result);
?>
in the java script just use a parse int
parseInt(string);
doing this with
var string = "2 - Company A"
var number = parseInt(string);
console.log(number);
give the output of 2
jsfiddle https://jsfiddle.net/esz5jnec/
if i understand your code correctly it would go in the switch
switch (type) {
case "mr_id_dialog":
dict["MR_ID"] = parseInt(value);
break;
case "supplier_id":
dict["Supp_ID"] = value;
break;
}

Retrieving AJAX value from a different Javascript function

In this simplified example of a larger web app, consider a simplistic registration form with fields: username, firstname, lastname and a Register button type="button".
<form action="" method="post" id="cns_form">
<table id="companyTable"><tr>
<td width="200">
First name*:<br />
<input type="text" id="first_name" name="first_name">
</td>
<td width="200">
Last name*:<br />
<input type="text" id="last_name" name="last_name">
</td>
</tr></table>
<input type="button" value="Register" id="register" >
</form>
<div id="alert" title="Alert"></div>
When the username field is completed, jQuery fires an ajax search of a database to see if that username already exists. This same search is also triggered when one clicks Register (for reasons removed from this simplified example).
PROBLEM: Everything works great when leaving the username field. However, after clicking Register, I don't know how to retrieve the result of the AJAX search and stop the form from submitting if the username already exists. I've tried all kinds of different things, but have returned the code to this state so it is easiest for the reader to assist.
For example, I tried integrating the suggested solution from this question, but I was unsuccessful applying it to my situation... I tried setting async:false inside the ajax function... I also tried calling the checkUsername(uname) from inside the checkForm function, but that didn't work either. A little help?
jQuery document.ready:
$(function(){
$('#username').blur(function() {
var uname = $.trim($(this).val());
checkUsername(uname);
}); //END BLUR username
$('#register').click(function() {
var uname = $.trim($( '#username').val());
checkUsername(uname);
checkForm();
});
}); //END document.ready
AJAX Call:
function checkUsername(uname) {
if (uname != '') {
$.ajax({
type: "POST",
url: 'ajax/ax_all_ajax_fns.php',
data: 'request=does_this_username_already_exist&username=' + uname,
async: false,
success:function(data){
//alert('Returned AJAX data: '+data);
if (data != 0) {
var existing_user = data.split('|');
var fn = existing_user[0];
var ln = existing_user[1];
focus_control = 'username';
$( '#alert' ).html( 'That username is already in use by ' + fn +' '+ ln +'. Please choose another.' );
$( '#alert' ).dialog( 'open' );
} //EndIf data<>0
} //End success
}); //End $.ajax
} //End If this.val <> ""
}
checkForm Function:
function checkForm() {
var un = $.trim($( '#username').val());
var fn = $( '#first_name').val();
var ln = $( '#last_name').val()
if (un=='' || fn=='' || ln=='') {
$( '#alert' ).dialog({
height: 200,
width: 300,
});
$( '#alert' ).html( 'Fields marked with an asterisk are required.' );
$( '#alert' ).dialog( 'open' );
} else {
$("#cns_form").submit();
}
}
One both rejoices and weeps when answering his own question, but here goes. The solution was to send the checkUsername() function as an input param to the checkForm() function, and to make the checkUserName() function return a value that we could check inside checkForm().
Therefore, we must modify the $('#register').click function thusly:
$('#register').click(function() {
var uname = $.trim($( '#username').val());
checkForm(checkUsername(uname)); //<===========================
});
THEN the checkUsername() function, thus:
function checkUsername(uname) {
var returnVal = 0; //<=================================
if (uname != '') {
$.ajax({
type: "POST",
url: 'ajax/ax_all_ajax_fns.php',
data: 'request=does_this_username_already_exist&username=' + uname,
async: false,
success:function(data){
//alert('Returned AJAX data: '+data);
if (data != 0) {
var existing_user = data.split('|');
var fn = existing_user[0];
var ln = existing_user[1];
focus_control = 'username';
$( '#alert' ).html( 'That username is already in use by ' + fn +' '+ ln +'. Please choose another.' );
$( '#alert' ).dialog( 'open' );
returnVal = 0; //<============================
} //EndIf data<>0
} //End success
}); //End $.ajax
} //End If this.val <> ""
return returnVal; //<==============================
}
AND the checkform() function thus:
function checkForm(exists) { //<============================
alert('sub checkForm(). value of exists: ' + exists);
if (exists==9) { //<================================
$( '#alert' ).html( 'That username is already in use' + existing +'. Please choose another.' );
$( '#alert' ).dialog( 'open' );
}else{ //<==========================================
var un = $.trim($( '#username').val());
var fn = $( '#first_name').val();
var ln = $( '#last_name').val()
if (un=='' || fn=='' || ln=='') {
$( '#alert' ).dialog({
height: 200,
width: 300,
});
$( '#alert' ).html( 'Fields marked with an asterisk are required.' );
$( '#alert' ).dialog( 'open' );
} else {
$("#cns_form").submit();
}
} //<===================================================
}
Thanks and kudos to Felix Kling for this helpful post.
Might put return false in the function call in the HTML form markup.
<form>
<bunchOfElements />
<button onclick="checkUserName(); return false">Check Name </button>
</form>
Also, you might bind the function to the button's click event using
$(document).ready(function(){
$("#buttonID").bind('click', function(){
//do your thing
checkForm();
});
});
Put a return false at the end of your #register button click function, right below checkForm(). The button is continuing to fire the form submit. when you have that handled by your javascript function.

Categories

Resources