Amateur here... I have an SQL query on an JS page and need to pass the variables onto a PHP webpage. I know how to pass the more simple variables through the URL, but am struggling in finding and executing the most efficient way to passing a long string, i.e. the text description of a point
Here on the JS side, I have:
downloadUrl("php_genxml1.php", function(data) {
var xml = data.responseXML;
var points = xml.documentElement.getElementsByTagName("point");
for (var i = 0; i < points.length; i++) {
var id = points[i].getAttribute("id");
var name = points[i].getAttribute("name");
var description = points[i].getAttribute("description");
var url = "PHPWebPage.php?name=" + name + "&id=" + id;
To get the id from the URL, I have used stuff like the standard
$id=$_GET['id'];
I know I could re run a query based off that id from the URL, but that surely doesn't sound the most efficient. I know my options (array, sessions, etc) for whatever that's worth.
Thanks for any help, C
Try POSTing the data instead. It also makes it less likely for someone to just edit your URL in the browser to get data they're not supposed to have.
Related
I've a div which contains a list of clients pulled from Mysql.
On the same page I have a jquery dialog box which pops up to allow a user to add a new client.
What I want to happen is that when the user adds a new client the containing the list reloads so the new client is available.
Is there a way to simply reload the div without using the Load() function as this is causing errors when I redeclare my classes that populate the list ?
Of course. Without looking at your code, your confusion here suggests that you don't understand "Separation of Concerns". Separate the process of getting information from the process of displaying that information. When the user enters new information, add that to javascript array or object of information you got from the server and also send that off to the server to be updated in the database. Then run the display function again using the updated information to include the new information. Ideally, the display process will use existing markup if it can, rather than deleting it all and recreating it all just to add one item. Here's a very basic example (click here). Ideally, you would take this concept and expand on it to make it optimally efficient and organized.
Here's the sample code from my jsbin. Please keep in mind this is just to get you started.
var info = [1,2,3,4,5]; //this is what you got from your ajax call to the server
function render(element, info) {
//this is a lazy system that recreates/replaces all the markup each time. I suggest doing this more efficiently, but that is work for you to do :)
var frag = document.createDocumentFragment();
var len = info.length;
for (var i=0; i<len; ++i) {
var p = document.createElement('p');
p.textContent = info[i];
frag.appendChild(p);
}
element.innerHTML = '';
element.appendChild(frag);
}
var targetElem = document.getElementById('targetElem');
render(targetElem, info);
var addButton = document.getElementById('add');
var input = document.getElementById('infoInput');
addButton.addEventListener('click', function() {
info.push(input.value); //update the information
render(targetElem, info); //render the updated information
});
Either of these should give you success.
success: function(userinfos) {
$("#users").append($('<tr><td>'+userinfos+'</td></tr>'))
display_message("user added");
}
$.ajax({
type: "GET",
url: "ht.tp://127.0.0.1:8000/result/?age="+ ageData +"&occasion="+
occasionData +"&relationship="+ forData +"#",
success: function (response) {
$("#testDIV").html(response);
}
});
This is a followup to a question I asked yesterday on the Google Apps Script Office Hours Hangout.
The goal of my final script is to create an election process for student elections at the high school where I work using Google Forms. The script has three parts: 1) Create Unique "Voting IDs" (a random 6-digit code) 2) Merge the student data (Name, Homeroom, & Voting ID) on with a template document that will create specific voting instruction for each student. (i.e. an old-fashioned mail merge) 3) Verify the results by checking Voting ID's and removing duplicate votes.
The part of the script that I am having trouble with is the student data merge (step 2). The first dataset is the only one that works. The rest show up as "DocumentBodySection". I have a feeling it is either how I am copying the text from the Document Template or how I am adding the text to the new document.
Spreadsheet w/ Data: https://docs.google.com/spreadsheet/ccc?key=0AierVcXWELCudFI1LU10RnlIVHNsUm11a0dDWEV6M1E
Document Template: (see followup comment for url)
Document Created by Script: https://docs.google.com/document/d/12r2D9SpIVmQYVaasMyMWKjHz6q-ZZyIMEBGHTwlQct8/edit
//Get Settings & Data
ss = SpreadsheetApp.getActiveSpreadsheet();
source_sheet = ss.getSheetByName("Student Data");
settings_sheet = ss.getSheetByName("SETTINGS");
results_column = settings_sheet.getRange("B19").getValue();
source_column = settings_sheet.getRange("B18").getValue();
source_lastrow = source_sheet.getLastRow();
docTemplateID = settings_sheet.getRange("B13").getValue();
docCopyName = settings_sheet.getRange("B14").getValue();
//Merge Student Data with Document
function SendDataMerge () {
// Open docTemplate and Copy Contents to entryTemplate
var docTemplate = DocumentApp.openById(docTemplateID);
var entryTemplate = docTemplate.getActiveSection();
docTemplate.saveAndClose();
// Make a NEW copy of docTemplate
var docTemplate = DocsList.getFileById(docTemplateID);
var docCopy = DocsList.copy(docTemplate, docCopyName);
var docCopyID = docCopy.getId();
// Create Array of Student Data (First, Last, Grouping, VID)
var data = source_sheet.getRange("A2:D"+source_lastrow).getValues();
// Open docCopy for Editing & Clear Contents
var doc = DocumentApp.openById(docCopyID);
var docText = doc.editAsText();
// Run through Student Data
for(var i=0; i<5 /*data.length*/; i++) { //For testing, limit this to 5 entries
var lastName = data[i][0];
var firstName = data[i][1];
var grouping = data[i][2];
var vid = data[i][3];
docText.replaceText('keyLastName', lastName);
docText.replaceText('keyFirstName', firstName);
docText.replaceText('keyGrouping', grouping);
docText.replaceText('keyVID', vid);
docText.appendText('\n*** Appended Text (End of entry) ***');
docText.appendText(entryTemplate);
}
// Save and Close
doc.saveAndClose();
}
I worked around this issue by creating a copy of the template, doing the text replacement and then appending the template elements from the original document into the copy. In particular, I used: var copyTables = templateDoc.getTables(); to fetch and store the tables (as all of my template data was contained in a table) and copyDoc.appendTable(copyTables[0].copy() ); to append the copy (the .copy() at the end seems to work the real magic). This provides the flexibility of updating the template in the friendly Documents interface without having to see a programmer.
I think the problem is with this line:
docText.appendText(entryTemplate);
The variable entryTemplate holds a DocumentBodySection, which is why you are seeing that in the output. If you are trying to append another copy of the original template text you'll need to store that before you enter the loop.
I agree with Eric that appendText(entryTemplate) isn't going to do what you want it to do.
Since you're trying to create one large document with all the students, using a "template" and replacing the text isn't going to work well. I'd suggest instead, creating the "template" in code using the api calls that produce the formatting you want. Then it makes it simple to keep appending new pages of student instructions. Although I think you may run into slowness when the document gets large... I don't know how many students you have.
Ok, so I'm learning web design as a co-op at a company. However, the department I'm in is lacking in knowledgeable people in web design. So here we go...
Building a site that will allow the department to manage PTO. I want to implement ajax b/c the main page will have a calendar system so the manager can view the PTO week by week. As a precursor to that, I'm attempting to implement ajax with the "add Employee" page for practice.
However, I can't seem to figure out what I'm missing (aka, why it's not doing anything)
This page just needs to add the new employee to the database. No display needed.
The main page just has 4 text fields and I get the information from those fields in javascript like so
var firstName = document.getElementById("firstNameField");
var lastName = document.getElementById("lastNameField");
var manager = document.getElementById("managerField");
var networkID = document.getElementById("networkIDField");
Simple enough so far.
So I set up the ajax code like so, (this is gathered from what I've read.
var url = "addEmpJSP.jsp?firstNameField=" + escape(firstName)+"&lastNameField="+escape(lastName)+"&managerField="+escape(manager)+"&networkIDField="+escape(networkID);
xmlhttp.open("POST",url,true);
xmlhttp.onreadystatechange=dummy;
xmlhttp.send(null);
This is the part where I'm assuming it's correct as I'm still learning ajax and how it works. I don't think I need to handle a response as I simply want the called jsp file to automatically do whats needed. (if that's possible).
The jsp file looks like this
<%
ResultSet rsEmpl;
Connection connection1 = getDBConnection();
Statement statment1=connection1.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
String fName = request.getParameter("firstNameField");
String lName = request.getParameter("lastNameField");
String manager = request.getParameter("managerField");
String networkID = request.getParameter("networkIDField");
Int empId = 0;
String EditEmplSQL = "select * from PTO_employee";
rsEmpl=statment1.executeQuery(EditEmplSQL);
rsEmpl.last();
empId = rsEmpl.getRow() - 1;
statement1.execute("INSERT INTO PTO_employee VALUES ("+empID+","+lName+","+fName+","+0+","+2+","+networkID);
%>
I have a button on the page that executes the javascript function that contains the ajax info. I'm avoiding jquery atm b/c I'm trying to understand this stuff and how it works before I attempt to use "shortcuts" like jquery. I'm working towards a degree in Software Engineering so understanding this stuff is my priority, not getting it done.(that's just a bonus) If you need anymore information I can provide it. Sorry for my lack of knowledge and if this is completely off base then :(
The main page just has 4 text fields and I get the information from those fields in javascript like so
var firstName = document.getElementById("firstNameField");
var lastName = document.getElementById("lastNameField");
var manager = document.getElementById("managerField");
var networkID = document.getElementById("networkIDField");
That gives you whole HTML DOM elements back, not the values of those elements. HTML DOM elements are like Java classes, having properties, methods and so on. Assuming that it are HTML input elements like <input>, then use their value property instead to get the value. So:
var firstName = document.getElementById("firstNameField").value;
var lastName = document.getElementById("lastNameField").value;
var manager = document.getElementById("managerField").value;
var networkID = document.getElementById("networkIDField").value;
So I set up the ajax code like so, (this is gathered from what I've read.
var url = "addEmpJSP.jsp?firstNameField=" + escape(firstName)+"&lastNameField="+escape(lastName)+"&managerField="+escape(manager)+"&networkIDField="+escape(networkID);
xmlhttp.open("POST",url,true);
xmlhttp.onreadystatechange=dummy;
xmlhttp.send(null);
The escape() is the wrong function. It escapes JS syntax, it does not encode URI components. You should be using encodeURIComponent() function instead.
The jsp file looks like this
...
Int empId = 0;
...
This doesn't compile. It should be int instead.
...
String EditEmplSQL = "select * from PTO_employee";
rsEmpl=statment1.executeQuery(EditEmplSQL);
rsEmpl.last();
empId = rsEmpl.getRow() - 1;
...
Unnecessarily overcomplicated. Learn how to use DB builtin sequences/autoincrement IDs. Refer the DB specific manual or ask DB admin for help.
...
statement1.execute("INSERT INTO PTO_employee VALUES ("+empID+","+lName+","+fName+","+0+","+2+","+networkID);
...
You should put quotes around string values in the SQL query. Assuming that lName, fName and networkID are strings, not numbers, then it should look like this:
statement1.execute("INSERT INTO PTO_employee VALUES (" + empID + ",'" + lName + "','" + fName + "'," + 0 + "," + 2 + ",'" + networkID + "'");
But you have there a huge SQL injection attack hole and you also don't seem to close DB resources at all after use, so they may leak away and cause your webapp to crash sooner or later because the DB runs out of resources. Use PreparedStatement to create a parameterized SQL query and use its setters to set the values. Close the resources in finally block.
After all, reading the server logs should provide you information about compile errors and any server exceptions. Reading the ajax response should provide you information about the response status and body. Your core problem was that you ignored it and thus didn't have any chance to understand what is happening.
I have a Javascript statement in an MVC view that looks like this and works:
win.attachURL('<%: Url.Action("GraphDetails", "Dashboard", new { area = "Anglian", OSName = "Hello" }) %>');
When I try to extract the variable 'Hello' and put it into a javascript variable (id) and subsequently embed it into my tag like this, it breaks:
var id = "Hello";
win.attachURL('<%: Url.Action("GraphDetails", "Dashboard", new { area = "Anglian", OSName = "' + id + '" }) %>');
Question is, how do I embed a JS variable inside an ASP server tag, that itself is already embedded within Javascript? This is for a local prototype, security concerns are not an issue.
Thank you,
Tom.
One is server-side, the other is client-side, you can't mix the two.
When you do it on the server side with the id as a variable it will break because id doesn't exist in the server side context.
Why don't u try break up the statement on the client side?
var id = "Hello";
var actionInit = "<%: Url.Action("GraphDetails", "Dashboard", new { area = "Anglian"}) %>";
win.attachURL(actionInit + "?OSName=" + id");
Note: when appending ?OSName, this may cause some issue if your route doesn't map 100% correctly. eg. u get /Dashboard/GraphDetails?area="Anglian" and u append another "?" that will be an invalid URL. On the other hand, it will also be invalid if your route matches 100% and you append "&OSName". So just check that out first
I don't think you can in general. In this case at least the <%: ... %> part is evaluated at page load time and will never run again.
Instead, you can compute this in JavaScript, e.g.
var id = "Hello";
var baseURL = '<%: Url.Action("GraphDetails", "Dashboard",
new { area = "Anglian" }) %>';
win.attachURL(baseURL + '&OSName=' + id);
However that makes assumptions about how you're assembling your routing parameters for that route. You could use Url.Action to generate the full route with a dummy value and then substitute, e.g.
var id = "Hello";
var baseURL = '<%: Url.Action("GraphDetails", "Dashboard",
new { area = "Anglian", OSName="ZZZ" }) %>';
win.attachURL(baseURL.replace('ZZZ', id);
but then there's a subtle chance this could go wrong, particularly if you're feeding user generated string into other parameters in the string where they could hit on the value you substitute.
If you really did want to run Url.Action again you'd have to make an AJAX call back to a known URL with the parameters to get the URL, which is overkill really.
iam using a simple insert script function to pass the values from registration html page to register php page.
Here is my script:
function insert() {
// Optional: Show a waiting message in the layer with ID login_response
document.getElementById('insert_response').innerHTML = "Just a second..."
// Required: verify that all fileds is not empty. Use encodeURI() to solve some issues about character encoding.
var dispname= encodeURI(document.getElementById('disp_name').value);
var firstname= (document.getElementById('first_name').value);
var lastname= (document.getElementById('last_name').value);
var gender= (document.getElementById('genderreg').value);
var day= (document.getElementById('day').value);
var month= (document.getElementById('month').value);
var year= (document.getElementById('year').value);
var country= (document.getElementById('countryreg').value);
var city= (document.getElementById('cityreg').value);
var suburb= (document.getElementById('suburbreg').value);
var email= (document.getElementById('emailreg').value);
var password= (document.getElementById('regpassword').value);
var code= (document.getElementById('code').value);
var service= (document.getElementById('termservice').value);
// Set te random number to add to URL request
nocache = Math.random();
// Pass the login variables like URL variable
http.open('get', 'register_insert.php?site_url='+dispname+'&fname= '+firstname+'&lname= '+lastname+'&gender= '+gender
+'&day= '+day+'&month= '+month+'&year= '+year+'&country= '+country+'&city= '+city+'&suburb= '+suburb
+'&email= '+email+'&password= '+password+'&code= '+code+'&service= '+service+'&nocache= '+nocache);
http.onreadystatechange = insertReply;
http.send(null);
}
I just have a small question that is it a good pratice of passing the password values like this from html to php page. If it is not good idea then what is the best why to do so.
Thanks in advance for sugesstions.
Yeah, ordinarily I wouldn't immediately suggest that someone go to a javascript library, but I make an exception for AJAX. Getting that sort of thing to work cross-browser is just plain not-worth-it. Go for jQuery and save yourself a heap of stress.
Also take a look at the jQuery Form Plugin - it'll do all this for you in a very easy way. The site is at http://malsup.com/jquery/form/ .
But to answer your question, I'd use POST data. The general rule of thumb is that if you're retrieving something, use GET, but if you're sending or changing something, use POST.
Another quick pointer is that the code could be made a lot more legible by doing something like this:
var fields = {'disp_name', 'first_name', 'last_name', 'genderreg' /* etc ... */ ];
var values = {};
for (var i = 0, l = fields.length; i < l; ++i) {
values[fields[i]] = document.getElementById(fields[i]).value;
}
http.open(
'get',
'register_insert.php'
+ '?site_url=' + values.dispname
+ '&fname=' + values.first_name
+ '&lname=' + values.last_name /* etc */
);
...but it's not really that important I suppose.
Sending The password in this manner is no different from a regular From Submission via GET. Generally however, you would use POST. The downside to using get is that the password will appear in the URL. If you care about security, you should be using SSL.
Consider using a JS library like jQuery... it would make what you are doing above.. very easy.