I have a AJAX Web Serice that runs an SQL statment, which works.
I am trying to take an HTML value from my web page and use it as an additional variable in my query.
Here is how I am capturing that variable on my web page.
<div style="margin-left:0px">
<label>Enter Number here: </label><br>
<input type= text id="demo">
</div>
...and this is my Web Service call.
//Generate code
function Generate() {
var myGrid = $('#jqquotes'),
selectedRowId = myGrid.jqGrid('getGridParam', 'selrow');
docid = myGrid.jqGrid('getCell', selectedRowId, 'docid');
document.getElementById("demo").innerHTML = document.getElementById("demo").value;
alert(document.getElementById("demo").value);
var quotenum = document.getElementById("demo".value);
if (confirm('Are you sure you want to generate a quote?')) {
$.ajax({
url: '/WebService1.asmx/Generate',
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "GET",
data: { docid: docid, quotenum: JSON.stringify(quotenum) },
success: function () {
//Get selected
var grid = $("#jqquotes");
var rowKey = grid.jqGrid('getGridParam', "selrow");
//Refresh grid
$('#jqquotes').trigger('reloadGrid');
//Set Selected
setTimeout(function () {
jQuery('#jqquotes').jqGrid('setSelection', rowKey);
}, 200);
}
});
} else {
return false
}
}
The alert box correct displays the HTML value from the box id "Demo"
But the WebService fails, saying the value is NULL, JSON reponse is:
Message "The parameterized query '(#docid nvarchar(5),#quotenum nvarchar(4000))UPDATE [dbo].[quote' expects the parameter '#quotenum', which was not supplied."
...and the GET URL shows the value as NULL
https://localhost:44338/WebService1.asmx/Generate?docid=10146"enum=null
Any help greatly appreciated.
I think the problem is here:
var quotenum = document.getElementById("demo".value);
This should be
var quotenum = document.getElementById("demo").value;
as in the line above it.
Related
I have a hidden input field in page "A". Whom value I am populating dynamically as there are 100+ values. The value changes when different element is clicked.
I want the set value in a different page "B". I am using the simple method of getting value by id but the output cames undefined.
Here is some code:
Input Field: <input type="hidden" id="sel_s_n" value="" name="sel_s_n">
Populating on element click:
jQuery('.shades-popup').click(function () {
jQuery('#myModaldcm .modal-body').css('display', 'none');
title = $(this).data('dcmtitle');
$("#sel_s_n").val(title);
var rgb = $(this).data('dcmrgb');
var img = $(this).data('dcmimg');
var pro_tit = $(this).data('dcmpt');
var pro_id = $(this).data('pid');
jQuery('.dcmptitle').html(title);
jQuery('.csdcmp').css('background', 'rgb(' + rgb + ')');
jQuery('.cdmpi').attr('src', img);
jQuery.ajax({
type: "post",
dataType: "json",
url: dcmAjax.dcmajaxurl,
data: { action: "get_dcm_products", post_id: pro_id },
success: function (response) {
if (response.type == "success") {
jQuery("#dcmselextt").html(response.data);
jQuery('#myModaldcm .modal-body').css('display', 'block');
}
else {
alert("Network Error! Try Again")
}
console.log(response);
}
})
});
$("#sel_s_n").val(title); --> This line add the value.
On the second page "B" I am getting it like alert( $("#sel_s_n").val() );
Can somebody point out what I am doing wrong.
Thanks
I am using MVC.
I am having two drop down and one change of 'primaryspec' the 'primarysubspec' should get loaded.
Everything is working fine for passing values to controller and it got saved to DB.
When I am trying to retrieve the saved details,'primarysubspec' saved values are not getting displayed.
But displaying save data for 'primarySpec'.
Here is my .cshtml code:
#Html.DropDownListFor(m => m.PSpec, Model.PSpec, new { id = "ddUserSpec", style = "width:245px;height:25px;", data_bind = "event: {change: primaryChanged}" }, Model.IsReadOnly)
#Html.DropDownListFor(m => m.PSubspec, Model.PSubspec, new { id = "ddUserSubSpec", style = "width:245px;height:25px;", data_bind = "options: primarySubSpec,optionsText: 'Name',optionsValue: 'Id'" }, Model.IsReadOnly)
Here is my JS Code to retrieve the values for :
this.primarySubSpec = ko.observableArray([]);
this.primarySpecChanged = function () {
var val = $("#ddetailsPrimarySpec").val();
primarySubStartIndex = 0;
primarySubSpecialityUrl = '/PlatformUser/GetSpecandSubSpec?primarySpe=' + val+//model.primarySpecID() +'&secondarySpec=';
loadPrimarySubSpec();
};
function loadPrimarySubSpec() {
$.ajax({
type: 'GET',
url: primarySubSpecUrl,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
processdata: false,
cache: false,
success: function (data) {
primarySubSpec = [];
model.primarySubspec('0');
try {
if (data.length == 0) {
primarySubSpeacId.empty();
}
model.primarySubSpec(data);
},
error: function (request, status, error) {
primarySubSpeacId.prop("disabled", true);
}
});
}
Everything is working fine,but facing issue only while displaying the saved values from the DB.
Showing fine for 'primarySpec'
The values showing empty for 'PrimarySubSpec' instead of saved values in dropdown.
Please let me know what is the issue how can i show the saved value as selected value in 'primarySubSpec'dropdown.
The Problem:
when you load the page to view saved values, the change event is never called.
Why:
When your page is loaded with saved values, the select box has the saved value selected before knockout knows anything about it. Hens the change event isn't called.
Simplest solution:
change the primarySpecilaityChanged as follows
this.primarySpecilaityChanged = function () {
var val = $("#ddUserDetailsPrimarySpeciality").val();
if(val){
primarySubStartIndex = 0;
primarySubSpecialityUrl = '/' + NMCApp.getVirtualDirectoryName() + '/PlatformUser/GetSpecialitiesandSubSpecilaities?primarySpeciality=' + val+//model.primarySpecialityUID() +'&secondarySpeciality=';
loadPrimarySubSpecilaities();
}
};
then call primarySpecilaityChanged function after you call ko.applyBindings.
var viewModel = new YourViewModel();
ko.applyBindings(viewModel);
viewModel.primarySpecilaityChanged();
I have a website where the log ins are screen names. On the create user form I want to be able to have ajax check if a screen name exists already as it is typed into the form.
This is the HTML form input field
<label for="screenName">Screen Name:
<input type="text" class="form-control" name="screenName" id="screenName" size="28" required>
<div class="screenNameError"></div>
A message should be displayed in the <div class="screenNameError"></div>line if the username matches the database.
This is my Jquery code for this.
$(document).ready(function(){
if ($('#screenName').length > 0){
var screenName = $("input").keyup(function(){
var value = $(this).val();
return value;
})
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + screenName,
success: function (r) {
$('.screenNameError').html(r);
}
})
}
});
This is the PHP file that gets called to make the DB query
$screenName = $_POST['Screen_Name'];
$screenNameSQL = "SELECT Screen_Name FROM Users WHERE Screen_Name = '$screenName'";
$result = $my_dbhandle->query($screenNameSQL); //Query database
$numResults = $result->num_rows; //Count number of results
$resultCount = intval($numResults);
if($resultCount > 0){
echo "The username entered already exists. Please a different user name.";
}
For some reason my Jquery is not firing when I type the username in the form :/
Thanks in advance
Try changing your jQuery to this -
$(document).ready(function() {
$('#screenName').keyup(function() {
var value = $(this).val();
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + value,
success: function(r) {
$('.screenNameError').html(r);
}
});
});
});
However you probably want to minimise the number of ajax requests being made so I would advise putting your ajax request into a setTimeout functon and clearing it with each subsequent keypress. -
$(document).ready(function() {
var ajaxRequest;
$('#screenName').keyup(function() {
var value = $(this).val();
clearTimeout(ajaxRequest);
ajaxRequest = setTimeout(function(sn) {
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + value,
success: function(r) {
$('.screenNameError').html(r);
}
});
}, 500, value);
});
});
if ($('#screenName').length > 0){
You should change it with
if ($('#screenName').val().length > 0){
OR
var name = $('#screenName').val();
if(name.length >0) {...
not sure about the syntax...
Add an event on keyup like this :
Edit
$("#screenName").on("keyup",function(){
var screenName=$(this).val();
if(screenName!='')
{
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + screenName,
success: function (r) {
$('.screenNameError').html(r);
}
})
}
});
JsFiddle
Your ajax call should be inside the keyup handler.
On page load for my current project, I have a modal overlay appear that prompts the user to enter a 5 digit long value. From that value, I want to have an AJAX call hit an API to see if that value exists/matches and from there, update the nav bar to say, "Hello, [user]" ([user] being another key value pair from the JSON object that the 5 digit long value is referencing. I'm still new to AJAX, so I'm wondering what the best way to go about doing this. I know the following is completely wrong, but I imagine this is the basic framework for starting out something like this.
$("#inputForm").submit(function(){
$.ajax({
url: "/my/api/url/",
type: "POST",
data: postData
success: function(postData){
//if 5-digit value matches value in the API, update the navbar with name key value pair in the JSON object
}
});
});
Try utilizing change event prompt
$(function() {
var check = function(vals, data) {
if (vals.length === 5 && vals.split("").every(Number)) {
if (vals in data) {
// do `$.ajax()` stuff here
/*
$.ajax({
url: "/my/api/url/",
type: "POST",
data: vals
success: function(returnData) {
var data = JSON.parse(returnData);
// check data and update nav bar
$("#navbar").html("Hi, " + data)
}
error: function() {
evt.preventDefault();
// show error
}
});
*/
$("#navbar").html("Hi, " + data[vals])
}
}
};
var data = {
12345: "abc"
};
var vals = prompt("enter 5 digits");
if (vals !== null) check(vals, data);
$("input").change(function(e) {
check(this.value, data)
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="navbar"></div>
<input type="text" placeholder="enter 12345" />
$("#inputForm").submit(function(evt){
$.ajax({
url: "/my/api/url/",
type: "POST",
data: postData
success: function(returnData){
var data = JSON.parse(returnData);
// check data and update nav bar
}
error: function() {
evt.preventDefault();
// show error
}
});
});
I want the drop down options to reflect all the items in an array stored in a file called companyinfo.js, which i request via ajax. I call the dropDownList() when the page loads.
function dropDownList (evt) {
console.log("dropdownfired");
var companyArray = [];
$.ajax({
url : 'assets/data/companyarray.js', //this file is just ["Facbeook", "Twitter", "Klout",]
dataType: 'script',
success: function(data) {
companyArray = data;
console.log(companyArray); //returns an array of the companies
$('#companyInput1').attr('data-source', companyArray); //#companyInput1 is the input field where I want the typehead to be
console.log($('#companyInput1').attr('data-source')); //returns undefined
}
});
}
UPDATES:
function dropDownList (evt) {
console.log("dropdownfired");
var companyArray = [];
$.ajax({
url : 'assets/data/companyarray.js', //this file is just ["Facbeook", "Twitter", "Klout",]
dataType: 'script',
success: function(data) {
companyArray = data;
console.log(companyArray); // gives array of companies
$('#companyInput1').data('data-source', companyArray);
console.log($('#companyInput1').data('data-source')); // gives undefined still
}
});
}
You should not store anything besides strings as attributes on HTML nodes. For storing an array use the .data()-method jquery offers
success: function(data) {
companyArray = data;
console.log(companyArray); //returns an array of the companies
$('#companyInput1').data('data-source', companyArray); //#companyInput1 is the input field where I want the typehead to be
console.log($('#companyInput1').data('data-source')); //should work
}