AJAX code confusion using GET method - javascript

I bought a book and began learning how to use AJAX and someone gave me a practice assignment where I have to enter values into one div and perform an AJAX get request to a website she gave me to receive the information in the right div. Maybe I am doing the AJAX get request incorrectly following this book. If anyone could point me in the right direction I would appreciate it. This is not for school, and I have no experience in web scripting languages but willing to learn. Just give my javascript a look and maybe you can help me out. I am not sure yet on how to display the information after it has been received but I know for sure I do not want to load another page when hitting the submit button!
Also, I have a weird way of lining up my code from programming in C++ for about 4 years now. I have developed it over time and sorry if it is hard to understand. If so, then I can format it a proper way and re-post. Also, I am trying to learn how to use the AJAX GET method, not the POST method. And I want to return the information in JSON.
<html>
<head>
<style type="text/css">
#header {
text-align: left;
}
#wrapper {
margin:bottom;
width:100%;
}
#sub-left {
float:left;
width:225px;
height:215px;
border:1px solid black;
position: relative;
text-align: left;
}
#sub-right {
padding-left: 52px;
float:left;
width:60%;
height:45%;
border:1px solid black;
position: relative;
text-align: left;
}
#sub-leftmost {
float:left;
width:10%;
height:100%;
position: relative;
text-align: left;
}
</style>
<script type=”text/javascript”>
// function create GetXmlHttpObject
function GetXmlHttpObject(){
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject){
// code for IE6, IE5
return new ActiveXObject(“Microsoft.XMLHTTP”);
}
return null;
}
function submitFormWithAjax(){
var myAjaxGetrequest = new GetXmlHttpObject();
var t2lName=document.testForm.namebox.value;
var t2lEmail=document.testForm.ebox.value;
var t2lAddress=document.testForm.addbox.value;
var t2lPhone=document.testForm.phnbox.value;
var parameters = "name=" + encodeURIComponent(t2lName)
+ "&email=" +encodeURIComponent(t2lEmail)
+ "&address=" + encodeURIComponent(t2lAddress)
+ "&phone=" +encodeURIComponent(t2lPhone);
myAjaxGetrequest.open("GET", "websitetosendandgetfrom.com" + parameters, true);
myAjaxGetrequest.send( );
if (myAjaxGetrequest.readyState==4){
if(myAjaxGetrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("result").innerHTML=myAjaxGetrequest.responseText
document.getElementById(“testForm”).style.display = “none”;
}
else {
document.getElementById(“testForm”).innerHTML=”An error has occured making the request”;
}
}
}
}
</script>
</head>
<body>
<div id="wrapper">
<div id="sub-leftmost">
</div>
</div>
<div id="wrapper">
<div id="header"><h1>Quiz</h1></div>
<div id="sub-left">
<form name = 'testForm'>
<FONT COLOR="CC3300",font size="5"> <b>User Info</b></FONT>
<br />
Full Name: <br /><center><input type="text" size="25" id = "namebox" /></center>
Email Address: <br /><center><input type="text" size="25" id = "ebox" /></center>
Address: <br /><center><input type="text" size="25" id = "addbox" /></center>
Phone Number: <br /><center><input type="text" size="25" id = "phnbox" />
<a href=”#” onclick=”submitFormWithAjax();”>Finished!</a>
</form>
</div>
</div>
<div id="wrapper">
<div id="sub-right">
</div>
</div>
</body>
</html>

The request is asynchronous and will only call a callback function when its status changes.
Basically, all the code that depends upon the request's status change needs to be wrapped into the callback of the AJAX request:
myAjaxGetrequest.send();
myAjaxGetrequest.onreadystatechange = function() {
if (myAjaxGetrequest.readyState==4){
...

Related

UI problems - How do I trigger an image loading on choice made by dropdown box? Then add text to overlay the image result?

I'm new to coding, I've learned the very basics of html/css/js/java, at least I thought I had, until I went to make a simple game.
I made a simple choose your own adventure game that worked, as each choice just went to a new page.
Then, I thought I'd make it a bit more complex, so I want to have the user enter their name, and store that to show next to the player's stats.
I've got a dropdown box with 4 choices for characters.I want to have Strength/Mana/Lives stats and have the player's choice of character to be able to adjust these stats accordingly before the game starts i.e. Male Warrior would have 2 extra Strength, Female Mage 2 extra mana etc.
Then, I'd like an image based on their character choice displayed next to their stats, so that the game can begin.
So far, I've been pulling my hair out in great clumps and have tried many different methods but so far, I've only got to the stage where I place the page with user input into an iframe. I can get to reflect their choices with text, but I can't get an image to load on submit. Ideally I'd like a permanent box in the top corner of the iframe, and have the statistics variables passed into the stats shown alongside the character's image.
I'd really really appreciate any help here, especially if it can be solved using HTML/CSS/JS as I'm not too familiar with JQuery, and would like to keep it as simple as possible really.
I've gone through as many q's and a's as I can to find relevant help, but I'm mainly finding answers for PHP or other languages.
I must apologise in advance for my waffling above, and sloppy coding. (I seriously thought this would be easy heh).
I'm unsure if my code so far will help, but I'll just paste it below anyway.
HTML for the UI page is:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Character Selection</title>
<link rel="stylesheet" href="css/style2.css">
<style>
img {
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<div>
<div id='gamestitle'>
<p>
<img src = "GAMETITLE.jpg"
alt = "Steve's Perilous Capers"/>
</p>
</div>
<br>
</div>
<div class='wrapper'>
<form id='nameForm'>
<div class='form-uname'>
<lable id='nameLable' for='nameField'>Create a username:</lable>
<input id='nameField' type='text' maxlength='25'></input>
</div>
<div class='form-sub'>
<button id='subButton' type='button'>Enter your name!</button>
</div>
</form>
<div>
<p id='result'></p></div>
</div>
<div>
</div>
<div>
<form>
Select your Hero please:
<select id="mySelect">
<option>Male Warrior</option>
<option>Male Mage</option>
<option>Female Warrior</option>
<option>Female Mage</option>
</select>
<br><br>
<input type="button" onclick="getOption()" value="Confirm">
</form>
</div>
<script src="js/index.js"></script>
<script>
document.getElementById("demo").innerHTML =
obj.options[obj.selectedIndex].text;
</script>
<p id="demo"></p>
</body>
</html>
The CSS is:
body {
margin: auto;
text-align: center;
}
li {
list-style:none;
}
li.fields {
margin: 0;
padding: 1em 0;
}
li.title {
cursor: pointer;
font-weight: bold;
font-size : 1.5em;
line-height: 2em;
background: #e3e3e3;
border-bottom: 1px solid #c5c5c5;
border-top: 1px solid white;
}
.gamestitle {
max-width: 100%;
margin: auto;
}
.hide { display: none;}
.result {
height: 200px;
width: 50%;
background-color: powderblue;
}
The JS file: (I've tried using icons and background image but I couldn't get them to show)
// the function which handles the input field logic
function getUserName() {
var nameField = document.getElementById('nameField').value;
var result = document.getElementById('result');
if (nameField.length < 3) {
result.textContent = 'Username must contain at least 3 characters';
//alert('Username must contain at least 3 characters');
} else {
result.textContent = 'Your Hero is: ' + nameField;
//alert(nameField);
}
}
function getOption() {
var obj = document.getElementById("mySelect");
document.getElementById("demo").innerHTML =
obj.options[obj.selectedIndex].text;
}
function swapImage(){
var image = document.getElementById("imageToSwap");
var dropd = document.getElementById("dd");
image.src = dropd.value;
};
// use an eventlistener for the click event
var subButton = document.getElementById('subButton');
subButton.addEventListener('click', getUserName, false);
var subButtonTwo = document.getElementById('subButtonTwo');
subButtonTwo.addEventListener('click', getOption, false);
$(function () {
$.widget("custom.iconselectmenu", $.ui.selectmenu, {
_renderItem: function (ul, item) {
var li = $("<li>"),
wrapper = $("<div>", {text: item.label});
if (item.disabled) {
li.addClass("ui-state-disabled");
}
$("<span>", {
style: item.element.attr("option-style"),
"class": "ui-icon " + item.element.attr("data-class")
})
.appendTo(wrapper);
return li.append(wrapper).appendTo(ul);
}
});
$("#mySelect")
.iconselectmenu()
.iconselectmenu("menuWidget")
.addClass("ui-menu-icons avatar");
});
/*
function getcurrentChoice() {
var characterSelection = ['MaleWarrior'], ['MaleMage'], ['FemaleWarrior'], ['FemaleMage'];
var currentChoice = document.getElementById('currentChoice').value;
var resultChoice = document.getElementById('resultChoice');
var subButtons = document.getElementById('subButtons');
subButtons.addEventListener('click', getcurrentChoice, false);
}
*/
Sorry for the messy coding, it's not helped that I've tried so many workarounds for each problem I've encountered that I've lost track of what is and isn't working.
I'm pretty sure this is out of control by now, and a waste of your time, but I'm so confused. I'm sure i'm over complicating the matter.
Thanks in advance again,
Steve.
Check this:
https://jsfiddle.net/digitalrevenge/q9z1x6vv/
I've added an img src and made some changes to your JS.
I'm not sure if it does exactly what you want but there's no harm in giving it a try ;)
I am not sure how to do this in Javascript, but I have achieved it with jQuery, maybe you can adapt it to Javascript if you like.
Basically...
Give each option a value
On selection, or change, empty div#change_this, and check for the value
If value = # then add html code to div#change_this
You can change the image/add in the stats, I just used some filler.
You will also need to add css and all that, if you have any specific questions about that, please let me know.
Functionality is there though.
Best,
Levi
body {
margin: auto;
text-align: center;
}
li {
list-style:none;
}
li.fields {
margin: 0;
padding: 1em 0;
}
li.title {
cursor: pointer;
font-weight: bold;
font-size : 1.5em;
line-height: 2em;
background: #e3e3e3;
border-bottom: 1px solid #c5c5c5;
border-top: 1px solid white;
}
.gamestitle {
max-width: 100%;
margin: auto;
}
.hide {
display: none;
}
.result {
height: 200px;
width: 50%;
background-color: powderblue;
}
<div>
<div id='gamestitle'>
<img src = "GAMETITLE.jpg" alt = "Steve's Perilous Capers"/>
</div>
<br>
</div>
<div class='wrapper'>
<form id='nameForm'>
<div class='form-uname'>
<lable id='nameLabel' for='nameField'>Create a username:</lable>
<input id='nameField' type='text' maxlength='25'></input>
</div>
<div class='form-sub'>
<button id='subButton' type='button'>Enter your name!</button>
</div>
</form>
<div>
<p id='result'></p>
</div>
</div>
<div>
<form>
Select your Hero please:
<select name="hero_type" id="mySelect">
<option value="0">Male Warrior</option>
<option value="1">Male Mage</option>
<option value="2">Female Warrior</option>
<option value="3">Female Mage</option>
</select>
<br><br>
<input type="button" onclick="getOption()" value="Confirm">
</form>
</div>
<div id="change_this">
<p>Yayyy, Male Warrior.</p> <img alt="" src="http://via.placeholder.com/350x150">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('select[name="hero_type"]').click(function() {
$('#change_this').empty();
if ($('select[name="hero_type"]').val() == "0"){
$('#change_this').append('<p>Yayyy, Male Warrior.</p> <img alt="" src="http://via.placeholder.com/350x150">')
}
if ($('select[name="hero_type"]').val() == "1"){
$('#change_this').append('<p>Yayyy, Male Mage.</p> <img alt="" src="http://via.placeholder.com/350x150">')
}
if ($('select[name="hero_type"]').val() == "2"){
$('#change_this').append('<p>Yayyy, Female Warrior</p> <img alt="" src="http://via.placeholder.com/350x150">')
}
if ($('select[name="hero_type"]').val() == "3"){
$('#change_this').append('<p>Yayyy, Female Mage</p> <img alt="" src="http://via.placeholder.com/350x150">')
}
})
});
</script>
The src attribute of an image tag points to the location of the image file to use.
You should be somewhat aware of this as your code contains:
<img src = "GAMETITLE.jpg" alt = "Steve's Perilous Capers"/>
To change the image, simply change the src attribute to point to the location of the new image.
The source of an image tag can be accessed and changed via:
document.getElementById("imageId").src="fileToUse";
This means you need to add an id to your image tag as so:
<img src = "GAMETITLE.jpg" alt = "Steve's Perilous Capers" id="imageId"/>
In your case, you want to get the image src from a select field. This means you need to tie the image file locations to your select form as values.
<select id="mySelect">
<option value="location-of-this-image.png">Male Warrior</option>
<option value="location-of-this-image.png">Male Mage</option>
<option value="location-of-this-image.png">Female Warrior</option>
<option value="location-of-this-image.png">Female Mage</option>
</select>
To use these values and assign them to the image src:
document.getElementById("imageId").src=document.getElementById("mySelect").value;
If you correctly id your image and select form, give the select form proper values, and put the above line of code in the function you call when choosing and image, your image should change.
Important Note
JQuery is a JavaScript library and isn't part of the base language. To use JQuery, you must import it in your html code. You seem to be using JQuery functions, but I don't see where you imported JQuery. This may be causing you problems/breaking your code.
If you do have JQuery imported, the above code can be rewritten using JQuery rather than vanilla JavaScript and it'll look a lot cleaner.

Add text to a textarea with JavaScript

Again I got a problem with JavaScript, but this time is something more complex.
I'm trying to make a little JavaScript text editor. Basically it's an experiment, a test and the thing should be easy. I have a <h1> HTML element, and a <p> HTML element, and both of them change, as the user writes on a <input type="text" /> element and a <textarea></textarea>.
Now, everything work fine, but there is a problem. For making a space between lines, the user can't just press Enter, but of course need to use the <br /> HTML tag.
So my idea was to make a little button that allows the user to add this tag by pressing that button.
And JavaScript just makes a variable of the actual text, save it and add at the end of it the <br />. The result should be the text written by the user plus the break HTML tag.
And this works, if the textarea is empty and if you have never written something on it. It works and work even 10 or 20 times, but if you write something on it, it just stop working, even if you delete all the text. What is the problem in the code below?
<html>
<head>
<title>Text editor</title>
<meta charset="utf-8" />
<link href="https://fonts.googleapis.com/css?family=Roboto|Roboto+Slab" rel="stylesheet">
<style>
.title {
font-family: roboto;
text-align: center;
}
.text {
font-family: roboto slab;
text-align: justify;
margin-bottom: 40px;
}
.container {
width: 80%;
}
.textarea {
width: 100%;
height: 30em;
text-indent: 0.5em;
}
.title_box {
margin: 10px;
width: 20em;
padding: 10px;
font-size: 1em;
}
</style>
</head>
<body>
<center>
<div class="container">
<h1 class="title" id="title_space">Title of the page</h1>
<p class="text" id="text_space">Content of the page.</p>
</div>
</center>
<hr />
<center><input type="text" class="title_box" placeholder="Title" id="title_box" /></center>
<textarea class="textarea" id="text_box"></textarea>
<input type="submit" value="Save" onclick="saveText()" />
<input type="submit" value="br" onclick="br()" />
<script>
function saveText(){
var title = document.getElementById("title_box").value;
var text = document.getElementById("text_box").value;
document.getElementById("title_space").innerHTML = title;
document.getElementById("text_space").innerHTML = text;
}
function br(){
var actualtext = document.getElementById("text_box").value;
var processedtext = actualtext + "<br />";
document.getElementById("text_box").innerHTML = processedtext;
}
</script>
</body>
</html>
When you're updating the text area, instead of:
document.getElementById("text_box").innerHTML = processedtext;
Use:
document.getElementById("text_box").value = processedtext;
Try to add this to your JavaScript code just before changing the text
text = text.replace(/\r?\n/g, '<br>');
Line breaks are \r\n or \n while HTML line break is <br> and that is the problem.
This in case I understood your question correctly.
Here is the code running

How to create a console like in IRC in JavaScript

I am new all around HTML and JavaScript. Now I am trying to build a simple program that get input from the command line by the user and print it on the big console window. Now when I insert a simple text it does not print nothing into the box. Is there a special object should I use?
this is my code:
</head>
<body>
<img src="img/Mellanox_logo.jpg" alt="logo" align="middle">
<h1>Menu</h1>
<div id="container1" >
<div id="console" >
<p>
<script>
function showVal(){
var tmp = document.lineform.command_line.value;
document.getElementsByName('command_line').value = tmp;
}
</script>
</p>
</div>
<div >
<form id="form1" name="lineform" >
<input id="commandline" type="text" name="command_line" placeholder="Command line" onclick="showVal()" >
</form>
</div>
</div>
</body>
</html>
this is the css:
h1{
color: black;
text-align: left;
}
p{
color: black;
text-align: left;
font-size: 20px;
}
#container1{
width:1300px ;
}
#form1{
width:1300px ;
}
#console{
border:5px solid dodgerblue;
background-color: white;
height: 650px ;
padding-left: 5px;
margin-bottom: 5px;
position: relative;
width: inherit;
}
#commandline{
width: inherit;
border: 5px solid dodgerblue;
height: 30px;
padding-left: 5px;
font-size: 18px;
position: absolute;
}
this is how the command line and the window looks like:
1.- For this case i think you should be using getElementById instead of getElementsByName.
2.- I'd recommend not using a form, but instead have the input in the div's "root".
3.- A text input doesnt have a onclick (or at least it doesn't do what you want it to do)
4.- Add a button type input that executes the code through onclick="blabla();"
5.- i'd recommend putting your script at the end of the page since it works with the DOM and you're not using JQuery.
6.- add an id to the <p> element inside of the console <div>
<body>
<h1>Menu</h1>
<div id="container1">
<div id="console">
<p id="console_content">
</p>
</div>
<div>
<input id="commandline" type="text" name="command_line" placeholder="Command line">
<input id="commandButton" type="button" name="command_button" value="confirm" onclick="showVal();">
</div>
</div>
</body>
7.- new script:
<script>
function showVal() {
var tmp = document.getElementById("commandline").value;
document.getElementById('console_content').innerHTML += (tmp + "<br/>");
}
</script>
Here's a JFiddle so you can see it works:
https://jsfiddle.net/bLehLrum/
The function you are using returns an HTMLCollection, you need to the following:
Change,
document.getElementsByName('command_line').value = tmp;
To
document.getElementsByName('command_line')[0].value = tmp;
This gets the first element in the array, notice how there is an s at the end of getElements which suggests plural. This should help you in the future.
Reading Material
getElementsByName
Exdending Script47 answer, The problem is you are taking the value from input field and setting the same value again to it, That's why you are seeing any change/affect.
If by the box you mean the console, you should change your function with this
function showVal(){
// get the value of the input
var tmp = document.getElementById('commandline').value;
// add to the innerHTML of the console the tmp value
document.getElementById('console').innerHTML += "<p>"+tmp+"</p>";
}
document.getElementById
Your code try to reassign the value of command_line with the same value.
document.lineform.command_line.value could be the same as document.getElementsByName('command_line')[0]

Would like to have a picture visually load in a custom form box I have created (also able to delete)

this one may be a little bit of a long one.
I have a form that takes a picture upload that I have customized with CSS to appear as a box. I would like it so that when the user clicks the box and are prompted to upload a picture, they can choose one and have it appear in the box (where the box will lengthen to fit the picture...the picture itself will be resized to fit the width, i have this part handled).
I am trying to make this happen with javascript, ajax, etc...:
I am including these scripts:
<link type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" media="screen" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>
<script type="text/javascript" src="/js/script.js"></script>
as well as the code found here:
http://homesconnect.me/js/jquery.form.js
script.js contains:
function validate_picture(form_data, form) {
var form = form[0];
if ( ! form.picture.value)
return false;
}
function show_picture_loader() {
$('.add_picture_label').hide().before('<img src="/images/loader.gif" class="loader"/>');
}
function hide_picture_loader() {
$('.loader').remove();
$('.add_picture_label').show();
}
function show_error_message(form_obj, message) {
$('.error').remove();
if(message != '')
{
form_obj.before('<div class="notification_msg error">' + message + '</div>');
$('html,body').animate({scrollTop: form_obj.parent().offset().top});
}
}
I also have the live script in the page itself written as so:
<script>
$(document).ready(function(){
$('.upload_picture_form').ajaxForm({
dataType: 'json', beforeSubmit: show_picture_loader, success: function(data) {
$('.pictures').prepend('<div class="profile_picture"><div class="delete_picture"><span></span></div><img src="' + data.image + '" /></div>');
$('form.account_form').prepend('<input type="hidden" name="image[]" value="' + data.image + '" />');
hide_picture_loader();
}
});
$('input.upload_picture_file_input').change(function(e) {
$('.upload_picture_form').submit();
});
$('.delete_picture span').live('click', function(e) {
$(this).closest('.profile_picture').fadeOut();
$.get('delete_picture', {image: $(this).closest('.profile_picture').find('img').prop('src')});
});
});
</script>
The form code is as so:
<div class="pictures add_pictures">
<div class="add_picture">
<div class="upload_picture">
<form action="upload.php" method="POST" enctype="multipart/form-data" name="upload_picture_form" class="upload_picture_form">
<span class="add_picture_label">+ Add a Profile Picture</span>
<input type="file" name="upload_picture_fileinput" class="upload_picture_file_input"/>
<input type="hidden" name="MAX_FILE_SIZE" value="100000"/>
<br><br><br><br><br><br><br>
<input type="submit" id="submit" value="Upload" />
</form>
</div>
</div>
</div>
Upload.php takes the image uploaded and saves it in a directory on my server, as well as saving its filename in a mysql directory. This works fine. However, the javascript I have included are not making the image appear in the box, and hence I am not able to delete it or anything either.
Here's the relevant CSS if it matters:
.content .pictures {
padding: 5px;
background: #fff;
width: 350px;
float: right;
box-shadow: 0 1px 10px rgba(0,0,0,.2);
}
.content .pictures .profile_picture img {
margin: 0;
padding: 0;
width: 350px;
}
.content .pictures .profile_picture {
position: relative;
}
.content .pictures .profile_picture .delete_picture {
position: absolute;
right: 0;
top: 0;
display: none;
}
.content .pictures .profile_picture .delete_picture span {
padding: 0;
font: bold 12px/normal 'Helvetica', 'Arial', sans-serif;
color: #444;
cursor: pointer;
background: url(/images/close.png) no-repeat;
width: 30px;
height: 29px;
display: block;
}
.content .pictures .profile_picture:hover > .delete_picture {
display: block;
}
If you feel like you see a problem or can help I would be very appreciative. I know this one is a doozy ha. Thanks.
p.s. also is there a way that I can remove the "update" button, and have it so that the image is uploaded automatically when the it is chosen by the user (as opposed to having them hit a button to do so)?
EDIT: I may have misunderstood the question. What I interpreted was an effect like that of Newgrounds.com's text boxes, which have a picture inside the text boxes, a neat aesthetic. If I have misinterpreted the question, I apologize
in css, you can put
try this:
textarea#image { background-image:url('image.jpg'); width:600; height:400 }
in this simple css example, assuming you named your input "<textarea id="image"></textarea>", the document puts a background image inside the element.
Because of jQuery's CSS affinity, you might be able to achieve the same result using just jQuery.

New to HTML,WebMatrix,Razor,etc Dealing with WebGrid

I'm am very sorry if this has been asked before but I cannot find it anywhere.
I am fairly new to web development in all aspects, but decided to create a nice little application to access and search a database from anywhere in the office.
I followed several tutorials using WebMatrix on how to set up a simple webpage etc and I have it mostly working, except for dealing with going to the next page in WebGrid. Here is what im talking about (kind of obscure but it cannot be helped)
I found two examples online about trying to use javascript and they gave me these bits of code to use..
In a file called _layout.cshtml
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Start</title>
<script src="#Href("~/scripts/jquery-1.6.2.min.js")" type="text/javascript"></script>
<link href="#Href("~/styles/site.css")" rel="stylesheet" />
#RenderSection("script", required: false);
</head>
<body>
#RenderBody();
</body>
</html>
Then a file called _PageStart.cshtml
#{
Layout = "~/_layout.cshtml";
}
Then I started creating my own site and modeling it after a few tutorials I had seen, specifically involved around the WebGrid.
This is my Default.cshtml
#{
string searchStr = Request["searchBox"];
string choice = Request["choice"];
Database db = Database.Open("NameOfDatabase");
if(choice == null)
{
choice = "DefaultColumnName"; // they choose which column they want to search
//via radio buttons
}
var queryStr = "SELECT * FROM databaseTable WHERE "+choice
+" LIKE '"+searchStr+"%'";
var data = db.Query(queryStr);
WebGrid grid = new WebGrid(source: data,
defaultSort: "Name",
rowsPerPage: 20, canPage:true, canSort:true);
if(IsPost)
{//not really doing anything here
}
}
<head>
<title>Database</title>
<style type="text/css"> " //added that because it was goofing up the color scheme..
.grid { margin: 4px; border-collapse: collapse; width: 600px; }
.head { background-color: #E8E8E8; font-weight: bold; color: #FFF; }
.grid th, .grid td { border: 1px solid #C0C0C0; padding: 1px; }
.alt { background-color: #E8E8E8; color: #000; }
.style1{ min-width: 300px; max-width:400px; font-weight:bold; white-space:nowrap; overflow:hidden;}
.style2{ min-width: 100px; max-width:150px; overflow:hidden;}
.style3{ min-width: 200px; max-width:250px; overflow:hidden; white-space:nowrap;}
.style4{ min-width:100px; max-width:200px; overflow:hidden; }
.style5{ min-width: 150px; max-width:250px; overflow:hidden; white-space:nowrap;}
.style6{ min-width: 200px; max-width:250px; overflow:hidden;}
</style>
</head>
<body onload="document.form1.searchBox.focus();">
<h1>Database</h1>
<form name="form2" method="post" action="">
<p><input type="submit" name="populate" value="Populate DB" /></p>
</form>
<div id="grid">
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("Name","Name",
format: #<p title="#item.Name.Trim()">#item.Name</p>,
style:"style1"),
//repeat to create 5 more columns exactly the same essentially
), mode: WebGridPagerModes.All
)
</div>
<form name="form1" method="post" action="Default">
<p><label for="searchBox">Search:</label>
<input type="text" name="searchBox" value="#searchStr" /></p>
<p><input type="radio" name="choice" value="Name" />
<label for="Name">Name</label></p>
<p><input type="radio" name="choice" value="choice1" />
<label for="choice1">choice1</label></p>
<p><input type="radio" name="choice" value="choice2" />
<label for="choice2">choice2</label></p>
<p><input type="radio" name="choice" value="choice3" />
<label for="choice3">choice3</label></p>
<p><input type="radio" name="choice" value="choice4" />
<label for="choice4">choice4</label></p>
<p><input type="radio" name="choice" value="choice5" />
<label for="choice5">choice5</label></p>
<p><input type="submit" name="Submit" value="Submit" /></p>
</form>
</body>
#section script{
<script type="text/javascript">
$(function () {
$('th a, tfoot a').live('click', function () {
$('form1').attr('action', $(this).attr('href')).submit()
return false;
});
});
</script>
}
That is my website in general.. Well whenever you enter say someones name and a choice and click submit, it queries it fine, but if there are more than 20 names then when i click on the second page it essentially redoes my orginial query to get all the names and i loose what they typed into the text field and which option they choose.
The script I found is supposed to fire whenever they user clicks on the links that the webgrid creates to go to the next page, and put the data from form1 into something so that I can pull it back out when the page is loaded again.
I have looked and looked online for a solution and if I have found one I havent understood how it works.. so if anyone out there understands what I'm talking about and could help me out it would be greatly appreciated.
Thanks!
Take a read of Mikesdotnetting The WebGrid - Efficient Paging and Sorting at
http://mikesdotnetting.com/Article/181/The-WebGrid-Efficient-Paging-And-Sorting-With-SQL-CE-4.0
Should give you some ideas to work with.

Categories