Alert Window after Insert Statement on Success/Fail - javascript

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");
});
});

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"}]

Inserting Row into Database using HTML/PHP/AJAX

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

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()

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;
}

show html in auto complete jqueryUi

i use jqueryui for search in my site just like facebook
jquery code:
//search main
function split( val ) {
return val.split( );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#mainsearch" ).bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "ui-autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function( request, response ) {
$.getJSON( "/block/search.php", {
term: extractLast( request.term )
}, response );
},
search: function() {
var term = extractLast( this.value );
if ( term.length < 2 ) {
return false;
}
},
focus: function() {
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
window.location.replace(ui.item.url);
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
php code:
while($f = mysqli_fetch_array($s,MYSQLI_ASSOC)){
if($userid != $f['id']){
$name = $f['name'].' '.$f['family'];
$url = $siteurl.$f['username'].'/';
array_push($results, array('id' => $f['id'],'value' => $name,'url' => $url));
}
}
echo json_encode($results);
but if i insert image tag like:
<img src='something'>
its just show < img > text not an image when its show result
there is anyway to solve it?
thank you
From the jQuery-ui docs: "If you want the label to be treated as html you can use Scott González' html extension".
ok i solve this problem with code blow:
function split( val ) {
function extractLast( term ) {
return split( term ).pop();
}
$( "#mainsearch" ).autocomplete({
source: function( request, response ) {
$.getJSON( "/block/search.php", {
term: extractLast( request.term )
}, response );
},
search: function() {
var term = extractLast( this.value );
if ( term.length < 2 ) {
return false;
}
},
focus: function() {
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
window.location.replace(ui.item.url);
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
})
.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li style='clear:both'>" )
.append( ""+item.value+"")
.appendTo( ul );
};return val.split( );
}
and php code:
while($f = mysqli_fetch_array($s,MYSQLI_ASSOC)){
if($userid != $f['id']){
$name = $f['name'].' '.$f['family'];$img = getimagesizes($f['image'],50);
$url = $siteurl.$f['username'].'/';
array_push($results, array('id' => $f['id'],'img' => $img,'value' => $name,'url' => $url));
}
}
echo json_encode($results);
.data must convert to html and show your result
as you can see in my qustion example in jqueryui is completely diffrent with this
but with this you can put html in your auto complete :)

Categories

Resources