I'm looking for help about this subject.
I've got in my view 2 textbox.
I would like to get a value (generated in my controller) applied to textbox2 when there is an change on the textbox1.
For example I enter an username in textbox1 and textbox2 is the email address getting from controller (we can imagine that the controller check in a database or an active directory).
My code below seems not working:
In my View file I added an script section :
#section scripts{
<script type="text/javascript" language="javascript">
function ShowPersonalPanel(myChkboxPersonalLine) {
if (myChkboxPersonalLine.checked == false) {
$("#1-w").hide("fast");
}
else {
$("#1-w").show("fast");
}
}
</script>
<script language="javascript">
$("#1-w").hide("fast");
$('#myOtherGID').change(function () {
var myOtherGID = this.value;
$.getJSON("/PhoneController/GetEmailByGID",
{
strGID: myOtherGID
},
function (data) {
$('myOtherEmail').val(data);
});
});
</script>
}
And the code in the view with textbox:
<label for="myOtherGIDlbl">GID:</label>
<label class="text" id="myOtherGIDlbl">
#Html.TextBoxFor(model => model.myOtherGID)
</label>
<label for="myOtherEmaillbl">Email:</label>
<label class="text" id="myOtherEmaillbl">
#Html.TextBoxFor(model => model.myOtherEmail)
</label>
On my controller (named PhoneController) I added an action:
public JsonResult GetEmailByGID(string strGID)
{
string strEmailAddress = "this is my email";
return Json(strEmailAddress, JsonRequestBehavior.AllowGet);
}
As I work with an _layout.cshtml and an viewFile.cshtml, I added in the layout (in the head section) the line below:
<script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
What did I miss?
Regards
I've found my issue.
I've changed my javascript to make an $.ajax command:
script type="text/javascript">
$('#myOtherGID').change(function () {
var selection = $('#myOtherGID').val();
if (selection.length > 0) {
var url = "/Phone/GetEmailByGID";
$.ajax({
type: "POST",
url: '#Url.Action("GetEmailByGID", "Phone")',
dataType: "json",
success: function(data, status) {
alert(data);
},
error: function() {
alert('error');
}
});
}
});
</script>
In the controller :
[HttpPost]
public ActionResult GetEmailByGID(string strGID)
{
string strEmailAddress = strEmailByGID(strGID);
return Json(strEmailAddress);
}
After testing, I can retrive data from my controler to my View without reloading all page.
Related
Dropdown selection change is not firing when the function contain ajax call. if the function contains only an alert, the function works.
Here is the code:
<div class="col-md-6">
<div class="form-group">
<label>Select Category</label>
#Html.DropDownListFor(x => x.CategoryId, new SelectList(Model.Categories, "CategoryId", "CategoryName", Model.CategoryId),
new { #class = "form-control select2", id = "myCategories" })
</div>
<div class="form-group" id="makes">
</div>
</div>
Here is the js function
#section scripts{
<script type="text/javascript">
$(document).ready(function () {
$(document.body).on('change', "#myCategories", function (event) {
var selected = $('#myCategories').val();
alert("catid changed to : " + selected);
$.ajax({
url : #Url.Action("getMakes","Transaction", new {categoryId= Model.CategoryId}),
success: function (data) {
alert(data);
$('#makes').html = data;
},
error: function () {
alert("failed");
}
});
});
});
</script>
}
If I comment the ajax block, it works and shows the alert. Anyone know why it is behaving like this?
Thanks to all those who helped me to fix this problem even though it is Christmas. Finally i got it working by putting single inverted comma before and after the url part in the ajax. Thanks #AnilTalla for the console clue. Here is the updated js
$(document).ready(function () {
$(document.body).on('change', "#myCategories", function (event) {
var selected = $('#myCategories').val();
alert("catid changed to : " + selected);
$.ajax({
url : '#Url.Action("getMakes","Transaction", new {categoryId= Model.CategoryId})',
success: function (data) {
alert(data);
$('#makes').html = data;
},
error: function () {
alert("failed");
}
});
});
});
Merry Christmas everyone.
I have this search bar inside navigation file and it's an enter submit input tag.
I include this file in many pages. but when I enter(submit) it doesn't go to searchResults.blade.php
MY HTML
<input class="searchkey" id="searchkey" type="search" required onkeydown="search(this)">
My JS
$('.searchkey').keydown(function(event) {
var getKeyword = document.getElementById("searchkey").value;
if (event.keyCode == 13) {
$.ajax({
url: "search",
type: "POST",
data:{
getKeyword : getKeyword
},
success: function() {}
});
}
});
MY CONTROLLER
public function multiSearch()
{
$searchKey = Input::get('getKeyword');
$getResults = array();
$getResults = DB::select("SELECT title FROM books WHERE title LIKE '%$searchKey%'");
return View::make('content.searchResults',array('getResults'=>$getResults));
}
MY ROUTES
Route::post('search', 'UserController#multiSearch');
First of all in your ajax callback you should put the view results in some container on the page, i.e.: <div id="search-result"></div> by adding this callback function:
success: function(data) {
$('#search-reasult').html(data);
}
You also have to render the view in your controller like this:
return View::make('content.searchResults',array('getResults'=>$getResults))
->render();
I try to use CKEDITOR to edit my website content. But there are a lot of CKEDITOR used, I put all the javascript functions in a Class, but not sure how it works. Anybody could help to see which part i need to change?
There are 2 files associated with my problems:
1) test.php (main page for update the content of website using Ckeditor)
2) CmsAjaxClass.js (Class contains all operation of Ajax and Ckeditor)
test.php
<!DOCTYPE html>
<html>
<head>
<title>A Simple Page with CKEditor</title>
<!-- Make sure the path to CKEditor is correct. -->
<script src="ckeditor/ckeditor.js"></script>
</head>
<script src="assets/js/jquery.js" type="text/javascript"></script>
<body>
<div>
</div>
<form method="post" action="test2.php">
<h1>Editor1</h1>
<textarea name="editor1" id="editor1"><?php
include_once('php/get_cms.php');
echo get_cms(1);
?></textarea>
_____________________________________<br/>
<h1>Editor2</h1>
<textarea name="editor2" id="editor2"><?php
include_once('php/get_cms.php');
echo get_cms(2);
?></textarea>
<script src="assets/js/CmsAjaxClass.js"></script>
<script>
var editor1 = new CmsAjaxClass("editor1", document.getElementById("editor1").value) ;
var editor2 = new CmsAjaxClass("editor2", document.getElementById("editor2").value) ;
</script>
</form>
</body>
</html>
CmsAjaxClass.js
function CmsAjaxClass(editorName, seteditorData)
{
//For nested Class usage
var myClass = this;
//Declare editorName to keep the editor name
this.editorName = editorName;
//Declare dataString to keep the data retrieve from editor
this.seteditorData = seteditorData;
//Function to update the CKEDITOR before it is parsed
this.updateCkeditor = function() {
for ( instance in CKEDITOR.instances )
{
CKEDITOR.instances[instance].updateElement();
}
}
//Function to run the AJAX if the element is blured
this.onBlur = function() {
//Update the Ckeditor data first before retrieve edited data
myClass.updateCkeditor();
//Retrieve edited data from HTML DOM
myClass.seteditorData = seteditorData;
//Call AJAX function to pass the value
myClass.startAjax();
}
//Catch the focus and blur status of inline toolbar
this.editor = CKEDITOR.inline( editorName, {
on: {
//focus: onFocus,
blur: myClass.onBlur,
}
});
//Declare which cms section we currently editing, parse the integer from the id of the textarea
this.setcmsID = parseInt(editorName.replace("editor",""));
//Create an AJAX function
this.startAjax = function() {
alert(this.seteditorData);
$.ajax
({
type: "POST",
url: "test2.php",
data: {editorData: this.seteditorData, cmsID: this.setcmsID},
cache: false,
beforeSend: function()
{
//Loading
},
success: function(result)
{
alert("Successfully updated!");
}
});
}
}
I dont understand your issue clearly.
But still these lines looks like a typo
<script>
var editor1 = new CmsAjaxClass("editor1") ;
var editor1 = new CmsAjaxClass("editor2") ;
</script>
I guess you meant editor2 in second line instead of overwriting editor1
this.onFocus() = function() {
//The CKEDITOR element is focused
}
I guess you want this.onFocus= function(){
You can keep a reference to the editor in your class
this.editor = CKEDITOR.inline( editorName, {
on: {
blur: this.onBlur,
}
});
which can facilitate
this.editor.on('blur', function(){});
this.editor.updateElement();
Thanks #sabithpocker and #DaniƫlKnippers
Finally it works, the Ckeditor update database when "blur" action is triggered.
test.php
<!DOCTYPE html>
<html>
<head>
<title>A Simple Page with CKEditor</title>
<!-- Make sure the path to CKEditor is correct. -->
<script src="ckeditor/ckeditor.js"></script>
</head>
<script src="assets/js/jquery.js" type="text/javascript"></script>
<body>
<div>
</div>
<form method="post" action="test2.php">
<h1>Editor1</h1>
<textarea name="editor1" id="editor1"><?php
include_once('php/get_cms.php');
echo get_cms(1);
?></textarea>
_____________________________________<br/>
<h1>Editor2</h1>
<textarea name="editor2" id="editor2"><?php
include_once('php/get_cms.php');
echo get_cms(2);
?></textarea>
<script src="assets/js/CmsAjaxClass.js"></script>
<script>
var editor1 = new CmsAjaxClass("editor1") ;
var editor2 = new CmsAjaxClass("editor2") ;
</script>
</form>
</body>
</html>
CmsAjaxClass.js
function CmsAjaxClass(editorName)
{
//For nested Class usage
var myClass = this;
//Declare editorName to keep the editor name
this.editorName = editorName;
//Declare dataString to keep the data retrieve from editor
this.seteditorData;
//Function to update the CKEDITOR before it is parsed
this.updateCkeditor = function() {
for ( instance in CKEDITOR.instances )
{
CKEDITOR.instances[instance].updateElement();
}
}
//Function to run the AJAX if the element is blured
this.onBlur = function() {
//Update the Ckeditor data first before retrieve edited data
myClass.updateCkeditor();
//Retrieve edited data from HTML DOM
myClass.seteditorData = document.getElementById(editorName).value;
//Call AJAX function to pass the value
myClass.startAjax();
}
//Catch the focus and blur status of inline toolbar
this.editor = CKEDITOR.inline( editorName, {
on: {
//focus: onFocus,
blur: myClass.onBlur,
}
});
//Declare which cms section we currently editing, parse the integer from the id of the textarea
this.setcmsID = parseInt(editorName.replace("editor",""));
//Create an AJAX function
this.startAjax = function() {
alert(this.seteditorData);
$.ajax
({
type: "POST",
url: "test2.php",
data: {editorData: this.seteditorData, cmsID: this.setcmsID},
cache: false,
beforeSend: function()
{
//Loading
},
success: function(result)
{
alert("Successfully updated!");
}
});
}
}
I need to check whether the data is already exists in the database before submitting the form using ajax. The most common scenario is the checking the availability of the username and email.
It's not working but I tested the ajax function without using the from control and it works fine. The project is created in MVC 3 VB.
Javascript:
$('#addSalesPeople').click(function () {
$.post("ajax_functions/checkDuplicate.cshtml",
{
extension: document.getElementById('Extension').value,
initials: document.getElementById('Initials').value
},
function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
});
HTML:
#Using Html.BeginForm("Create", "SalesPeople", FormMethod.Post)
#Html.ValidationSummary(True)
#<fieldset>
............................
..............................
#Html.TextBoxFor(Function(model) model.Extension, New With {.onkeyup = "javascript: charCounter(this,4);", .onblur = "javascript: zeroPad(this, 4)"})
#Html.TextBoxFor(Function(model) model.Initials)
<input id="addSalesPeople" class="btn span2" type="submit" value="Add" />
</fieldset>
-Thanks
You need to observe the submit event of the form.
Instead of
$('#addSalesPeople').click(function () {
use
$('#theFormId').submit(function () {
see: http://api.jquery.com/submit/
You can also disable the form submit and send it later manually:
$( '#theFormId' ).submit( function ( event ) {
event.preventDefault();
/* your AJAX code */
$( '#theFormId' ).submit();
} );
I am posting a real tested code.
HTML: Simple form post button in #using
(Html.BeginForm())
{
//use your text box or other control here
<input type="submit" id="Create" value="Create" class="btn btn-primary" />
}
JavaScript:
<script>
$(document).ready(function () {
$("form").submit(function (e) {
e.preventDefault(); //prevent default form submit
if ($(this).valid()) {
var UserId= $('#UserId').val();
$.ajax({
url: '/Home/CheckUserExist/', //ControllerName/ActionName/
data: {
UserId: UserId
},
success: function (data) {
showMsg(data);
},
cache: false
});
}
});
});
function showMsg(hasCurrentJob) {
if (hasCurrentJob != "OK") {
alert(hasCurrentJob);
return false;
} else {
//if check is ok than from post to controller
$("form").unbind('submit').submit();
}
}
</script>
MVC Controller:
public async Task<JsonResult> CheckUserExist(int UserId)
{
//condition for user check
if (UserExist==true)
{
return Json("User Exist Please choose another user name or etc", JsonRequestBehavior.AllowGet);
}
return Json("OK", JsonRequestBehavior.AllowGet);
}
if you have any query mail me vishalroxx7#gmail.com.
I may be missing something obvious here, but how could I rewrite this code!
i am trying here to store the value entered in the textbox(Textbox was showed in javascript dialog page).In a javascript dialog page i have one 'ok' button.. when i click the button i want to store the value entered in the textbox.I want to save the content using Ajax.
Please see my sample code
View page:
<script language="javascript" type="text/javascript">
$(function () {
$('.button').live('click', function () {
$('.Text_dialog').dialog('open');
});
$('.Text_dialog').dialog({
autoOpen: false,
buttons: {
'Ok': function () {
var textValue = $(':txtValue').val();
$.ajax({
url: '/Home/About',
type: 'POST',
data: { str: textValue },
success: function (result) {
alert(result.val);
}
});
},
}
});
});
</script>
<input type="button" value="Add Value" class="button" />
<div class="Text_dialog" title="Basic modal dialog">
TextValue: <input type="text" class="txtValue" />
</div>
Control page:
[HttpPost]
public ActionResult About(string str)
{
ValidateClass ObjAM = new ValidateClass();
int value = ObjAM.ValidatetextValue(str);
return Json(new { val = value });
}
Model page:
public class ValidateClass
{
DataClasses1DataContext dbObj = new DataClasses1DataContext();
public int ValidatetextValue(string str)
{
string value = (from SearchtextValue in dbObj.Options
where SearchtextValue.OptionName == str
select SearchtextValue.OptionName).Single();
if (value == null)
{
return 1;
}
return 0;
}
}
When i run this code i am getting script error like "Object doesn't support this property or method".Please advice
Change data: { str: textValue } to data: "{ 'str' :'" + textValue +"' }"
If you are confused on escaping the quotes properly, try this.
$(function() {
$('.button').live('click', function() {
$('.Text_dialog').dialog('open');
});
$('.Text_dialog').dialog({
autoOpen: false,
buttons: {
'Ok': function() {
var DTO = "{ 'str' :'" + $('.txtValue').val() +"' }";
$.ajax({
url: '/Home/About',
type: 'POST',
data: DTO,
success: function(result) {
alert(result.val);
}
});
},
}
});
});
Please note that I have changed the :txtValue to .txtValue as it is the correct selector.
can you try changing
<input type="text" class="txtValue" />
to
<input type="text" class="txtValue" id="txtValue" />
and
var textValue = $(':txtValue').val();
to
var textValue = $('#txtValue').val();
I've never used : selector... but I think it will return you a collection and you should use index [0] or, why don't you use class selector .?
Edit: as I see you cannot use : in this case
also you can add dataType: "json",into your Ajax request, and change your method return type from
public ActionResult About(string str)
to
public JsonResult About(string str)
EDIT 2:
have you included the library where dialog() function is? after including the jquery library?