Generic Way of Capturing Page Title, Control labels - javascript

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

Related

What's a correct way of retrieving data?

I've posted a few questions seeking clarity in small details about the do's and don't's of javascript, ajax and html. And here's one more. I'm creating a list with javascript by the usage of an api. When making the list I get the correct values for the text. When pressing the button in the row I'm getting the alert message. But the new entry is blank.
Can I add data this way (a for loop getting info and building a string with it baked in)?
OR is it the way I retrieve and store data that is wrong?
EDIT: My data is undefined. Don't I get a string from: data.items[i].Info.drivers?
Part of javascript that talks to an api and gives drivers and cars. This segment is part of a for loop.
...+'<h5><data-title="'
+data.items[i].Info.drivers+'">'
+data.items[i].Info.drivers
+'</data></h5>'
+'<p class="subtitle"><data-title="'
+data.items[i].Info.cars+'">'
+data.items[i].Info.cars
+'</data></p>'
+ '<input class="adding"type="button" name="vehicle" value="Add book">'...
My add code (javascript in html):
$(document).on('click', '.adding',function() {
window.alert("active");
var $this = $(this);
var drivers = $(this).data('drivers');
var cars = $(this).data('cars');
alert($(this).data('drivers')); //<----gives alert, says Undefined
$.ajax({
url: 'insert.php',
type: 'POST',
data: {
'driver': drivers,
'car': cars
},
success: function(msg) {
window.alert("success triggered");
}
});
});
This is referring to the button. By putting the data attributes in the button in the same way the problem is solved.

PHP Javascript Single Form Call Submit to Two Forms

Have you seen?
submit a form inside another form
Submitting form data to two locations using Javascript and PHP?
None of them actually answer the question.
Let me explain the scenario. I have a form that asks for Name, Email and Phone Number and it needs to be submitted to TWO locations on two different vendors.
1) Aweber
2) The Company
One possibility is to create a Javascript piece of code that when people click 'submit' it sends it to two form calls in two different browser windows (that would be my preferred method)
The second possibility would be to send it first to Aweber (autorespnder) and then pass the variables to a custom PHP page. Fetch the variables with $_GET and then pass those into an automatic form submit that passes those on to the 2nd form that goes to the company.
For example - I can submit the form to Aweber first and then pass the results back to form.php:
$name = $_get['name'];
$email = $_get['email'];
$phone = $_get['phone'];
What would the rest of the form look like with Curl or javascript?
I tried passing the variables into the company post form. It won't accept any GET commands - it only accepts a POST command, so CURL is probably not going to work, (unless there's a way to POST a form via CURL?)
Anyone have an elegant solution that doesn't look bad to end users?
What ideas do you have? Thanks in advance!
Without any real data to go on or real forms to call, this should give a basic idea of how to do it with AJAX and jQuery.
*Updated
I updated the answer to show how to pass the form variables as a post rather than a get.
HTML
<form id="test-form">
<input type="text" id="name" name="name"/>
<input type="submit" value="submit"/>
</form>
<p class="response1">
Response 1 goes here
</p>
<p class="response2">
Response 2 goes here
</p>
jQuery
$("#test-form").on("submit", function(e) {
e.preventDefault(); //stops the form from actually submitting
var root = 'https://jsonplaceholder.typicode.com';
$.ajax({
url: root + '/posts/1',
method: 'POST',
data: $("#test-form").serialize()
}).then(function(data) {
if(data) {
$(".response1").text(data.title);
$.ajax({
url: root + '/posts/2',
method: 'POST',
data: $("#test-form").serialize()
}).then(function(data) {
if(data) {
$(".response2").text(data.title);
}
});
}
});
})
Obviously you'd have to set the URL's correctly and pass the post data, which isn't happening here because I don't have an API to query that accepts post data. After the first form submits, it sends the data to the second form. How you handle the data is going to depend on what the responses are from the servers.
Fiddle: https://jsfiddle.net/calder12/t0fos3kk/1/

SQL/PHP updates multiple rows when client modifies javascript function parameter for two buttons to be the same

I am trying to create a vote up functionality where a user can view many comments can and vote each of them. Each vote up button looks like this,
<input type="button" value="UpVote93" id="upvote_55" onclick="upvote('commendID1')">
<input type="button" value="UpVote42" id="upvote_56" onclick="upvote('commendID2')">
The upvote(param) function is an ajax call like this,
function upvote(x) {
$.ajax({
url: 'dbHandler.php',
type: 'post',
data: {
"action": 'UPVOTE_COMMENT',
"unique_answer_id": x
},
success: function(data){
alert(1);
},
failure: function(data){
alert(0);
},
complete: function(data) {
alert(2);
}
});
}
and the php update statement looks like this,
$query = $conn->query("UPDATE answers SET vote_count = vote_count+1 WHERE commentID='$commentID' LIMIT 1>
The problem is that, the user can change the second button upvote parameter to "commentID1". Now, when he clicks the second button, two rows are updated in the the mysql database for the both comments, i.e. commentID1 and commentID2.
I tried the same thing on voting tutorial sites and was able replicated the issue. However, when I tired on sites like Quora, the bug was not there. What is the best approach for this functionality?
You could try turning your inputs into html arrays. PHP is good at reading those. Something like:
<input name="MyArray[]" />
<input name="MyArray[]" />
Then you can read the input as an array and process it like an array.
Are you referring to users being able to vote for a comment more than once?
If your users have to be logged in, then you can easily store their user id next to the vote in the database to make sure they only vote once per comment.
If login is not required, you can either store their IP address in the DB, or save it in their session (or possibly a cookie) that they have already voted.

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 can I hit my database with an AJAX call using 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);
}
}

Categories