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).)
Related
I am working on a social networking site where user Posts are displayed on the home page. They can be liked and commented on. If a post is liked,
it updates the like table through AJAX and have like count incremented by one.
AJAX code:
$(".mlike").click(function () {
$(".murconform").submit(function(e){
return false;
});
var $this=$(this);
var post_id = $(this).val();
var user_id = $(".user_id").text();
alert('Post: '+post_id +' User: '+user_id);
var request = $.ajax({
url: "likes.php",
type: "POST",
data: { post : post_id , user : user_id },
dataType: "html"
});
request.done(function( msg ) {
$this.prev('.likecount').html( msg );
});
});
In the home.php page I have some PHP variables ($userID, $userName) that are data fetched from MySQL and they all work fine but they
don't work with the variables ($viewedUserID, $viewedUserName) in the user.php. In the user.php, only posts related to profile been
viewed are fetched but when you press the like button and try to comment on any of the post it says undefine variables; $viewedUserID, $viewedUserName. And these
variables are defined from the beginning of the page in user.php.
I have been thinking of what might be the possible cause of this and was also thinking the AJAX was suppossed to have effect on the clicked
button only.
NOTE: The alert works just fine.
Thanks in advance.
Was going to write as a comment, but I guess an answer will be clearer:
Ajax
How does AJAX work?
I think you're getting confused with what Ajax's job is. The problem is Ajax is literally just a connector between your front-end (JS / HTML) and back-end (PHP / Rails etc)
Your statements that "Ajax isn't updating MYSQL" lead me to believe you're relying on Ajax to update your table. It won't
Your table will update by using PHP, which is why most of the comments are focused on the PHP & not the JS
PHP
Your Ajax needs to send the correct data to PHP, but then it's your server-side scripts' job to sort it all out, sending a worthy response
Your JS looks like it will work well, but I think your problem will be with your backend. If you update your question with your PHP you'll get a lot more clearer answers!
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
}
});
});
Is it possible to run a MySQL query using jQuery? I'm trying to emulate the functionality of voting on SE sites.
The vote counter on SE automatically updates without the need to reload the page (which is what I currently have, a hidden form that re-submits to the current page but runs a small block on PHP that updates the score of a question in the database). I'm assuming that is being done using Javascript/jQuery seeing as it is dynamic.
How can I do this? Is there a library which makes it easy and simple (like PHP)?
You can use ajax to call a server page (PHP / ASP /ASP.NET/JSP ) and in that server page you can execute a query.
http://api.jquery.com/jQuery.ajax/
HTML
<input type='button' id='btnVote' value='Vote' />
Javascript
This code will be excuted when user clicks on the button with the id "btnVote". The below script is making use of the "ajax" function written in the jquery library.It will send a request to the page mentioned as the value of "url" property (ajaxserverpage.aspx). In this example, i am sending a querystring value 5 for the key called "answer".
$("#btnVote").click(function(){
$.ajax({
url: "ajaxserverpage.aspx?answer=5",
success: function(data){
alert(data)
}
});
});
and in your aspx page, you can read the querystring (in this example, answer=5) and
build a query and execute it againist a database. You can return data back by writing a Response.Write (in asp & asp.net )/ echo in PHP. Whatever you are returning will be coming back to the variable data. If your query execution was successful, you may return a message like "Vote captured" or whatever appropriate for your application. If there was an error caught in your try-catch block, Return a message for that.
Make sure you properly sanitize the input before building your query. I usually group my functionalities and put those into a single file. Ex : MY Ajax page which handles user related stuff will have methods for ValidateUser, RegisterUser etc...
EDIT : As per your comment,
jQuery support post also. Here is the format
$.post(url, function(data) {
alert("Do whatever you want if the call completed successfully")
);
which is equivalent to
$.ajax({
type: 'POST',
url: url,
success: function(data)
{
alert("Do whatever you want if the call completed successfully")
}
});
This should be a good reading : http://en.wikipedia.org/wiki/Same_origin_policy
It's just a few lines in your favorite language.
Javascript
$.post('script.php', { id: 12345 }, function(data) {
// Increment vote count, etc
});
PHP (simplified)
$id = intval($_POST['id']);
mysql_query("UPDATE votes SET num = num + 1 WHERE id = $id");
There are many different ways to accomplish this.
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);
}
}
Hey all. I was fortunate enough to have Paolo help me with a piece of jquery code that would show the end user an error message if data was saved or not saved to a database. I am looking at the code and my imagination is running wild because I am wondering if I could use just that one piece of code and import the selector type into it and then include that whole json script into my document. This would save me from having to include the json script into 10 different documents. Hope I'm making sense here.
$('#add_customer_form').submit(function() { // handle form submit
The "add_customer_form" id is what I would like to change on a per page basis. If I could successfully do this, then I could make a class of some sort that would just use the rest of this json script and include it where I needed it. I'm sure someone has already thought of this so I was wondering if someone could give me some pointers.
Thanks!
Well, I hit a wall so to speak. The code below is the code that is already in my form. It is using a datastring datatype but I need json. What should I do? I want to replace the stupid alert box with the nice 100% wide green div where my server says all is ok.
$.ajax({
type: "POST",
url: "body.php?action=admCustomer",
data: dataString,
success: function(){
$('#contact input[type=text]').val('');
alert( "Success! Data Saved");
}
});
Here is the code I used in the last question, minus the comments:
$(function() {
$('#add_customer_form').submit(function() {
var data = $(this).serialize();
var url = $(this).attr('action');
var method = $(this).attr('method');
$.ajax({
url: url,
type: method,
data: data,
dataType: 'json',
success: function(data) {
var $div = $('<div>').attr('id', 'message').html(data.message);
if(data.success == 0) {
$div.addClass('error');
} else {
$div.addClass('success');
}
$('body').append($div);
}
});
return false;
});
});
If I am right, what you are essentially asking is how you can make this piece of code work for multiple forms without having to edit the selector. This is very easy. As long as you have the above code included in every page with a form, you can change the $('#add_customer_form') part to something like $('form.json_response'). With this selector we are basically telling jQuery "any form with a class of json_response should be handled through this submit function" - The specific class I'm using is not relevant here, the point is you use a class and give it to all the forms that should have the functionality. Remember, jQuery works on sets of objects. The way I originally had it the set happened to be 1 element, but every jQuery function is meant to act upon as many elements as it matches. This way, whenever you create a form you want to handle through AJAX (and you know the server will return a JSON response with a success indicator), you can simply add whatever class you choose and the jQuery code will take over and handle it for you.
There is also a cleaner plugin that sort of does this, but the above is fine too.
Based on your question, I think what you want is a jQuery selector that will select the right form on each of your pages. If you gave them all a consistent class you could use the same code on each page:
HTML
<form id="some_form_name" class="AJAX_form"> ... </form>
Selector:
$('form.AJAX_form")