C# Submitting http post request to fill a form - javascript

I am trying to submit a form using C# to my website. On my website I have a petition form where I have a few text boxes and a submit button, I can do this completely fine on the browser, but I want to do it from C#.
Here is the following javascript code it's very simple:
(function($) {
"use strict";
var $button = $('#sign-petition');
$button.submit(function(e){
e.preventDefault();
var $country = '';
var $state = '';
var $zip = '';
var $city = '';
var $terms = '';
var $newsletter = 0;
var $bio = '';
if( $( 'select[name="country"]', this ).length > 0 ) {
$country = $( 'select[name="country"]', this ).val();
}
if( $( 'input[name="state"]', this ).length > 0 ) {
$state = $( 'input[name="state"]', this ).val();
}
if( $( 'input[name="zip"]', this ).length > 0 ) {
$zip = $( 'input[name="zip"]', this ).val();
}
if( $( 'input[name="city"]', this ).length > 0 ) {
$city = $( 'input[name="city"]', this ).val();
}
if( $( 'input[name="terms"]', this ).length > 0 ) {
if( $( 'input[name="terms"]', this ).prop('checked') ){
$terms = $( 'input[name="terms"]', this ).val();
}
}
if( $( 'input[name="newsletter"]', this ).length > 0 ) {
if( $( 'input[name="newsletter"]', this ).prop('checked') ){
$newsletter = 1;
}
}
if( $( 'textarea.bio', this ).length > 0 ) {
$bio = $( 'textarea.bio', this ).val();
}
var data = {
'action': 'sign_petition',
'email' : $( 'input[name="email"]', this ).val(),
'fname' : $( 'input[name="fname"]', this ).val(),
'lname' : $( 'input[name="lname"]', this ).val(),
'bio' : $bio,
'signature' : $( '#signature', this ).val(),
'country' : $country,
'state' : $state,
'zip' : $zip,
'city' : $city,
'terms' : $terms,
'newsletter' : $newsletter
};
$.post( petition.ajaxurl, data, function( response ) {
//console.log(response);
response = JSON.parse(response);
if( typeof(response.errors) !== "undefined" && response.errors !== null ){
if( $( '#petition-errors' ).html() !== '' ){ $( '#petition-errors' ).html(''); }
$('#sign-petition .error').each(function (){
$(this).removeClass('error');
});
$.each( response.errors, function( key, error ){
$( '.' + key, '#sign-petition' ).addClass( 'error' );
$( '#petition-errors' ).append( '<li>' + error[0] + '</li>' );
});
} else{
$( '<p>' + response.success + '</p>' ).insertBefore( '#sign-petition' );
$('#sign-petition').hide();
}
});
});
})(jQuery);
I've used Microsoft's provided example and this is what i have so far, but it's not working.
string uriString = "https://example.org/";
// Create a new WebClient instance.
WebClient myWebClient = new WebClient();
// Create a new NameValueCollection instance to hold some custom parameters to be posted to the URL.
NameValueCollection myNameValueCollection = new NameValueCollection();
myNameValueCollection.Add("signature", "15c8c9a392");
myNameValueCollection.Add("email", "tom#appleseed.com");
myNameValueCollection.Add("fname", "Tom");
myNameValueCollection.Add("lname", "Appleseed");
myNameValueCollection.Add("country", "US");
myNameValueCollection.Add("state", "WA");
myNameValueCollection.Add("zip", "98174");
myNameValueCollection.Add("city", "Seattle");
var responseArray = myWebClient.UploadValues(uriString, myNameValueCollection);
var response = Encoding.ASCII.GetString(responseArray);
var outputFilePath = Environment.CurrentDirectory + "\\petition\\" + DateTime.Now.ToString("yyyy-MM-dd--HH-mm-ss") + ".html";
try
{
File.WriteAllText(outputFilePath, response);
}
catch (Exception e) { Console.WriteLine(e); }
Also here is the html code:
<form id="sign-petition" method="post">
<input type="hidden" id="signature" name="signature" value="15c8c9a392">
<input type="hidden" name="_wp_http_referer" value="/">
<div class="form-group">
<input type="text" class="form-control email" name="email" value="" placeholder="E-mail Address"">
</div>
<div class="form-group">
<input type="text" class="form-control fname" name="fname" value="" placeholder="First Name">
</div>
<div class="form-group">
<input type="text" class="form-control lname" name="lname" value="" placeholder="Last Name">
</div>
<div class="form-group">
<select name="country" class="form-control" id="country">
<option value="0" selected="selected">Select a country ... </option>
<option value="US" label="United States">United States</option>
</select>
</div>
<div class="form-group">
<input type="text" class="form-control lname" name="state" value="" placeholder="State / Province">
</div>
<div class="form-group">
<input type="text" class="form-control lname" name="zip" value="" placeholder="Zip / Postal Code">
</div>
<div class="form-group">
<input type="text" class="form-control lname" name="city" value="" placeholder="City">
</div>
<div class="form-group">
<textarea class="form-control bio" placeholder="comments" rows="3"></textarea>
</div>
<ul id="petition-errors"></ul>
<button type="submit" class="btn btn-primary">Sign Petition!</button>
</form>
Any help is appreciated
Thanks.

What about using an HttpClient and just posting the data? Something like this.
var data = new
{
action = "sign_petition",
signature = "15c8c9a392",
email = "tom.appleseed.com",
fname = "Tom",
lname = "Appleseed",
country = "US",
state = "WA",
zip = "98174",
city = "Seattle"
};
using (var client = new HttpClient())
{
var uriString = "https://example.org";
var result = client.PostAsync(uriString, new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json")).Result;
if (!result.IsSuccessStatusCode)
{
//Handle the error
}
else
{
//Do something else
}
}

Related

The searchfilter i make didn't fetch the data i want to search

I'm adding a search filter in my system but it won't search.Please someone tell Me the problem with my coding.
Controller
public function facility_reservation_view(){
$name = $this->input->post('name');
$searchtype = $this->input->post('searchtype');
$datefrom = $this->input->post('datefrom');
$dateto = $this->input->post('dateto');
$status = $this->input->post("status");
$query = $this->model_facility->facility_reservation_table($name, $status, $searchtype, $datefrom, $dateto);
echo json_encode($query);
}
Model
public function facility_reservation_table($name, $status, $searchtype, $datefrom, $dateto){
// storing request (ie, get/post) global array to a variable
$requestData= $_REQUEST;
global $access;
$columns = array(
// datatable column index => database column name for sorting
0 => 'fr_id',
1 => 'fr_status',
2 => 'CONCAT(fr_fname, fr_mname, fr_lname)',
3 => 'fr_room',
4 => 'fr_purpose',
5 => 'CONCAT(fr_date_from, fr_time_from)',
6 => 'CONCAT(fr_date_to, fr_time_to)'
);
$sql = "SELECT * FROM facility_reservation WHERE fr_enabled = 1";
$query = $this->db->query($sql);
$totalData = $query->num_rows();
$totalFiltered = $totalData; // when there is no search parameter then total number rows = total number filtered rows.
$sql = "SELECT * FROM facility_reservation WHERE fr_enabled = 1";
if ($searchtype == "divdate") {
$sql .= " AND fr_date_from BETWEEN ? AND ? ";
$data = array($datefrom, $dateto);
}
elseif ($searchtype == "divname"){
$sql .= " AND fr_fname LIKE ? " ;
$data = array($name);
}
elseif ($searchtype == "divstatus") {
$sql .= " AND fr_status LIKE ? ";
$data = array($status);
}
$query = $this->db->query($sql, $data);
$totalData = $query->num_rows();
$totalFiltered = $totalData; // when there is no search parameter then total number rows = total number filtered rows.
$sql .=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." "; // adding length
$query = $this->db->query($sql);
$data = array();
$token = en_dec("en", $this->session->userdata('token_session'));
foreach( $query->result_array() as $row ) { // preparing an array for table tbody
$nestedData=array();
$nestedData[] = $row["fr_id"];
$nestedData[] = $row["fr_status"];
$nestedData[] = $row["fr_fname"]." ".$row["fr_mname"]." ".$row["fr_lname"];
$nestedData[] = $row["fr_room"];
$nestedData[] = $row["fr_purpose"];
$nestedData[] = $row["fr_date_from"]." ".$row["fr_time_from"];
$nestedData[] = $row["fr_date_to"]." ".$row["fr_time_to"];
$nestedData[] = '<button data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#viewFRModal" class="btn btn-info btnViewFR btnTable" name="update" data-value="'.$row['fr_id'].'" id="'.$row['fr_id'].'"><i class="fa fa-eye"></i> View</button> <button data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#updateFRModal" class="btn btn-success btnUpdateFR btnTable" name="update" data-value="'.$row['fr_id'].'" id="'.$row['fr_id'].'"><i class="fa fa-edit"></i>Update</button> <button data-toggle="modal" data-backdrop="static" data-keyboard="false" data-target="#deleteFRModal" class="btn btn-primary btnDeleteFR btnTable" name="delete" data-value="'.$row['fr_id'].'" id="'.$row['fr_id'].'"><i class="fa fa-trash"></i> Delete</button>';
$data[] = $nestedData;
}
$json_data = array(
"draw" => intval( $requestData['draw'] ),
"recordsTotal" => intval( $totalData ),
"recordsFiltered" => intval( $totalFiltered ),
"data" => $data
);
return $json_data;
}
view
<div class="row">
<div class="col-lg-2">
<div class="form-group">
<label class="form-control-label col-form-label-sm">Select Filter</label>
<select id="sosearchfilter" class="form-control sosearchfilter">
<option value="divdate">Search by Date</option>
<option value="divname">Search by First Name</option>
<option value="divstatus">Search by Status</option>
</select>
</div>
</div>
<div class="col-lg-4">
<div class="form-group row">
<div class="divdate" id="divdate">
<?php
$dateInTwoWeeks = strtotime('-1 weeks');
$dateInTwoWeeks = date("m/d/Y", $dateInTwoWeeks);
// echo $dateInTwoWeeks;
?>
<label class="form-control-label col-form-label-sm">Date</label>
<div class="input-daterange input-group" id="datepicker">
<input type="text" id="datefrom" class="input-sm form-control material_josh search-input-select1 searchDateTo" value="<?=$dateInTwoWeeks;?>" name="start" readonly/>
<span class="input-group-addon" style="background-color:#fff; border:none;">to</span>
<input type="text" id="dateto" value="<?=today_text();?>" class="input-sm form-control material_josh search-input-select2 searchDateFrom" name="end" readonly/>
</div>
</div>
<div class="divname" id="divname" style="display: none;">
<label class="form-control-label col-form-label-sm">Name</label>
<input type="text" class="input-sm form-control material_josh search-input-text search_name" id="search_name" placeholder="Name.." onkeypress="return (event)" />
</div>
<div class="divstatus" id="divstatus" style="display: none;">
<label class="form-control-label col-form-label-sm">Status</label>
<select id="search_status" class="form-control fr_status" >
<option value="<?php foreach ($get_stat->result() as $gdept) { ?>" ></option>
<option value="<?=$gdept->fr_status_name?>"><?=$gdept->fr_status_name?></option>
<?php } ?>
</select>
</div>
</div>
</div>
<div class="col-lg col-6" style="padding-left: 0">
<div class="pull-right">
<label class="form-control-label col-form-label-sm "></label>
<button type="submit" id="search_order" class="btn blue-grey search_order">Search</button>
<button type="button" data-target="#addFRModal" class="btn btn-primary addsupp"> Add New Room Reservation</button>
</div>
</div>
</div>
js
$(function(){
var base_url = $("body").data('base_url'); //base_url come from php functions base_url();
var token = $("#token").val();
var d = new Date();
var date = d.getFullYear() + "/" + (d.getMonth()+1) + "/" + d.getDate();
var searchDateTo = $("#searchDateTo").val();
function fillDatatable(name, status, searchtype, datefrom, dateto) {
var dataTable = $('#table-grid').DataTable({
destroy : true,
"bDeferRender": true,
"order": [[ 1, "desc" ]],
"serverSide": true,
"columnDefs": [
{ "targets": 1,
"createdCell": function (td, cellData, rowData) {
if (cellData == "Approved"){
$(td).css('background-color', '#DFF0D0')
}else if (cellData == "Disapprove"){
$(td).css('background-color', '#F5DBD9')
}else if (cellData == "Pending"){
$(td).css('background-color', '#FEECB5')
}else if (cellData == "Cancel"){
$(td).css('background-color', '#CFCFC4')
}else if (cellData == "New"){
$(td).css('background-color', '#DAF0F7')
}
}
}],
"ajax":{
url:base_url+"Main_facility/facility_reservation_view", // json datasource
type: "post", // method , by default get
data: { 'name':name, 'status':status, 'searchtype':searchtype, 'datefrom':datefrom, 'dateto':dateto },
beforeSend:function(data) {
$.LoadingOverlay("show");
},
complete: function() {
$.LoadingOverlay("hide");
},
error: function(){ // error handling
$(".table-grid-error").html("");
$("#table-grid").append('<tbody class="table-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
$("#table-grid_processing").css("display","none");
}
}
});
}
function toastMessage(heading, text, icon, color) {
$.toast({
heading: heading,
text: text,
icon: icon,
loader: false,
stack: false,
position: 'top-center',
allowToastClose: false,
bgColor: color,
textColor: 'white'
});
}
fillDatatable('divdate', searchDateTo, date, "");
// $(".searchBtn").on("click", function(){
// name = $(".searchName").val();
// status = $(".searchStat").val();
// fillDatatable(name, status);
// });
$("#sosearchfilter").change(function() {
var searchtype = $('#sosearchfilter').val(); // id ng dropdown
var currentdate = new Date();
var dateto = $('#searchDateTo').val();
var datefrom = $('#searchDateFrom').val();
if(searchtype == "divdate") {
$('.divdate').show('slow');
$('.divname').hide('slow');
$('.divstatus').hide('slow');
$(".search_name").val("");
$(".search_status").val("");
$(".searchDateTo").val($.datepicker.formatDate('mm/dd/yy', dateto));
$(".searchDateFrom").val($.datepicker.formatDate('mm/dd/yy', datefrom));
}
if(searchtype == "divname") {
$('.divdate').hide('slow');
$('.divname').show('slow');
$('.divstatus').hide('slow');
$(".search_name").val("");
$(".search_status").val("");
$(".searchDateTo").val("");
$(".searchDateFrom").val("");
}
if(searchtype == "divstatus"){
$('.divdate').hide('slow');
$('.divname').hide('slow');
$('.divstatus').show('slow');
$(".search_name").val("");
$(".search_status").val("");
$(".searchDateTo").val("");
$(".searchDateFrom").val("");
}
});
$("#search_order").click(function() {
searchtype = $('#sosearchfilter').val();
datefrom = formatDate($("#datefrom").val());
dateto = formatDate($("#dateto").val());
name = $('#search_name').val();
status = $('#search_status').val();
checker = 0;
if (searchtype == "divdate") {
if (datefrom == "" || dateto == "") {
toastMessage('Note', 'Please fill in the Date fields.', 'info', '#FFA500');
checker = 0;
}
else {
checker = 1;
}
}else if (searchtype == "divname") {
if (name == "") {
toastMessage('Note', 'Please fill in the Name.', 'info', '#FFA500');
checker = 0;
}
else {
checker = 1;
}
}else if (searchtype == "divstatus") {
if (status == "") {
toastMessage('Note', 'Please fill in the Status Field.', 'info', '#FFA500');
checker = 0;
}
else {
checker = 1;
}
}
if (checker == 1) {
fillDatatable(searchtype, datefrom, dateto, name, status);
}
});
Expecting to get the right code so I can fetch the data I wanted to search
Here's my MVC coding and wanted to show you all so you can answer me clearly been stuck here for a while and would be happy if someone could help me.

How to retrieve old text and subtract from total - JS

This is a follow up question on an existing question. I am able to get total sub-price tof products that i selected and add up to get the grand total. Now, when an item is deselected, i want to subtract the price of the item being deselected from the existing grand total?
How do i get that done please?
When i try to get the oldtext, it is always 0 .. why is this happening?
HTML
<div class="panel" id="panel">
<div>
<div >
<p> class="mygoods" >Total: <span ></span></p>
</div>
JS
<script type="text/javascript">
function order(food)
{
var ad = JSON.parse(food.dataset.food);
if(food.checked == true) {
$('.panel').append(
'<div class="container" style=" font-size:14px; "> '+
'<p class="total" ><span class="sub-total" name="total" id="total"></span></p>'+
'<input size="50" type="text" class="form-control quantity" id="qty" placeholder=" qty " name="quantity[]" required/>'+
'</div>'
)
}
else{
var total = $(".panel .container [data-id=" + ad.id + "]").parent().find(".total").text();
$(".panel .container [data-id=" + ad.id + "]").parent().remove();
if (total) {
$('.mygoods span').text(function(oldtext) {
console.log('this is my old text '+oldtext)
return oldtext ? oldtext - total : oldtext;
});
}
}
}
$('.panel').on('keyup','.quantity',function()
{
var sum;
container = $(this).closest('div');
quantity = Number($(this).val());
price = Number($(this).closest('div').find('.price').data('price'));
container.find(".total span").text(quantity * price);
sum = 0;
$(".sub-total").each(function(){
sum = sum + Number($(this).text());
})
$('.mygoods span').text(sum);
});
</script>
$( '.mygoods span' ).text( function( oldtext ) {
console.log( 'this is my old text ' + oldtext )
return oldtext ? oldtext - total : oldtext;
} );
the .text method returns the parameters index and text - you only are retrieving one. Therefore the index is being stored in the oldtext variable, not the text.
Type: Function( Integer index, String text ) => String A function
returning the text content to set. Receives the index position of the
element in the set and the old text value as arguments.
http://api.jquery.com/text/
You can fix this by simply adding another parameter.
$( '.mygoods span' ).text( function(index, oldtext ) {
console.log( 'this is my old text ' + oldtext )
return oldtext ? oldtext - total : oldtext;
} );
I tried copying a snippet over to show you, but the code you provided is not enough to build anything. The attempted build is below.
function order( food ) {
var ad = JSON.parse( food.dataset.food );
if ( food.checked == true ) {
$( '.panel' ).append( '<div class="container" style=" font-size:14px; "> ' +
'<p class="total" ><span class="sub-total" name="total" id="total"></span></p>' +
'<input size="50" type="text" class="form-control quantity" id="qty" placeholder=" qty " name="quantity[]" required/>' +
'</div>' )
} else {
var total = $( ".panel .container [data-id=" + ad.id + "]" ).parent().find(
".total" ).text();
$( ".panel .container [data-id=" + ad.id + "]" ).parent().remove();
if ( total ) {
$( '.mygoods span' ).text( function( index, oldtext ) {
console.log( 'this is my old text ' + oldtext )
return oldtext ? oldtext - total : oldtext;
} );
}
}
}
$( '.panel' ).on( 'keyup', '.quantity', function() {
var sum;
container = $( this ).closest( 'div' );
quantity = Number( $( this ).val() );
price = Number( $( this ).closest( 'div' ).find( '.price' ).data( 'price' ) );
container.find( ".total span" ).text( quantity * price );
sum = 0;
$( ".sub-total" ).each( function() {
sum = sum + Number( $( this ).text() );
} )
$( '.mygoods span' ).text( sum );
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel" id="panel">
<div>
<div>
<p class="mygoods"> Total: <span></span></p>
</div>
</div>
</div>

Update SQL Server Database On Table Edit/Change

I have a dynamic HTML table that can be edited in multiple ways. There is an edit button where you can edit inline, the information of the rows and then click save to save the information. A deactivate button that grays out the row and an activate button that appears afterwards in order to reactivate it. And also and add row button that brings up a dialog box where you can hit add row again and add another row to the table.
However, while that is all nice...I want to write these changes/updates to a SQL Server database now so it actually saves them. I want to be able to automatically save these changes after each action (save, deactivate/activate, and add row) happens. I have never done this before so any help/advice/code would be appreciated!
JavaScript code:
// ----- Deactivate/Activate Row -----
$(document).on("click", "#html_master .deactivate", function () {
var $this = $(this);
var $tr = $this.closest('tr');
var action = $tr.hasClass('deactivated') ? 'activate' : 'deactivate';
// ------ Confirmation box in order to deactivate/activate row -----
if (confirm('Are you sure you want to ' + action + ' this entry?')) {
$tr.toggleClass('deactivated');
$this.val(function (i, t) {
return t == 'Deactivate' ? 'Activate' : 'Deactivate';
});
}
});
// ----- Edit Row -----
$(document).on("click", "#html_master .edit", function () {
var $this = $(this);
var tds = $this.closest('tr').find('td').not('.mr_id').filter(function () {
return $(this).find('.edit').length === 0;
});
if ($this.val() === 'Edit') {
$this.val('Save');
tds.prop('contenteditable', true);
} else {
var isValid = true;
var errors = '';
$('#myDialogBox').empty();
// changed from here.......
var elements = tds;
if (tds.find('input').length > 0) {
elements = tds.find('input');
}
elements.each(function (index, element) {
var type = $(this).attr('class');
var value = (element.tagName == 'INPUT') ? $(this).val() : $(this).text();
// changed from here....... to here
// ----- Switch statement that provides validation -----
switch (type) {
case "buyer_id":
if (!$.isNumeric(value)) {
isValid = false;
errors += "Please enter a valid Buyer ID\n";
}
break;
case "poc_n":
if (value == value.match(/^[a-zA-Z\s]+$/)) {
break;
}
else {
isValid = false;
errors += "Please enter a valid Name\n";
}
break;
case "poc_e":
if (value == value.match(/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/)) {
break;
}
else {
isValid = false;
errors += "Please enter a valid Email\n";
}
break;
case "poc_p":
if (value == value.match('^[0-9 ()+/-]{10,}$')) {
break;
}
else {
isValid = false;
errors += "Please enter a valid Phone Number\n";
}
break;
}
})
if (isValid) {
$this.val('Edit');
tds.prop('contenteditable', false);
} else {
alert(errors);
}
}
});
// ----- Dialog Box -----
$( function() {
var dialog, form,
emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,
phoneRegex = /^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/,
mr_name = $( "#mr_name" ),
buyer_id = $( "#buyer_id" ),
poc_n = $( "#poc_n" ),
poc_e = $( "#poc_e" ),
poc_p = $( "#poc_p" ),
allFields = $( [] ).add( mr_name ).add( buyer_id ).add( poc_n ).add( poc_e ).add( poc_p ),
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" );
valid = valid && checkRegexp( mr_name, /^[a-z]([0-9a-z_\s])+$/i, "Please enter a valid vendor name" );
valid = valid && checkRegexp( buyer_id, /^(0|[1-9][0-9]*)$/, "Please enter a valid Buyer ID" );
valid = valid && checkRegexp( poc_n, /^[a-zA-Z ]*$/, "Please enter a valid name" );
valid = valid && checkRegexp( poc_e, emailRegex, "Please enter a valid email" );
valid = valid && checkRegexp( poc_p, phoneRegex, "Please enter a valid phone number" );
if ( valid ) {
var $tr = $( "#html_master tbody tr" ).eq(0).clone();
$.each(allFields, function(){
$tr.find('.' + $(this).attr('id')).html( $(this).val() );
});
$tr.find('.mr_id').html( $( "#html_master tbody tr" ).length + 1 );
$( "#html_master tbody" ).append($tr);
/*
$( "#html_master tbody" ).append( "<tr>" +
"<td>" + mr_name.val() + "</td>" +
"<td>" + buyer_id.val() + "</td>" +
"<td>" + poc_n.val() + "</td>" +
"<td>" + poc_e.val() + "</td>" +
"<td>" + poc_p.val() + "</td>" +
"</tr>" );
*/
dialog.dialog( "close" );
}
return valid;
}
var dialog = $( "#dialog-form" ).dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Add Row": 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();
});
$( ".create-user" ).button().on( "click", function() {
dialog.dialog( "open" );
});
} );
HTML/PHP code:
<?php
$host="xxxxxxxxx";
$dbName="xxxxx";
$dbUser="xxxxxxxxxxx";
$dbPass="xxxxxx";
$dbh = new PDO( "sqlsrv:server=".$host."; Database=".$dbName, $dbUser, $dbPass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM Stage_Rebate_Master ORDER BY MR_ID ASC";
?>
<html>
<body>
<div id="dialog-form" title="Add Vendor">
<p class="validateTips">All form fields are required.</p>
<form>
<fieldset>
<label for="mr_name">Vendor</label>
<input type="text" name="mr_name" id="mr_name" class="text ui-widget-content ui-corner-all">
<label for="buyer_id">Buyer ID</label>
<input type="text" name="buyer_id" id="buyer_id" class="text ui-widget-content ui-corner-all">
<label for="poc_n">POC Name</label>
<input type="text" name="poc_n" id="poc_n" class="text ui-widget-content ui-corner-all">
<label for="poc_p">POC Email</label>
<input type="text" name="poc_e" id="poc_e" class="text ui-widget-content ui-corner-all">
<label for="poc_p">POC Phone</label>
<input type="text" name="poc_p" id="poc_p" class="text ui-widget-content ui-corner-all">
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
Without Ajax - This can be done with a (PHP/ASP) 'pass-through' window.open - this is a window that you open which processes the passed parameters and writes them to an SQL database and then closes itself. This leaves the original site intact but updates the database with your changes.
So, window.open(saveChanges.php?param1=..&param2=..&etc,....)
The saveChanges.php file should read in the passed params and run the appropriate SQL to save updates.
Once completed, the saveChanges.php file should close itself with window.close()
Your database should now reflect the contents of your web page entries.

javascript Alert to confirm if value entered twice

I have a form:
// 10 times
<input type="text" name="cityname" class="autocompletecity">
<input type="text" name="cityID" class="autocompletecityID">
When I enter the city name, it autocompletes the city name and the cityID from database with this code:
<?php for ($i = 0; $i < 10; $i++) { /*in the field class add $i */ ?>
$(function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 1 );
}
$( ".autocompletecity<?php echo $i ?>" ).autocomplete({
source: "/*path to json*/",
select: function( event, ui ) {
var item = ui.item;
if(item) {
$(".autocompletecityID<?php echo $i ?>").val(item.cityID);
$(this).val(item.value +' ' + item.country);
return false;
}
}
//code from J.D.
select: function( event, ui ) {
var item = ui.item;
if(item) {
$('input[name="cityID"]').each(function(index, element) {
var $element = $(element);
if ($element.value() == item.cityID) {
alert('This city has already been selected');
}
});
}
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" +item.value + " " +item.country + "</a>" )
.appendTo( ul );
};
});
<?php } ?>
After it autocompletes the cityID, I would like to show an alert box if same cityID has alredy been entered: Click OK to confirm or Cancel to clear the cityname and cityID with repeated entry.
I tried to search in the jqueryui, but no luck...
Thanks!!
Try this:
select: function( event, ui ) {
var item = ui.item;
if(item) {
$('input[name="cityID"]').each(function(index) {
var $element = $(this);
if ($element.value() == item.cityID) {
alert('This city has already been selected');
}
});
}
}

How to get onblur input id or tabIndex from a cfinput via JavaScript or jQuery?

I have a ColdFusion cfform containing:
<cfinput type="text" name="part1" id="part1" tabIndex="1" onblur="enabled()" >
<cfinput type="text" name="part2" id="part2" tabIndex="2" onblur="enabled()" disabled="disabled" >
<cfinput type="text" name="part3" id="part3" tabIndex="3" onblur="enabled()" disabled="disabled" >
What I want is let input box disabled unless its previous one is not empty, so I done this:
function enabled()
{
var curIndex = + ( $( " * : focus " ).attr( " tabIndex " ) );
var curVal = $( ' * : input [ tabIndex=' + curIndex + ' ] ' ).val();
var nextIndex = curIndex + 1;
var nextId = $( ' input [ tabIndex = " ' + nextIndex + ' " ] ' ).attr( " id " );
if ( curVal == "" )
{
nextId.setAttribute( ' disabled ', ' disabled ' );
}
else
{
nextId.removeAttribute( ' disabled ' );
nextId.focus();
}
}
But I stuck with getting curIndex, it appeared " undefined " when I alerted it.
Any suggestion is appreciated.
What about:
​$('input[type=text][name^=part]').on('blur',function(){​​​​​​​​​​​
var el = $(this);
var elNext = el.next('input[type=text][name^=part]');
if(el.val()!=''){
elNext.removeAttr('disabled');
}else{
elNext.attr('disabled',true);
}
});
So you don't need the handlers on inputs:
<cfinput type="text" name="part1" id="part1" tabIndex="1" >
<cfinput type="text" name="part2" id="part2" tabIndex="2" disabled="disabled" >
<cfinput type="text" name="part3" id="part3" tabIndex="3" disabled="disabled" >
​Demo

Categories

Resources