Submitting inputs without forms with - javascript

I am trying to edit my table rows (img: http://imgur.com/yTpfCIc ) and POST the changed data to my edit.php file. I am trying to do this via jQuery. But when I click save button nothing happens, this is the explained javascript:
//Getting all "Edit" buttons in the table (one for each row)
var buttons = document.getElementsByClassName("clicker");
var savebutton = function(id){
//Alert the Id of the button to see if the function is being called, and it is.
alert(id);
//If I have any $_POST["action"] different from "update" or "edit" I should get redirected to a page apologizing, saying this cant happen. But nothing happens. (not problem with edit.php, because already tried via another way of posting from another page)
$.post( "edit.php", { action: "test"} );
};
var buttonclicked = function(e){
if(e.target.textContent == "Edit")
{
//In this function I create a lot of inputs that you see in the picture and cannot be submited one at a time
e.target.textContent = "Cancel";
var id = e.target.id;
var editable_elements = document.querySelectorAll("[contenteditable=false]");
var sub = document.getElementById("sub"+id);
var j = document.createElement("input");
j.setAttribute("type", "text");
j.setAttribute("name", "subject");
j.setAttribute("value", sub.textContent);
j.setAttribute("placeholder", sub.textContent);
j.setAttribute("style", "width: 150px");
j.textContent = sub.textContent;
sub.innerHTML = "";
sub.appendChild(j);
for(var k = (id*6); k < (id*6)+6; k++){
var l = k;
var index = k -(k*id) + 1;
l = document.createElement("input");
l.setAttribute('type',"number");
l.setAttribute("style", "width: 75px");
l.setAttribute("step", "0.01");
if(index <= 4){
l.setAttribute('name',"g"+index);
l.setAttribute('placeholder',"G"+index);
l.setAttribute("value", editable_elements[k].textContent);
}
else if(index == 5){
l.setAttribute('name',"creditos");
l.setAttribute('placeholder',"credits");
l.setAttribute("value", editable_elements[k].textContent);
}
else if(index == 6){
l.setAttribute('name',"criteria");
l.setAttribute('placeholder',"criteria");
l.setAttribute("value", editable_elements[k].textContent);
}
editable_elements[k].innerHTML = "";
editable_elements[k].appendChild(l);}
//If any edit button is pressed, create a save button in the same row
var s = document.createElement("input");
s.textContent = "Save";
s.setAttribute('type',"button");
s.setAttribute('value',"update");
s.setAttribute("id", id);
s.setAttribute("name", "a");
//Call the function that is supposed to POST all inputs infotmations
s.setAttribute("onclick", "savebutton(this.id)");
var clickbutton = document.getElementById("save"+id);
clickbutton.appendChild(s);
}
else //save button has been clicked
{
//nothing
}
};
//If one of those buttons is clicked call the function
for(var j = 0; j < buttons.length; j++)
{
buttons[j].addEventListener('click', buttonclicked);
}
That is my problem...
If you want to see the whole page, its here: http://pastie.org/10578782

You have this comment in your code:
//If I have any $_POST["action"] different from "update" or "edit" I
should get redirected to a page apologizing, saying this cant happen.
But nothing happens. (not problem with edit.php, because already tried
via another way of posting from another page)
$.post( "edit.php", { action: "test"} );
When you post via ajax, redirects do not work. Open the dev tools in your browser and check the network traffic. I'm pretty sure the edit.php page is being posted to. You need to use a callback function to check the response of the post action and act accordingly, example:
$.post( "edit.php", { action: "test"}, function(data) {
//data is the response from the edit.php
alert(data);
});
Try this code and see what the alert box says. If you want to "redirect", you can use document.location.href = 'whatever.php'; inside the callback in place of the alert(); statement.

Related

JavaScript Chrome printing multiple screens

problem in Chrome printing multiple screens
the code below is designed to load records from a list of students and print the resulting screen for each student.
this works fine in browsers other than Chrome
Chrome does not display each students record result and thus prints multiple copies of just one student.
When the script finishes the last student record in the list is displayed so we know that the form request is being made successfully. It appears Chrome is not waiting for the form request to load or that it doesn't update the screen before getting to the print command.
function printAll() {
var stdsObj = document.getElementById('stds');
for ( var i = 0; i < stdsObj.options.length; i++ ) {
showRec(i)
printIframe("main")
}
}
function showRec(selRec) {
var recID = '';
var recName = '';
var recNum = '';
var stdsObj = document.getElementById('stds');
recID = stdsObj.options[selRec].value;
recName = stdsObj.options[selRec].text;
recNum = selRec +1;
document.getElementById('recID').value = recID;
document.getElementById('recName').value = recName;
document.getElementById('recNum').value = recNum;
document.getElementById('noCacheRec').value = Math.random();
document.recList.submit()
}
function printIframe(id) {
var iframe = document.frames ? document.frames[id] : document.getElementById(id);
var ifWin = iframe.contentWindow || iframe;
ifWin.focus();
ifWin.printMe();
return false;
}
The form recList loads data into iframe "main"
<form id="recList" name="recList" action="ru_cse_view.pl" target="main">
printMe is a function in the iframe "main" that prints the iframe
function printMe() {
window.print()
}

UPDATED: redirect url pass parameter from another page

I'm would like to do a 2 step process without the user knowing. Right now when the user click on the link from another page.
URL redirect to run some JavaScript function that updates the database.
Then pass the variable to view a document.
User clicks on this link from another page
Here is some of code in the JavaScript file:
<script type="text/javascript">
window.onload = function(){
var auditObject ="";
var audit_rec = {};
var redirLink = "";
if(document.URL.indexOf('?1w') > -1 {
redirLink = "https://www.wikipedia.org/";
auditObject = redirLink;
audit_rec.action = "OPEN";
audit_rec.object = auditObject;
audit_rec.object_type = "WINDOW";
audit_rec.status = "Y";
window.open(redirLink);
} else {
audit_rec.target = /MyServlet;
audit_rec.action = "OPEN";
audit_rec.object = TESTSITE;
audit_rec.object_type = "WINDOW";
audit_rec.status = "Y";
}
function audit(audit_rec) {
var strObject = audit_rec.object;
strObject = strObject.toLowerCase();
var strCategory = "";
if (strObject.indexOf("wiki") > -1) {
strCategory = "Wiki";
} else if strObject.indexOf("test") > -1) {
strCategory = "TEST Home Page";
}
//Send jQuery AJAX request to audit the user event.
$.post(audit_rec.target, {
ACTION_DATE : String(Date.now()),
DOMAIN : "TESTSITE",
ACTION : audit_rec.action,
OBJECT : audit_rec.object,
OBJECT_TYPE : audit_rec.object_type,
STATUS : audit_rec.status
});
}
//TEST initial page load.
audit(audit_rec);
}
</script>
Can someone help? Thanks
You could give your link a class or ID such as
<a id="doclink" href="http://website.com/docviewer.html?docId=ABC%2Fguide%3A%2F%2F'||i.guide||'">'||i.docno||'</a>
then use javascript to intercept it and run your ajax script to update the database. Here's how you'd do it in jQuery:
$('#doclink').click(function(e) {
var linkToFollow = $(this).attr('href');
e.preventDefault();
yourAjaxFunction(parameters, function() {
location.href = linkToFollow;
});
});
where the function containing the redirect is a callback function after your ajax script completes. This stops the link from being followed until you've run your ajax script.
if your question is to hide the parameters Here is the Answer
you just use input type as hidden the code like this
'||i.docno||'

Javascript - parse XML document to create array

I am working on a web-based application which contains 'divs' that I use for clickable buttons. Currently, my code calls a handleClick function for each 'div' button that needs to be handled. I would like to parse an xml document to get the inputs required for my handleClick function. I have tried implementing solutions from this thread: Parsing XML with Javascript and create array, but I haven't had any luck. I have also been trying to use this information: http://www.w3schools.com/xml/dom_intro.asp, but I'm confused as to what is really needed. The w3schools code uses the XMLHttpRequest function, but the stackoverflow code does not. Here's what I have so far:
//Change background image when Login button clicked.
handleClick("#btnLogin", "SideMenu.png", "LoginButton", "SideMenuButton");
function handleClick (inputButton, inputImage, inputIndexOFF, inputIndexON) {
$(inputButton).click(function() {
$("body").css("background-image", "url(" + inputImage + ")");
//This is how I remove the highlight from the buttons.
zIndexON(inputIndexON);
//This is how I apply the highlight to buttons.
zIndexOFF(inputIndexOFF);
});
}
function zIndexOFF (inputClass) {
var x = document.getElementsByClassName(inputClass);
for (i = 0; i < x.length; i++) {
x[i].style.zIndex = "-1"
}
}
function zIndexON (inputClass) {
var x = document.getElementsByClassName(inputClass);
for (i = 0; i < x.length; i++) {
x[i].style.zIndex = "1"
}
}
//XML
<buttons>
<button>
<inputButton>#btnLogin</inputButton>
<inputImage>SideMenu.png</inputImage>
<inputIndexOFF>LoginButton</inputIndexOFF>
<inputIndexON>SideMenuButton</inputIndexON>
</button>
</buttons>
My initial idea was to create a function to load the xml doc per the information from the w3schools page, then use a for loop to parse the xml elements, and create an array containing the necessary inputs for the handleClick function, then loop through the array to call the handleClick function to process all of the clicks, rather than repeat the same call to handleClick for each button. If there is a simpler way, I'm all ears.
EDIT: I have created a handleClicks function trying to implement the thread from the post I linked above. I also edited my XML doc to resemble the XML from the same thread.
function handleClicks () {
//Get all buttons from XML
var btns = jQuery(buttons).find("button");
//Get input fields for each button in XML
for (var i = 0; i < btns.length; i++) {
var ret = [];
var tot = [];
ret[0] = jQuery(btns[i]).find('inputButton').text();
ret[1] = jQuery(btns[i]).find('inputImage').text();
ret[2] = jQuery(btns[i]).find('inputIndexOFF').text();
ret[3] = jQuery(btns[i]).find('inputIndexON').text();
tot.push(ret);
}
//Call handleClick function for each button from XML doc, and pass in inputs to handleClick function
for (var j = 0; j < button.length; i++) {
handleClick(tot[0].text, tot[1].text, tot[2].text, tot[3].text);
}
}
The buttons still highlight on hover, but nothing happens when I click.
Regarding XML parsing your example is correct. The only place that is not clear is your buttons variable in jQuery(buttons).find("button");. The following example correctly parses the sample xml and calls handleClick with needed data:
var xml_text = "<buttons>" +
"<button>" +
" <inputButton>#btnLogin</inputButton>" +
" <inputImage>SideMenu.png</inputImage>" +
" <inputIndexOFF>LoginButton</inputIndexOFF>" +
" <inputIndexON>SideMenuButton</inputIndexON>" +
"</button>" +
"</buttons>"
var xml = $.parseXML(xml_text);
function handleClick(inputButton, inputImage, inputIndexOFF, inputIndexON) {
console.log(inputButton +' ' + inputImage +' ' + inputIndexOFF +' ' + inputIndexON);
}
function parseXml(xml) {
jQuery(xml).find("button").each(function() {
var inputButton = jQuery(this).find("inputButton").text();
var inputImage = jQuery(this).find("inputImage").text();
var inputIndexOFF = jQuery(this).find("inputIndexOFF").text();
var inputIndexON = jQuery(this).find("inputIndexON").text();
handleClick(inputButton, inputImage, inputIndexOFF, inputIndexON);
});
}
The XML document can be downloaded from the Web using jQuery GET or POST request:
$.ajax({
type: "POST",
url: "/echo/xml/",
dataType: "xml",
data: {
xml: xml_text
},
success: function(xml) {
console.log(xml);
parseXml(xml);
},
error: function(data) {
console.log(data);
}
})
In this example https://jsfiddle.net/t406v94t/ the XML is downloaded using POST request. The sample xml_text is posted to the jsfiddle server to receive it back as Web data. The document is parsed once the download is successfully finished.

Combining 2 Javascript/Jquery scripts

Im having a issue, I need to combine 2 scripts together. One of which is a validation and the other is variables/ajax script. I tried but i cannot get it to work. I put it within the script under the area that checks if it has the needfilled element attached however it submits without executing the ajax call.
Script 1:
$(document).ready(function(){
$("#loading").hide();
// Place ID's of all required fields here.
required = ["parentFirstName", "parentLastName", "parentEmailOne", "parentZip"];
// If using an ID other than #email or #error then replace it here
email = $("#parentEmailOne");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
$("#theform").submit(function(){
//Validate required fields
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("needsfilled");
}
}
// Validate the e-mail.
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
return false;
} else {
errornotice.hide();
return true;
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});
Script 2:
// Form Varables
var parentFirstNameVal = $("#parentFirstName").val();
var parentLastNameVal = $("#parentLastName").val();
var emailaddressVal = $("#parentEmailOne").val();
var parentPhoneVal = $("#parentPhone").val();
var parentAddressVal = $("#parentAddress").val();
var parentAddressContVal = $("#parentAddressCont").val();
var parentCityVal = $("#parentCity").val();
var parentStateVal = $("#parentState").val();
var parentZipVal = $("#parentZip").val();
var parentListenVal = $("#parentListen").val();
var codeVal = $("#code").val();
var getUpdateVal = $("#getUpdate").val();
input.removeClass("needsfilled");
$("#message-space").html('<br /><br /><span class="greenText">Connected to Facebook.</span><br />');
$("#loading").show();
var counter = 0,
divs = $('#div1, #div2, #div3, #div4');
function showDiv () {
divs.hide()
.filter(function (index) { return index == counter % 3; })
.show('fast');
counter++;
};
showDiv();
setInterval(function () {
showDiv();
}, 10 * 600);
alert(parentFirstNameVal);
$.ajax({
type: "POST",
url: "includes/programs/updateEmailsTwo.php",
data: "parentFirstName="+parentFirstNameVal+"&parentLastName="+parentLastNameVal+"&UserEmail="+emailaddressVal+"&parentPhone="+parentPhoneVal+"&parentAddress="+parentAddressVal+"&parentAddressCont="+parentAddressContVal+"&parentCity="+parentCityVal+"&parentState="+parentStateVal+"&parentZip="+parentZipVal+"&parentListen="+parentListenVal+"&code="+codeVal+"&getUpdate="+getUpdateVal+"&ref=<?php echo $_SESSION["refid"]; ?>",
success: function(data){
$("#message-space").html('<br /><br /><span class="greenText">Complete</span><br />');
divs.hide()
}
});
In addition to the suggestions that #JeffWilbert gave, I am going to follow it up with some more suggestions to make your code a bit more cleaner and efficient.
First, just like you did in script 1, where you have an array of field names, you can do the same for script 2. Below is an example of what you can do make your code a bit more readable.
var fields = ['parentFirstName', 'parentLastName', 'parentEmailOne', 'parentPhone'];
var fieldsValue = [], dataString;
for(i = 0; i < fields.length; i++){
fieldsValue.push(fields[i] + "Val=" + $('#' + fields[i]).val());
}
dataString = fieldsValue.join("&");
Second, If Script 2 is not dependent on any variable declared from Script 1, I would convert Script 2 into its own function and call it from Script 1. I think adding all that code inside the else like Jeff suggested is not best.
function Script2(){
//Script 2 Code
}
$("#theform").submit(function(){
//Call Script 2
});
And Third, If you are going to submit the form via AJAX and not through its default method, I would recommend using .preventDefault and then handle the flow of the submission inside the event handler function.
$("#theform").submit(function(e){
e.preventDefault();
//rest of your code here.
});
The code in script 2 needs to go inside script 1 where I marked below with a comment; if your code in script 2 is submitting the form via ajax call then you don't need to return true if no errors are found, by doing so your telling the form to submit normally.
if ($(":input").hasClass("needsfilled")) {
return false;
} else {
errornotice.hide();
// SCRIPT 2 CODE HERE BEFORE THE RETURN
// If the ajax call in script 2 is submitting your form via ajax then change
// the line below to return false so your form doesn't submit
return true;
}

javascript - redirecting

I can get the code to pop-up both alert but redirecting is not working. After adding an item it should redirect.
<script type="text/javascript" src="/_layouts/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
fields = init_fields();
// Where to go when cancel is clicked
goToWhenCanceled = '/test/English/YouCanceled.aspx';
// Edit the redirect on the cancel-button's
$('.ms-ButtonHeightWidth[id$="GoBack"]').each(function(){
$(this).click(function(){
STSNavigate(goToWhenCanceled);
})
});
// Edit the form-action attribute to add the source=yourCustomRedirectPage
function setOnSubmitRedir(redirURL){
var action = $("#aspnetForm").attr('action');
var end = action.indexOf('&');
if(action.indexOf('&')<0){
newAction = action + "?Source=" + redirURL;
}else{
newAction = action.substring(0,end) + "&Source=" + redirURL;
}
$("#aspnetForm").attr('action',newAction);
alert(redirURL);
}
/*
// Use this for adding a "static" redirect when the user submits the form
$(document).ready(function(){
var goToWhenSubmitted = '/test/English/ThankYou.aspx';
setOnSubmitRedir(goToWhenSubmitted);
});
*/
// Use this function to add a dynamic URL for the OnSubmit-redirect. This function is automatically executed before save item.
function PreSaveAction(){
// Pass a dynamic redirect URL to the function by setting it here,
// for example based on certain selections made in the form fields like this:
var dynamicRedirect = '/surveys/Pages/ThankYou.aspx';
// Call the function and set the redirect URL in the form-action attribute
setOnSubmitRedir(dynamicRedirect);
alert(dynamicRedirect);
// This function must return true for the save item to happen
return true;
}
function init_fields(){
var res = {};
$("td.ms-formbody").each(function(){
if($(this).html().indexOf('FieldInternalName="')<0) return;
var start = $(this).html().indexOf('FieldInternalName="')+19;
var stopp = $(this).html().indexOf('FieldType="')-7;
var nm = $(this).html().substring(start,stopp);
res[nm] = this.parentNode;
});
return res;
}
</script>
If you set window.location.href = 'SomeUrl' at any point, it should redirect right then. Looking at your code, I dont see that anywhere.
At what point are you trying to redirect?

Categories

Resources