Populating razor text input from ViewData - javascript

Im trying to pre populate an input text box in a modal. Currently i click the edit button which calls a jQuery function that makes an ajax call
<script>
$(document).ready(function(){
$(".selectRow").click(function(e)
{
e.preventDefault();
var row = $(this).closest("tr"),
tds = row.find("td:nth-child(1)").first();
var textval = tds.text();
$.ajax({
url: "EditApplication?handler=GetRowInfo",
type: "POST",
dataType: "json",
data: { textval },
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function () {
alert("success");
},
complete: function () {
$('#editAppModal').modal('show');
},
failure: function () {
alert("failure");
}
})
});
});
</script>
On completion i show the modal. This jQuery function calls a method in the code behind called GetRowInfo which grabs a cell from a table.
GetRowInfo
public void OnPostGetRowInfo(string textval)
{
Console.WriteLine("-----------------"+textval);
DutyWeb dutyWebManager = new DutyWeb();
textval = textval.Trim();
Console.WriteLine("-----------------NEW-"+textval);
selectedRow = dutyWebManager.SearchByApplication(textval);
ViewData["appName"] = textval;
}
I assign the text value sent into the ViewData as appName
I then assign the textbox input value to be the ViewData["appName"
<div class="modal-body">
<input type="text" name="appName" id="appName" value='#ViewData["appName"]'>
<input type="text" name="appShortName" style="width:15%">
<br>
</div>
I dont know if im doing this wrong but it seems right to me. The modal is inside of a form element. Stepping through revealed that the ViewData is indeed storing the correct value, but its not being displayed in the textbox
I would like to avoid using jQuery to do this. I feel like ViewData is a much easier way of accomplishing the same task

Related

Including javascript file along with ajax response

I've got a dropdown that runs AJAX each time an option is selected. The ajax call returns HTML markup (buttons and text boxes) and a script tag, which the HTML(buttons) uses to submit to a database via ajax.
<html>
<head>........</head>
<body>........</body>
<select class="chooseOption">
...
...
</select>
<div class="ajaxResult">
<!-- after successful ajax -->
<!-- HTML Markup here -->
<!-- I'm having to include main.js here again so that HTML matkup can use AJAX -->
</div>
....
....
....
<footer> //include main.js </footer>
This arrangement seems to work fine only that, there's an exponential call to main.js each time an option is selected.
Doing something like this(below) doesn't seem to work, I'm guessing because AJAX is injected into the page and isn't aware of what scripts that are already available on the page?
<script>
var len = $('script').filter(function () {
return ($(this).attr('src') == 'main.js');
}).length;
//if there are no scripts that match, the load it
if (len === 0) {
var url = "main.js";
$.getScript(url);
}
</script>
Is there a simple way around this? To make sure that main.js works across all AJAX requests without having to include it with each request?
Sample main.js content.
Ajax snippet that populates the HTML Markup (buttons and textboxes)
$("#students").on("change", function (e) {
e.preventDefault();
var supervise = this.value;
var faculty = $("#faculty").val();
$.ajax({
method: "POST",
url: 'URL',
dataType: 'html',
data:
{
selectValue: supervise,
faculty: faculty
},
success: function (result) {
$("#ajaxResult").html(result);
}
})
});
When #statement_button from HTML markup returned from select dropdown is clicked
$('#statement_button').click(function (e) {
var student_statement = $("#student_statement").val();
if (student_statement == '') {
alert('Please enter your statement');
return false;
}
var student = $("#student").val();
var statement_button = $(this).attr("value");
$.ajax({
type: "POST",
url: formsUrl,
dataType: 'text',
data:
{
student_statement: student_statement,
student: studentusername,
statement_button: statement_button
},
success: function (result) {
$("#result").text(result);
$("textarea#student_statement").val('');
}
})
});
From the code you posted it looks like you can just delegate the button handling to the .ajaxResult element which is always present in the html (from the initial load).
So just changing how you bind your button handlers should be enough
$("#students").on("change", function (e) {
to
$('.ajaxResult').on('change', '#students', function (e) {
$('#statement_button').click(function (e) {
to
$('.ajaxResult').on('click', '#statement_button', function (e) {
etc..
So the script with the above code is run once in the initial load of the page (in a $(document).ready(..))

search function in laravel wont work

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

Javascript works fine with a hard-coded string but not with variable

I have a problem I have bee struggling over all morning so I felt it was time to get some help! I have a javascript function which gets the value entered by a user into an autocomplete box, uses AJAX to send that value to a php script which queries the database and then populates the following box with the possible options. The problem is this all works fine when I hard-code in the selected option as so:
var selected="Ed Clancy";
but not when it pulls it from the box, as so:
var selected = this.getValue();
I have tried debugging this using an alert box and both boxes come up with the same string in them so I am completely puzzled! Any ideas? Full code below:
$(riderSelected).on('selectionchange', function(event){
var selected = this.getValue();
//var selected="Ed Clancy";
alert(selected);
$('#nap4').removeAttr('disabled');
$('#nap4').empty();
$('#nap4').append($("<option>-select-</option>"));
$.ajax({
type: "GET",
url: 'getbiketype.php',
data: { name: selected },
success: function(data) {
console.log(data);
$('#nap4').append(data);
}
});
});
Based on magicsuggest documentation - http://nicolasbize.com/magicsuggest/doc.html , you probably could do this
var selected = this.getValue()[0];
IF you do not allow multiple selection
Change your code as I have written below for you .
Code
$(riderSelected).on('change', function (event) {
var selected = this.value;
alert(selected);
$('#nap4').removeAttr('disabled');
$('#nap4').empty();
$('#nap4').append($("<option>-select-</option>"));
$.ajax({
type: "GET",
url: 'getbiketype.php',
data: {name: selected},
success: function (data) {
console.log(data);
$('#nap4').append(data);
}
});
});

How to show php passed results to ajax without refreshing

I want to do is when a user type an email to the inputbox ajax will pass the value automatically to php.
My problem is the result only show if I try to refresh the page
html:
<input type="text" id="email" name="email" />
script:
$(document).ready(function(){
var countTimerEmailName = setInterval(
function ()
{
emailName();
}, 500);
var data = {};
data.email = $('#email').val();
function emailName(){
$.ajax({
type: "POST",
url:"Oppa/view/emailName.php",
data: data,
cache: false,
dataType:"JSON",
success: function (result) {
$("#imageLink").val(result.user_image);
$("#profileImage").attr('src', result.user_image);
$("#emailNameResult").html(result.user_lname);
$("#emailCodeResult").val(result.user_code);
}
});
};
});
You can try with:
Because you dont need declare function in ready() and you need yo get the email value after any change. Now you only get the value when the page is ready.
function emailName( email ){
$.ajax({
type: "POST",
url:"Oppa/view/emailName.php",
data: 'email=,+email,
cache: false,
dataType:"JSON",
success: function (result) {
$("#imageLink").val(result.user_image);
$("#profileImage").attr('src', result.user_image);
$("#emailNameResult").html(result.user_lname);
$("#emailCodeResult").val(result.user_code);
}
});
};
$(document).ready(function(){
$('#email').change(function(e) {
emailName( this.val());
});
});
You're handling it wrong. jQuery has particular events to do these things.
Take this for example:
$(document).ready(function(){
$(document).on('keyup', '#email', function(e) {
e.preventDefault();
val = $(this).val();
console.log("Value: " + val);
});
});
It will look what is in the below input field as the user types. (which is what I presume you're trying to do?)
<input type="text" id="email" name="email" />
Example
You could simply remove that console.log() and replace it with your ajax request. (The above example will run as the user types.)
Alternatively you could use change() like this:
$(document).ready(function(){
$(document).on('change', '#email', function(e) {
e.preventDefault();
val = $(this).val();
console.log("Value: " + val);
});
});
Which will run after the value of the text box has changed. (When the user clicks out of the text box or moves somewhere else on the page.)
Example

You cannot apply bindings multiple times to the same element

I have a Bootstrap modal, and every time it shows up I will use KO to bind a <select> dropdown.
HTML:
<select id="album" name="album" class="form-control" data-bind="options: availableAlbums">
</select>
JavaScript:
$('#uploadModal').on('show.bs.modal', (function () {
function AlbumsListViewModel() {
var self = this;
self.availableAlbums = ko.observableArray([]);
$.ajax({
url: "../../api/eventapi/getalbums",
type: "get",
contentType: "application/json",
async: false,
success: function (data) {
var array = [];
$.each(data, function (index, value) {
array.push(value.Title);
});
self.availableAlbums(array);
}
});
}
ko.applyBindings(new AlbumsListViewModel());
}));
However, on the second showing, KO will present me with this error:
Error: You cannot apply bindings multiple times to the same element.
The error message says most of it. You have two options:
Call the applyBindings function once, when your page loads. KO will automatically update the View when you update the model in a AJAX success function.
Call the applyBIndings function on each AJAX success, but supply additional parameters to tell it what element to bind to.
Most likely the first option is what you're looking for. Remove the call from the $('#uploadModal').on call and place it on document load (if you haven't already).
To see what I mean, here's two fiddles:
Your current code with the error you mention.
Refactored version that doesn't have the error.
The latter tries to stay as close as possible to your initial version (so as to focus on the problem at hand), and goes along these lines:
function AlbumsListViewModel() {
var self = this;
self.availableAlbums = ko.observableArray([]);
}
var mainViewModel = new AlbumsListViewModel();
ko.applyBindings(mainViewModel);
$('#uploadModal').on('show.bs.modal', (function () {
// Commenting things out to mock the ajax request (synchronously)
var data = [{Title:'test'}];
/*$.ajax({
url: "../../api/eventapi/getalbums",
type: "get",
contentType: "application/json",
async: false,
success: function (data) {*/
mainViewModel.availableAlbums.removeAll();
var array = [];
$.each(data, function (index, value) {
array.push(value.Title);
});
mainViewModel.availableAlbums(array);
/*}
});*/
}));

Categories