How can I hit my database with an AJAX call using javascript? - javascript

I am pretty new at this stuff, so bear with me.
I am using ASP.NET MVC.
I have created an overlay to cover the page when someone clicks a button corresponding to a certain database entry. Because of this, ALL of my code for this functionality is in a .js file contained within my project.
What I need to do is pull the info corresponding to my entry from the database itself using an AJAX call, and place that into my textboxes. Then, after the end-user has made the desired changes, I need to update that entry's values to match the input. I've been surfing the web for a while, and have failed to find an example that fits my needs effectively.
Here is my code in my javascript file thus far:
function editOverlay(picId) {
//pull up an overlay
$('body').append('<div class="overlay" />');
var $overlayClass = $('.overlay');
$overlayClass.append('<div class="dataModal" />');
var $data = $('.dataModal');
overlaySetup($overlayClass, $data);
//set up form
$data.append('<h1>Edit Picture</h1><br /><br />');
$data.append('Picture name: ');
$data.append('<input class="picName" /> <br /><br /><br />');
$data.append('Relative url: ');
$data.append('<input class="picRelURL" /> <br /><br /><br />');
$data.append('Description: ');
$data.append('<textarea class="picDescription" /> <br /><br /><br />');
var $nameBox = $('.picName');
var $urlBox = $('.picRelURL');
var $descBox = $('.picDescription');
var pic = null;
//this is where I need to pull the actual object from the db
//var imgList =
for (var temp in imgList) {
if (temp.Id == picId) {
pic= temp;
}
}
/*
$nameBox.attr('value', pic.Name);
$urlBox.attr('value', pic.RelativeURL);
$descBox.attr('value', pic.Description);
*/
//close buttons
$data.append('<input type="button" value="Save Changes" class="saveButton" />');
$data.append('<input type="button" value="Cancel" class="cancelButton" />');
$('.saveButton').click(function() {
/*
pic.Name = $nameBox.attr('value');
pic.RelativeURL = $urlBox.attr('value');
pic.Description = $descBox.attr('value');
*/
//make a call to my Save() method in my repository
CloseOverlay();
});
$('.cancelButton').click(function() {
CloseOverlay();
});
}
The stuff I have commented out is what I need to accomplish and/or is not available until prior issues are resolved.
Any and all advice is appreciated! Remember, I am VERY new to this stuff (two weeks, to be exact) and will probably need highly explicit instructions.
BTW: overlaySetup() and CloseOverlay() are functions I have living someplace else.
Thanks!

You cannot (and shouldn't, ever) connect to the database directly from Javascript. Even if you theoretically could (I suppose nothing's impossible) you shouldn't; you'd have to open the DB up to the public in a way that would make anyone dedicated to security pull your hair out once they'd finished with their own.
What you should do instead is find some intermediary that can act as a proxy for the database. Almost in the same way that ASP.NET does, if that's a good enough hint.
If it's not:
Create a custom ASP.NET control and have it fill your form data server-side. Have its post-back handle validation and then updating the database server-side.

I use jQuery (which uses an HTTP Request object under the covers).
You would of course have to create a web service that it talks to, that does your database access. You should look at XML and JSON as alternatives to format the data you're passing.

This sounds like the perfect task for a WCF Data Service. This basically lets jQuery talk directly (almost) to your database. Check out http://stephenwalther.com/blog/archive/2010/03/30/using-jquery-and-odata-to-insert-a-database-record.aspx for an example.

The ajax call can be done with jQuery and it would send a Post to a controller action. The controller would accept the Post and perform persistence.
jQuery
$('.saveButton').click(function() {
//prepare your content
var data = {
name: $nameBox.val(),
relativeUrl: $urlBox.val(),
description: $descBox.val()
};
//make a call to my Save() method in my repository
$.ajax({
url: "/mycontroller/action",
data: JSON.stringify(data),
type: "POST",
cache: false,
contentType: "application/json; charset=utf-8"
}).done(function(data) {
//do something when request returns
CloseOverlay();
});
});
Controller
public class MyController : BaseController
{
[HttpPost]
public ActionResult Action(string name, string relativeUrl, string description)
{
//not sure what repository you're using.
//replace this with your actual repository implementation
var repository = new MyRepository();
repository.Save(name, relativeUrl, description);
}
}

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.

Thymeleaf page refresh followup - Now with AJAX

As a followup to my earlier question about using Thymeleaf and preventing page refresh:
http://forum.thymeleaf.org/Preventing-page-refresh-Thymeleaf-amp-Spring-MVC-td4029155.html
Basically I had a working Spring MVC app that uses Thymeleaf to save form data. When the user saves the data the page would refresh (since I wanted to leave them on the page for more edits) and I wanted to eliminate the page refresh.
I have coded up some Javascript to use JQuery Ajax to post the data to my Spring MVC Controller. The trick seemed to be to not use a submit button, just a regular button and bind a JS function to it for sending the data to the server.
It all seems to work perfectly, but I want to make sure I understand what is happening. In particular I'm wondering if Thymeleaf is now redundant. I don't think it is because when I initially load the page Thymeleaf is still bound to the data bean. From using the debugger on the server side in the controller it looks like the post request calls the mapped method and passes in the data to the model.
I would appreciate your comments on whether or not this is the correct way to accomplish this.
Finally, how do I handle an error, say for example the repository fails to persist the data for any reason?
Thanks very much.
Here are the important parts of the form:
<FORM id="adminDataForm" action="#" th:action="#{/admin_ajax}" th:object="${adminFormAjax}" method="post">
<input type="button" value="Save Changes" id="post" onClick="sendData()" />
Here is the Javascript:
function sendData()
{
$.ajax(
{
type: "POST",
data: $("#adminDataForm").serialize(),
cache: false,
url: "/admin_ajax",
success: function(data)
{
alert("Your changes have been saved");
},
error: function()
{
alert("Error - Data not saved");
}
});
}
Here is the controller:
#SessionAttributes("adminFormAjax")
#Controller
public class TestController
{
final static protected long INDEX_RA = 2L;
#Autowired
private AdminDataRepository rep;
#RequestMapping(value="/admin_ajax", method=RequestMethod.GET)
public String adminFormAjax(Model model)
{
AdminData ad = rep.findById(INDEX_RA);
// If there is no configuration record, create one and assign the primary key
if(ad == null)
{
ad = new AdminData();
ad.setId(INDEX_RA);
}
model.addAttribute("adminFormAjax", ad);
return "adminFormAjax";
}
#RequestMapping(value="/admin_ajax", method=RequestMethod.POST)
public #ResponseBody AdminData adminSubmit(#ModelAttribute("adminFormAjax") AdminData ad, Model model)
{
rep.save(ad);
model.addAttribute("adminFormAjax", ad);
return ad;
}
}
So breakdown of answer.
Thymeleaf not redundant, it will still render the HTML page prior to sending to client. Ajax just does the further processing for you on client side.
You can use submit button as well, you just need to ensure your form is properly structured and you have javascript listening for your submit button click e.g.
$("#submitbutton").on('click', function (){//do stuff});
You handle any and all exceptions/issues within your Ajax controller as you would with standard controller. You need to separate issue handling at different levels. e.g. respository level issues should be managed at rep level, controller/pojo should be at controller level (or pojo if you using one for processing). You should also be capturing any exceptions through a global medium (e.g. ControllerAdvice).
Any issues/errors you pick up you should be communicating back via your return call in adminSubmit, and managing the relevant client response in ajax.

Generic Way of Capturing Page Title, Control labels

One of our customers has a new requirement to dynamically capture the page/screen title and the labels of all the controls(textboxes, checkboxes, radio buttons, normal buttons,link,images,menu/menu items) on the page the users interacts with and then push them to an excel file.
If customer navigates/opens a page A and sets a value in the textbox Name = John , enables the checkboxChBox/radio button Rbutton and then finally clicks save/submit button, then the following output is being expected. User Action and Results being the first 2 columns of the Excel file.
**User Action** **Result**
Open Page/Screen A Page/Screen A is displayed
Set textbox Name = John Field Name is set successfully
Set ChBox = true ChBox is enabled successfully
Set Rbutton = true Rbutton is enabled successfully
Click Submit button Page B is displayed
Just wondering if it is possible to accomplish this and generic way of capturing the user interactions of any page.
Just an idea : you could listen all events (with jquery, for example), and then post an ajax request for each 'interesting' event (you have to filter...), store it in a database, and then add an 'export' function in csv or excel format.
Maybe some performance issues, it depends on the amount of pages, events and users...
The idea to use class name to filter is good, thanks to Hasan Iqbal Anik.
Javascript doesn't have access to writing files in hard drive. However you can capture the data, make a model and then store it in the server using ajax calls.
Some ideas:
Use a layout or master page that is rendered throughout the application views.
Give same class name for all the page labels, buttons, checkboxes and anything you need to store information about.
Use some jquery magic in the master/layout page to get the values of those elements and make an array.
Send that array through ajax call to the server.
Now you can get tons of examples of how to get element values using jquery. I'm saving you from giving all that. Hope that helps... :D
//edit: i'm trying to extend my answer as per steve requested.
<form action="someAction" id="myForm">
Name: <input type="text" class="Name">
Checkbox: <input type="checkbox" class="ChBox"/>Click this box
RButton: <input class="Rbutton" type="radio" />
Submit: <input type="submit" class="submit"/>
</form>
Now some jquery:
$(function() {
$(".submit").click(function(){
var dataToSend = new Object();
dataToSend.pageUrl = window.location.pathname + " is displayed";
if ($(".Name").val().length > 0) {
dataToSend.Name = "Field Name is set successfully";
}
else {
dataToSend.Name = "Field Name is empty";
}
if($(".ChBox").is(':checked')){dataToSend.ChBox = "ChBox is enabled successfully";}
else{dataToSend.ChBox = "ChBox is not enabled";}
if($(".Rbutton").is(':checked')){dataToSend.Rbutton = "Rbutton is enabled successfully";}
else{dataToSend.Rbutton = "Rbutton is not checked";}
dataToSend.Submit = $("#myForm").attr['action'] + " is displayed";
});
//now send it to the server via ajax
$.ajax({
type: "POST",
url: "your server action url that would make excel file with these data",
data: dataToSend,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
//do as you wish
}
});
});

update table cell

this is my html form:
<form name="input" action="html_form_action.asp" method="get">
<input type="checkbox" id="mycheckbox">Don't show me again<br>
<input type="submit" id="Submit">
</form>
I have a table, is called: "mytable". this table contains: name(string), box(boolean).
I tried to do the next thing:
when the user checked the box of don't show me again, I want to update the box of the table (assuming the row with id=6).
p.s. the box of the table inits to False.
so I have to do something like:
$("#submit").click(function() {
if($("#mycheckbox").is(':checked')) {
//here I have to update the table in the database
}
});
how can I do that?
I found examples with php but I don't want to do it with php.
UPDATE:
based on your answers, I want to do it with Ruby-on-rails.
I found this:
update_sql = "update mytable set box = TRUE where id = 6"
affected_rows = Job.connection.update(update_sql)
any help appreciated!
You need to create a controller that accepts the ajax request but first update the js to this one.
# js
$("#submit").click(function() {
$.ajax({
url: '/my_tables/' + <id of resource to update>,
type: 'PUT',
data: { my_table: { box: $("#mycheckbox").is(':checked') } }
});
});
create a controller called MyTablesController
# my_tables_controller.rb
class MyTablesController < ActionController::Base
def update
#my_table = MyTable.find params[:id]
#my_table.update_attributes params[:my_table]
# do something else here like a redirect ...
end
end
that's the gist of it. If you can't make it work, you may need to start with more basic tutorials. Good luck!
$("#submit").click(function() {
if($("#mycheckbox").is(':checked')) {
$.ajax({
url: 'post.php',
cache: false,
success: function() {
alert("done");
}
});
}
});
You can use $.ajax to update your table in database. Just create post.php file and set up a query in there which updates table.
Also, PHP uses mysqli to connect to database in latest versions. mysql_ functions are deprecated.
Unfortunately, you need some sort of server script like php to communicate with mySQL :(
Query mySQL natively from JQuery without the need for PHP etc
You can use any language you like on the server (even JavaScript), but you need server side code to process the HTTP request (which you can make from JavaScript using XMLHttpRequest) and interact with the database.
(Note: "any language you like" is limited by what is installed or what you can install on your server (or a server you move to).)

Using JSON to store multiple form entries

I'm trying to create a note taking web app that will simply store notes client side using HTML5 local storage. I think JSON is the way to do it but unsure how to go about it.
I have a simple form set up with a Title and textarea. Is there a way I can submit the form and store the details entered with several "notes" then list them back?
I'm new to Javascript and JSON so any help would be appreciated.
there are many ways to use json.
1> u can create a funciton on HTML page and call ajax & post data.
here you have to use $("#txtboxid").val(). get value and post it.
2> use knock out js to bind two way.and call ajax.
here is simple code to call web app. using ajax call.
var params = { "clientID": $("#txtboxid") };
$.ajax({
type: "POST",
url: "http:localhost/Services/LogisticsAppSuite.svc/Json/GetAllLevelSubClients",
contentType: 'application/json',
data: JSON.stringify(params),
dataType: 'json',
async: false,
cache: false,
success: function (response) {
},
error: function (ErrorResponse) {
}
I have written a lib that works just like entity framework. I WILL put it here later, you can follow me there or contact me to get the source code now. Then you can write js code like:
var DemoDbContext = function(){ // define your db
nova.data.DbContext.call(this);
this.notes=new nova.data.Repository(...); // define your table
}
//todo: make DemoDbContext implement nova.data.DbContext
var Notes = function(){
this.id=0; this.name="";
}
//todo: make Note implement nova.data.Entity
How to query data?
var notes = new DemoDbContext().notes.toArray(function(data){});
How to add a note to db?
var db = new DemoDbContext();
db.notes.add(new Note(...));
db.saveChanges(callback);
Depending on the complexity of the information you want to store you may not need JSON.
You can use the setItem() method of localStorage in HTML5 to save a key/value pair on the client-side. You can only store string values with this method but if your notes don't have too complicated a structure, this would probably be the easiest way. Assuming this was some HTML you were using:
<input type="text" id="title"></input>
<textarea id="notes"></textarea>
You could use this simple Javascript code to store the information:
// on trigger (e.g. clicking a save button, or pressing a key)
localStorage.setItem('title', document.getElementById('title').value);
localStorage.setItem('textarea', document.getElementById('notes').value);
You would use localStorage.getItem() to retrieve the values.
Here is a simple JSFiddle I created to show you how the methods work (though not using the exact same code as above; this one relies on a keyup event).
The only reason you might want to use JSON, that I can see, is if you needed a structure with depth to your notes. For example you might want to attach notes with information like the date they were written and put them in a structure like this:
{
'title': {
'text':
'date':
}
'notes': {
'text':
'date':
}
}
That would be JSON. But bear in mind that the localStorage.setItem() method only accepts string values, you would need to turn the object into a string to do that and then convert it back when retrieving it with localStorage.getItem(). The methods JSON.stringify will do the object-to-string transformation and JSON.parse will do the reverse. But as I say this conversion means extra code and is only really worth it if your notes need to be that complicated.

Categories