adding new dropdown lists in asp without reloading the page - javascript

I would like to have a page that would contain:
hyperlik "Add new country".
After clicking this link by user, dropdown list with names of countries should appear. However this hyperlink should stay on this page. When user click this hyperlink once again, second dropdown list with exactly the same names should appear. This should be repeat as long as user clicks hyperlink.
It is important that this page shouldn't be reloaded.
Does anyone has any idea how can it be made?

The typical way to achieve this is to have your Add new country link trigger an ajax call out to a page you create which will provide the data for your list.
The preferred method these days seems to be having that page you call build up a JSON response, then your callback on the ajax method where you called it can populate that data into a drop down.
The page you call from AJAX could be something simple like this:
protected override void Render(HtmlTextWriter writer)
{
Dictionary<string, int> myStuff = new Dictionary<string, int>();
myStuff.Add("country1", 1);
myStuff.Add("country1", 2);
JavaScriptSerializer jss = new JavaScriptSerializer();
Response.Write(jss.Serialize(myStuff.ToList()));
Response.ContentType = "application/json";
}
Use this jQuery on your main page:
<script type="text/javascript">
$(document).ready(function () {
$("#btn").click(function () {
getCountries();
});
});
function getCountries() {
$.ajax({
url: "ApiPage.aspx",
dataType: "json",
success: function (data) {
for (var i in data) {
$("#myDropDown").append($('<option></option>').val(data[i].Value).html(data[i].Key));
}
}
});
}
</script>
Tested and working. (in a simplified example) I did have to convert from Dictionary to List for the json serializer to make it an array as desired. See the updated Serialize call. There is also some validation, e.g. did the ajax call return real data?, that would need added to a real life implementation.

It looks like you are doing it a least approximately right.
in the HTML if you have some tag that surrounds the area you want the drop down box to then it is simple.
for example:
in HTML:
Add new country
<div id="dropdownarea"></div>
in javascript:
function addDD(){
document.dropdownarea.innerHTML += "HTML code for the drop down that you want";
}

Related

How to pass data from Laravel View to Ajax or Javascript code without html div (id or class) - Laravel 5.3

So, currently I am passing values stored in Database MySQL to View (using Controller). I do simple querying ModelName::where()->first();.
I have my data right now in View. I want to use that data in Ajax or Javascript code that I am writing.
I can have 46 values and one way to do this is to have <div id="field1"></div> for 46 times set div style to display:none in css and in Javascript use document.getElementById('field1'); to access the values and finally, do whatever I want to do with it.
But I find this quite long and un-necessary to do as there is no point of printing all the values in html first and then accessing it. How can I directly get {{$data}} in Javascript?
myCode
public function index(Request $request){
$cattfs = Cattf::all();
$cattts = Cattt::all();
$cattos = Catto::all();
return view('/index',compact('cattfs'));
}
View
Nothing in the view. and I prefer it to be none.
Javascript and Ajax
$(document).ready(function()
{
init();
});
function init(){
my_Date = new Date();
var feedback = $.ajax({
url:url,
dataType: "JSON",
type: "GET",
}).success(function(data){
console.log(data);
//I have some data called data from url
//I want some data from controller like: cattf,cattt,catto
//I will combine url data and cattf and do simple arithmetic to it
//finally output to the view.
}).responseText;
}
One good way would be to actually make a small API to get your data. Let's say you wanted to retrieve users.
In the api.php file in your route folder:
Route::get('/posts', function () {
return Post::all();
});
and then you just need to use http://yourUrl.dev/api/posts as your URL sent in your .ajax() call to work with what you need.
I found best solution use this: https://github.com/laracasts/PHP-Vars-To-Js-Transformer
It takes values from controller directly to Javascript.

Post textarea using #Html.ActionLink - ASP.NET MVC 5

I know that this question was answered many times, but since I don't know much about javascript, and this is my first website, I followed the answer in this link. This is my code so far:
<li>#Html.ActionLink("Save","SaveClass",new { path2=Model.path,code="xxx"},new { id="save"})</li>
#Html.TextAreaFor(m=>m.code, new { id = "code" })
<script>
$("#save").click(function(evt) {
var fakedUri = $("#save").attr("href");
alert($('#code').val());
var uri = $("#save").attr("href").replace("xxx", $("#code").val());
});
</script>
And this is my controller:
public ActionResult SaveClass(string path2,string code)
{
modelSC.path = path2;
modelSC.code = code;
System.IO.File.WriteAllText(Server.MapPath(modelSC.path), code);
return RedirectToAction("Index");
}
The code always saves 'xxx' to the file, and throws:
The requested content appears to be script and will not be served by
the static file handler.
How can I get it to work?
ActionLink helper generates a link and clicking on that will issue a GET request. Looks like you are trying to send the value of the text area through querystring to the next action method. But GET might not be the best solution to handle that. Querystring has a limit on how much data it can handle (varies for different browsers).
Ideally you should do a form submit, If you do not prefer a button, but want a link to initiate the form submit, that is possible with a little javascript.
#using(Html.BeginForm("SaveClass","YourControllerName"))
{
#Html.TextAreaFor(m=>m.code)
#Html.HiddenFor(s=>s.path)
#Html.ActionLink("Save","SaveClass","YourControllerName",null,new { id="save"})
}
Now in your javascript, when click on the link, stop the default behavior (the default GET Action) and then submit the form where the clicked link is present. We can use the closest() method.
$(function(){
$("#save").click(function(e){
e.preventDefault();
$(this).closest("form").submit();
});
})
Make sure you use the correct parameter name (matching with the input name)
public ActionResult SaveClass(string path,string code)
{
// to do : return something
}

Render html into View MVC

Hi i am making my project in MVC, i which i want to add the control from the drop-down selection on right side div, (the black rectangle part in the image).
Now i have two requirements
Get the inner html or .html() of the right side div, and save this in the database along with the left side form values
I have another view details where i want to display the values of left side fields and render the inner html on right side, (i have the container div in my details view )..
i am getting the html with following button click function
$('#SaveCone').click(function () {
var a = $('#NewData').html();
console.log(a);
});
tell me please if you want another details, thanks for your kind help
this is nice question
If you want to store your html into the database, simply use ajax ,
$('#urbutton).click(function () {
var a = $('#yourForm).html();
$.ajax({
type: 'POST',
url: '/UrController/Uraction',
data:
$('#MyForm').serialize() + "&par2=" + a,
success: function (data) {
// ` alert(data);
}
});
});
your controller looks like this
public ActionResult Create(Table table, string par2)
{
using (urcontext cntxt = new urcontext ())
{
if (ModelState.IsValid)
{
table.data = par2;
cntxt.SaveChanges();
}... so on
this will store your data into database
How to render the Html from database to the view
simply use
<div id="container">
#HTML.Raw(model.data)
< /div>
Hope this will help you man

How to Make a Feed From User Submitted Posts

I'm trying to figure out how to use AJAX to create a Twitter-like feed that displays user's posts on the same page immediately after they push the submit button. It would be an infinite-feed site that would have a "more" button at the bottom.
All I'm trying to make is a simple page containing a textarea box with a submit button and to have user submissions appear below the box as they are submitted.
If possible, a walk through or discussion of the script needed to do this would be great.
Thanks so much
All you need is a server-side script with an SQL query that would return newer posts.
have your javascript store a variable of the date or of the last post id (used PHP for clarification):
result = mysql_query("SELECT ID,POST FROM POSTS WHERE DATE>" . $_GET['date']); //or use WHERE ID> $_GET['id']
while(rows[] = mysq_fetch_array(query));
print json_encode(rows);
now you have a server-side script that will return new posts, so all you have to do is write javascript function for the more button:
updatePosts = function () {
$.ajax({
url: 'serversiderUrl?lastId=' + last_id, //last_id is global variable for the id of the last post on the page
success: function(data){
data = JSON.parse(data);
for(i in data){
$('#posts_container').append(data[i].post); //do your appending functions here
last_id = data[i].id;
}
}
}
now for posting new entries create a server-side script of your favorite language that handles new posts:
result = mysql_query("INSERT INTO POSTS VALUES(''," . urldecode($_POST['POST']) . ")");
now for the client side:
submit_post = function(){
$.ajax({
type: 'POST',
url:'yourposturl',
data: "post=" + encodeURIComponent($('#textArea').text()),
success: function(){
updatePosts(); // call the function that update the posts so the new entry is now added to the page
}
});
}
Now bind the functions to the appropriate buttons when the document is fully loaded:
$(document).ready(function (){
$('#moreButtonId').click(updatePosts);
$('#submitButtonId').click(submitPost);
});
There are many ways such as the submit button kept sending it to the database while we'd append text to a container underneath. Or we can update the container underneath to create a container (page) that are similar, after the ajax response is successful then we append the data to the container beneath
$.post(url,function(data){
//Here you can append the data responsed by the ajax request to the container underneath
});
But you have to have a exactly same view with a conatiner (feed container) existing in the currently page

How do I make a jQuery POST function open the new page?

I know that a submit button in HTML can submit a form which opens the target page, but how do I cause a jQuery ajax call to POST information to a new page and also display the new page. I am submitting information that is gathered by clicking elements (which toggle a new class called "select") and then identifiers from these items with the new class are added to a string and POSTed to the new page. This new page will use this data to provide a summary of the selections from the previous page. I currently can get it to POST the data to a new PHP page but it seems to be the ajax function simply remains on the current page (which is great for some things, just not this), not redirecting to the new page. how might I go about doing this?
here's the script section:
//onload function
$(function() {
//toggles items to mark them for purchase
//add event handler for selecting items
$(".line").click(function() {
//get the lines item number
var item = $(this).toggleClass("select").attr("name");
});
$('#process').click(function() {
var items = [];
//place selected numbers in a string
$('.line.select').each(function(index){
items.push($(this).attr('name'));
});
$.ajax({
type: 'POST',
url: 'additem.php',
data: 'items='+items,
success: function(){
$('#menu').hide(function(){
$('#success').fadeIn();
});
}
});
});
return false;
});
any pointers would be great!! thanks
edit:
thanks for the help, I've changed my script to :
//onload function
$(function() {
//toggles items to mark them for purchase
//add event handler for selecting items
$(".line").click(function() {
//get the lines item number
var item = $(this).toggleClass("select").attr("name");
});
$('#process').click(function() {
var items = [];
//place selected numbers in a string
$('.line.select').each(function(index){
items.push($(this).attr('name'));
});
$('#items').attr('value',items);
$('#form').submit()
});
return false;
});
First of all I discourage using ajax here as you are not using it for the purpose for which it is intended to, and you are forcing it to do a reload.
You can do something like this in the success of ajax
success: function(){
window.location = "the new url you wanted to load";
}
Edit:
Why not do a normal post with form action attribute set to the page you want to post to and you can access all the variables of the form in that posted page, or alternatively you can concatenate or store in array all your values and store this array in a hidden variable and access this variable in the posted script.
Ajax posts by definition won't to a page load. But you can do whatever you want in your success handler. So just change the document location there:
success: function(){
$('#menu').hide(function(){
$('#success').fadeIn();
});
window.location = 'http://www.example.com/elsewhere';
}
Oftentimes a POST will return a HTTP 301 or 302 redirect. In that case, you can get the returned header information from the XHR object, which is passed into the callback functions.
complete: function( xhr ) {
// assume we got a redirect; the new URL will be in the Location header
window.location = xhr.getResponseHeader( 'Location' );
}

Categories