Passing values to popup window by post? - javascript

i am trying to figure out how to pass an element id to a popup window that executes only php code. when the link is clicked, it grabs the link id, the opens the popup, how do i get the id to be passed?
JS:
$(document).on('click', '.char_inventory', function (e) {
c = true;
var id = e.currentTarget.id;
//alert(id);
if (id == "close_inventory") {
$("#console").html("<div id=\"placeholder\"></div>");
c = false;
} else {
/* $.post('input_commands/inventory_show.php',{id:id}, function(data) {
text=data;
elem = $("#console");
//delay=100;
elem.html(text);
}); */
function popUp(target, id) {
//var id = parent.document.getElementById('id').value;
popWin = window.open(target, "windowName", "width=400,height=250,status=yes");
}
popUp("input_commands/inventory_show.php", id);
}
load();
//setTimeout(function(){c=false;},4000);
});

you mean like:
function popUp(target, id) {
window.some_id = id;
window.open(target, "windowName", "width=400,height=250,status=yes");
}
and in child window:
//get some_id
var id = window.opener.some_id;
if you want to access the element with id from child window, do:
var id = window.opener.some_id;
var clickedElement = window.opener.$("#" +id)

Edit the line popUp("input_commands/inventory_show.php", id); to popUp("input_commands/inventory_show.php?id="+id); and on the page inventory_show.php you can use $_REQUEST['id'] or $_GET['id'] to get the value.
if you want to pass more parameters you can do :
popUp("input_commands/inventory_show.php?id="+id+"&param1="+param1_value+"&param2="+param2_value);

It's a very good educational issue: you will understand that the "narrative" or the "story" of the program execution breaks when you pass anyting to the server (PHP in this case).
Interpret the situation as two separate action:
User selects an item, the data is fowarded to server side for further processing.
When the server completes a processing, it sends the data to the client for displaying it.
In JavaScript, there is no single-line of program execution. There are listeners, and when an event occurs, like user action or timeout or arrival of an AJAX response, the appropiate handler executes and processes it (and may do things which will be generate further events in the future, e.g. set up a timer or initiate AJAX).
When you initiate something, which will cause event in the future, it's your responsibility that the event should contain all the information for the handler. Most of cases there is a simple way to do it: you can set up separate handler for each event, other cases you should use a mechanism to put ID or "target address" into the event, which the handler can recognise.

Related

Adding Event Listeners (in a callback function) to generated elements

My objective - and I want to do this w/out jQuery:
retrieve data from a json file (ajax GET)
use data therein to generate a list of links
when one of these links is clicked, get the value of its id (or perhaps another attribute), use it to load corresponding data (from the same json file, also via ajax GET)
Having rewritten this code to employ a callback, I'm getting the json data & creating links. However, I'm confused about two things regarding how the addEventListener works: first, why is the showProj function invoked as the event listeners are added in the for loop (so far, only alerting each link's id)? And second, why do the links not respond to clicks afterwards? I thought adding event listeners merely enables the generated links to be clickable?
function ajaxReq() {
var request = new XMLHttpRequest();
return request;
}
function getJsonData(makeLinks) { // makeLinks = the callback
var request = ajaxReq();
request.open("GET", "/json/projects.json", true);
request.setRequestHeader("content-type", "application/json");
request.send(null);
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
makeLinks(request.responseText);
}
}
} // onreadystatechange
} // getJsonData
getJsonData(makeLinks);
function makeLinks(result) { // result = request.responseText
var projects = JSON.parse(result);
var projects = projects["Projects"];
var projectList = document.getElementById("project-list"); // ul#project-list
for (var project in projects) {
var projectId = projects[project].id;
var listItem = "<li><a class=\"project-link\" id=\""+projects[project].project+"\" href=\"#\">" + projects[project].project + "</a></li>";
projectList.innerHTML += listItem;
}
var projLink = document.getElementsByClassName("project-link");
for (var i = 0; i < projLink.length; i++) {
var projId = projLink[i].id;
projLink[i].addEventListener("click", showProject(projId), false); // ** ?? **
}
} // makeLinks
function showProject(projId) {
/*
function showProject will load data corresponding to the link's id (or another attribute);
presently there are only alerts until the links are working
*/
alert("projId is: " + projId);
} // showProject
Again, what I'm ultimately after is simply to click on a .project-link class link, get its id (or some other attribute) and then load corresponding data, e.g. (pseudo-code):
projLink.onclick = function(){
var projId = this.id;
showProject(projId);
}
... and I realize I could do it with this:
$(document).ready(function() {
$("#project-list").on("click", 'li a', function() {
var projId = this.id;
showProject(projId);
})
})
... but I want to know why the event listeners aren't working in the first place (that is, without the jQuery bit).
And lastly: would it be considered evil bad practice in this scenario to preclude a scope issue by defining var projLink globally, so that I don't have to redefine it e.g., inside showProj?
Many thanks in advance for any corrections, suggestions, insights.
svs
You're correct that var projLink is scoped to the makeLinks() function, but more importantly it's also inside the Ajax callback, which is a separate asynchronous scope.
While that Ajax code is running asynchronously, the rest of your JS continues to run as well.
So if you call another function to also getElementsByClassName("project-link"), most likely there aren't any yet because the Ajax callback hasn't finished doing its thing.
Possible options include:
Put everything in the Ajax request.onreadystatechange() within makeLinks() (not ideal)
Adjust the code to use a separate callback function, and pass your JSON data to it. You may have to mess w/timeouts & checks to ensure the data is defined & complete before you try to act on it.
Take a look at this previous question about Ajax response.
Having read up a little further on event listeners, I have discovered the answer to my initial two questions and solved my current issue so if it's of interest to anyone:
projLink[i].addEventListener("click", showProject(projId), false);
The 'showProj' function is invoked in the above statement because i) it's (also) a callback, and - if I understand correctly - ii) because an argument is provided; therefore it's invoked as each of the elements in the for loop has the click event added. Evidently if no argument is provided to the addEventListener callback, then the callback function will indeed be invoked on click. [ more insight on this would be welcome ]
Furthermore, I learn that the third argument (boolean) pertains to capture & bubbling, however I shall not presently sidetrack myself on the finer points of capture & bubbling. Suffice to say that in my case, I'm fairly certain I can achieve my needs thusly:
projLink[i].addEventListener("click", showProject, false);
... (and perhaps even without the optional boolean altogether, though my understanding is that it's better practice to include it (?)
svs, over & out.

Does JQuery $.post() not work with document.onbeforeunload event?

I am trying to use $.post to send form data to a server side script to be saved if the user tries to leave the page without submitting the form. I am using the same function attached to a save button and on setInterval set to every 2 minutes, and it works fine. But when I attach the function to document.onbeforeunload it does not work. In firebug, I see the request is being sent, but it looks like it is being stopped before a status code is returned and the page continues to unload. I am still pretty new to Javascript and Jquery and I am not sure if maybe $.post is one of those functions that might not work on the onbeforeunload event. If that is true, is there another way I can send the data if the user tries to leave the page without saving?
This is the function I am calling from the onbeforeunload event:
function ajaxSubmit(){
var blogtitle = $("#title").val();
var publishedstate = 0;
var blogid = $("#blogID").val();
var blogbody = CKEDITOR.instances['body'].getData();
var postdata = {ajaxSubmit:true,title:blogtitle,body:blogbody,published:publishedstate,blog_id:blogid};
$.post('ajaxblog.php',postdata,function(data){
$("#autosaveMessage").html(data);
$("#autosaveMessage").show();
setTimeout(function(){$("#autosaveMessage").hide();},5000);
});
}
and this is how I am calling the function:
var post_clicked = false;
$("#postButton").click(function(){
post_clicked = true;
});
function leaveEditor(){
if(post_clicked==false){
ajaxSubmit();
}
else{
//Do Nothing
}
}
window.onbeforeunload = leaveEditor;
No, and this is by design. It would be remarkably troublesome if a page could use onbeforeunload to indefinitely delay browsing away, persist its presence somehow, etc. One of the most important abilities for a user of a web browser to have is the ability to leave.
Just use the stringy return value—the whole point of it is to remind the user that s/he made changes that will be lost. Like on SO :)

Inject custom function to onclick event

What I'm trying to do is to record all user activity on a given web page, so I'm using socket.io to send the events registered on the page, to the server with something like this:
$(document).on('click.mynamespace', function(event){
var elem = event.target;
socket.emit('my-message', { 'element' : elem };
}
The problem I'm facing is when the target element is a link of this kind My link. Whatever function is called and the page unloads (disconnecting my socket) before the socket.emit statement is executed properly.
I want to make this as universal as possible since this will be working as a plugin, and would like it to adjust to any kind of environment over which I will have no control.
So, is there a way to "highjack" all click events, send them first with my custom function, and then continue with the "normal" execution, whatever it may be?
EDIT
It seems only FF (tested on 14.0.1) causes the socket.emit event not to finish. Chrome 21.0.x seems to be working but not sure if this is by "chance".
EDIT 2
The function someFunctionThatRedirects actually redirects in this way window.location.ref = clickedurl
Events bubble upwards, so clicked element gets it's event fired before your socket.emit, you can change the way the functions work to make them do their actions in the order you want as follows
function someFunctionThatRedirects(){
window.redirectTo = 'myNewPage';
}
$(document).on('click.mynamespace', function(event){
var elem = $(event.target)[0];
socket.emit('my-message', { 'element' : elem };
if(window.redirectTo !== undefined) window.location.href = window.redirectTo;
}

Javascript, determine which button was selected in a function, similar to (id)sender in iOS?

I'm taking a Javascript class and was wondering if there was a way to tell which button was selected when a function is called. I basically have a method like this:
function sendRequest()
{
var url = "http://classwebsite/bookmarks.php";
url += "?userid=crystal";
var transmission = document.getElementById("transmission").value;
url += "&response=" + transmission;
var callback = {success:handleResponse,
failure:handleFailure,
timeout:5000
};
var transaction = YAHOO.util.Connect.asyncRequest("GET", url, callback, null);
}
This method gets called when a button is pressed. It basically gets back the prof's response in the appropriate JSON, XML, etc format and displays it. I want to add an "add" feature to add new rows to the table. That's done by calling the same URL in the above method and just manually putting this in the address bar:
http://classwebsite/bookmarks.php?userid=crystal&action=add&name=yahoo&url=yahoo.com&desc=Yahoo+website
In this scenario, if I had another button called "Add" to add in fields from a form, would I call the same sendRequest() method, and modify the url accordingly? If so, how do I know which button was pressed if both the "List" button and "Add" button would be tied to the same event handler.
Or is it a better design to have another method, that handles addRequest() and just adds fields from the form? Thanks.
If you did use the Yahoo utils like they are supposed to be used (i.e. via YAHOO.util.Event.addListener()), then your button is referenced by this.
See Automatic Scope Correction in the YUI docs.
In addition, please encode URL parameters correctly before you use them.
var transmission = document.getElementById("transmission").value,
url = "http://classwebsite/bookmarks.php"
+ "?userid=crystal"
+ "&response=" + encodeURIComponent(transmission); // <- !!
You should be able to modify the parameters of your javascript function to see the sender.
There is also a hidden array called arguments, that will let you look at what parameters are available to a function, in case you are ever curious.
function sendRequest(sender, args) {
//sender is your clicked button
var url = "http://classwebsite/bookmarks.php";
url += "?userid=crystal";
var transmission = document.getElementById("transmission").value;
url += "&response=" + transmission;
var callback = {success:handleResponse,
failure:handleFailure,
timeout:5000
};
var transaction = YAHOO.util.Connect.asyncRequest("GET", url, callback, null);
}
If a button is pressed then an event should be passed to the function. The event object contains the target of the click among other things.
function sendRequest(e) {
var target;
if(!e) {
e = window.event;
}
// the button clicked can now be accessed as
// we use the ternary because IE uses a different property
target = e.target ? e.target : e.srcElement;
}
Youll note a couple if statements in there... this is because IE differs a bit form the standard. However, i see youre using a Yahoo lib for some of your js. I imagine if you are to use the facilities of this library to bind your events it would also normalize the event object passed in to your callbacks so you wouldnt have to manually create xbrowser accommodations.

deleting cookie at the end of a process

I am using the following plug in for cookies in jQuery:
https://code.google.com/p/cookies/
The issue i am having is not with the plugin but when and how to delete the cookie at the end of a quoting process.
The site i am using this on is a six step online quote and buy process.
There is Omniture event serialisation sitestat tracking applied to some of the pages. This event serialisation has to include the name of the event and a random number of which i create.
I have a generic function for this which i call at the bottom of the page like so:
serialEvent('event21:', 'payment');
Here is the function:
function serialEvent(eventNumber, eventName) {
var sessionID = jaaulde.utils.cookies.get('sessionID');
var remLength = 20 - eventName.length;
var remSession = sessionID.substr(sessionID.length - remLength, remLength);
var eventName = eventName + remSession;
s.events = eventNumber + eventName;
}
I need to delete the cookie at the end of the process, the Thank you page but i also need the cookie 'sessionID' for the 'serialEvent' function.
As the function is called at the bottom of the page should i just write the cookie delete after it? Is that robust enough?
I need to be sure that the function has successfully been called before the cookie is deleted.
The code for deleting the cookie is quite simple:
jaaulde.utils.cookies.del('sessionID');
Thanks :)
There's no asynchronous or timer-delayed callback functions called in serialEvent function so you can either
Put it at the end of the function before the closing bracket,
or
Put it after serialEvent('event21:', 'payment');.
Javascript executes synchronously, so you can be sure that the cookie is only deleted when you are finished with it.
you can delete the cookie at the end of the process as well as in window.onUnload event to make sure that the cookie is cleared even if you are closing the window before the process completes.
function serialEvent(eventNumber, eventName)
{
var ok = false;
try
{
var sessionID = jaaulde.utils.cookies.get('sessionID');
var remLength = 20 - eventName.length;
var remSession = sessionID.substr(sessionID.length - remLength, remLength);
var eventName = eventName + remSession;
s.events = eventNumber + eventName;
ok = true;
}
catch(e)
{
// todo: error handling (what has gone wrong?)
ok = false;
}
return ok;
}
This way you can find out if the function is called correctly. ok will only be true if the whole function is executed correctly.

Categories