php, scroll page to specified html control on form - javascript

First question after starting with netbeans and wamp server 2 days ago. Only have some desktop vb background, so my jargon may be off. In vb I would want to set the focus on a control.
I have a long, as in a lot of scrolling, webpage form in html that displays the way I want it. There are about 300 controls, almost all checkboxes.
When the Submit button is clicked at the bottom of the form I want to find any incomplete data, scroll the page to that control and give the user a message so I don't insert unfinished records.
How do I do that?

I think you need to validate data with javascript and with a function to do scroll. Check this:
scroll to div ajax/javascript

In the form, add the 'required' attribute to each input tag.
EX:
<input type="text" required>
When the form is submitted, the first input tag with the 'required' attribute will be scrolled to, and the user will be notified.

What you are looking for is called validation. You should validate data on the server with PHP to make sure that the data meets your defined criteria (since the data could come from a manipulated form and users can deactivate javascript). You should also look into escaping data, for example with mysqli_real_escape_string to prevent SQL injection (an attack where a malicious user enters SQL statements in your form to alter/expose data in your database). And you should sanitize your data.
But that is all server-side. What you also want is to have a good user experience and not even send data to the server unless is is valid. This is done with javascript on the client side. The upside is: Immediate feedback without a page load. But it has little to do with security since it's easy to manipulate that or turn javascript off.
I would recommend using jQuery and then a plugin like jQuery Validation. And for the scrolling part you could use jQuery scrollto. You could combine those two with a callback from jquery validation. For example (just a quick and dirty example):
$(".form-selector").validate({
invalidHandler: function(event, validator) {
// 'this' refers to the form
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'You missed 1 field. It has been highlighted'
: 'You missed ' + errors + ' fields. They have been highlighted';
$("div.error span").html(message);
$("div.error").show();
// Now scroll to the first error message
var first_element = validator.errorList[0].element;
$(window).scrollTo(first_element);
} else {
$("div.error").hide();
}
}
});
But the best thing would be to start with a jQuery tutorial and then dig into that.

Related

Invisible Recaptcha - site key not loaded?

Updating because I have changed the implementation to something (somewhat) more successful.
I'm trying to implement the Invisible Recaptcha in our system. We are using dynamically generated forms, so, I'm going the route of programmatically invoking the challenge. I have this code to get the API:
<script src="https://www.google.com/recaptcha/api.js?render=explicit" async defer></script>
Just before drawing my form, I inject the captcha div:
form.fields.push({
html: '<div id="g-recaptcha-div" class="g-recaptcha" data-sitekey="<mykey>" data-callback="myCallback" data-size="invisible"></div>',
type: 'html'
});
When my form is drawn, I then call the render function:
recaptcha_id = grecaptcha.render(
'g-recaptcha-div',
{
'data-callback': _settings.form.submit
}
);
When the form appears, he "protected by reCAPTCHA" logo box shows up over my submit button.
In my submit function, I do some form validation, and then 'execute' the reCaptcha:
grecaptcha.execute(recaptcha_id);
And then continue on with my submit. So far, exactly once I have seen the reCaptcha challenge ('pick out images with a storefront'), at which point the g-recaptcha-response value was inserted into my form submission, and I see it in the parameters passed to my PHP function.
But, most of the time I do not see the challenge, and there is nothing in the g-recaptcha-response parameter, so my PHP validation fails. A couple of questions:
1) My assumption about the challenge not showing up all the time is that the Google logic only requires it when "conditions are right". If that is the case, what am I to do when it doesn't show up, at which point the g-recaptcha-response parameter is there with no value - do I just ignore it at that point, assuming that no value means ok?
2) Is there any way to "force" the challenge to show up, if only to make me feel better about the whole thing working, and to test my handling of a response?
3) I have tried calling grecaptcha.getResponse(recaptcha_id) after grecaptcha.execute(recaptcha_id), but that doesn't return anything. It would be easier/better for me to process the reCaptcha in my client.
Any answers appreciated. I may resubmit this as a new 'Question' since this one has been around a while.

How can I force an AngluarJS form to realize required fields have been filled through DOM manipulation (no user input)?

I've written an Excel VBA macro to paste some data into an AngularJS form -- it opens an Internet Explorer (11) window, navigates to the page containing the form, and crawls the document tree looking for certain elements by their ID, changing their values from blank to non-blank strings from the Excel sheet. However, when I submit the form, the form logic treats all the required fields as if they were still blank, drawing a red box around the supposed offending fields. (I can intervene at this point by clicking into each field, typing a random character at the end of the pasted data and immediately deleting it, and this triggers the logic that the required field is now filled.)
I'm not a javascript programmer and didn't design the form (nor can I change it in any way). I can manipulate the DOM elements (focusing and blurring the fields, for example, though that doesn't seem to work), and I can probably run any command that could be entered into the console in the browser debugger. Would any AngularJS expert know a relatively simple way to force the form to check itself?
Have you solved this problem Karim or found any solution? I recently had a project of mine, with the same problem.
Try to find the tag with ng-submit something like what I have 'ng-submit"=submit($event)"'. I referenced the form element and used .submit. In your case, try this:
Set HTMLFormEl = HTML.getElementById("accountNameValue")
HTMLFormEl.Submit
The 'submit' was the one that solved my problem. Let me know if this works for you.
Not a VBA nor AngularJS expert but I noticed that AngularJS has nothing to do in treating the required fields as if they were still blank. Just need to find the correct event to trigger. Just my opinion.
Don't know is my answer is actual or not, but i had the same problem, and i found a solution using Application.SendKeys. The function filling out the form looks like this
Function inputWrite(ByVal str As String, inputEl As Object, ByVal hwnd As LongLong) As Boolean
TryAgain_inputWrite:
strSub = Left(str, Len(str) - 1)
strKey = Right(str, 1)
inputEl.Focus
inputEl.Value = strSub
setToFore hwnd
Application.SendKeys strKey
Application.Wait DateAdd("s", 1, Now)
If (inputEl.Value = str) Then
inputWrite = True
Else
GoTo TryAgain_inputWrite
End If
End Function
setToFore is just a function to always keep the Internet Explorer on top of other applications, so the send key won't miss.

Input Validation & Return with either javascript or asp

I need to know how to make a order look up validation.
For example if order number 2005 is entered into the field,
i want it to pull a specific html page.
If entered number is anything other than 2005 ,it will pull another html page.
Will be great if u guys can show for asp or java script with the .document write innerhtml for java script
how to do do this with javascript or asp?
There are a few ways you can go about this. You can use JQuery or Javascript to make an AJAX request to validate the OrderNumber first. If Valid, that field gets posted back to the Form which envokes the response object to go to the page desired.
dim strOrderNumber
strOrderNumber = request("txtOrderNumber") ' Or whatever field name you gave this object
' Page gets posted and picks up here
if len(strOrderNumber) > 0 then
' Be sure to close any opened DB connections and destroy any objects that were created
response.redirect("pagename_" & strOrderNumber & ".asp")
end if

Javascript, Ajax and form submission/response

I'm hoping there is a simple solution to this, or else its possible AJAX time!
I WAS using ClickBank. I had a simple button on my page. That sent the form data to a script, I processed the data, and then added a redirect at end of script to jump to the "pay" link. Nice n' easy
But now I'm switching to "Click2Sell" ... and they have a direct href to their site.
Now I COULD use javascript to read the form data, place it into their "cp_" prefix, and create a super long (about 400 chars) query string and send that to their server, then re-read the data at the IPN stage ...
?country=UK&area=essex&desc=This is the data entered by the user 'whatever'
(but that leads to a little fact that certain parts might need to be escaped(?) such as the spaces and the " ' " or whatever other symbol they enter)
So I devised this method:
<javascript>
function send_data(){
document.user.submit();
return true;
}
</javascript>
<div name="noshowdiv"><object name="noshow"></object></div>
<form method="post" target="noshow" name="user">
<input type="text" name="country">
<input type="text" name="area">
<textarea name="desc"></textarea>
</form>
<img src="xxx" onclick="return send_data();">
In a nutshell, when the button is clicked, it jumps to the function, and submits the form data to my script, and then returns to the hyperlink to submit the second form via the hyperlink.
Two problems: Firstly, the data returned by my script is opening in a new tab rather than the <div>, (I suspect 'cos the submit option loses track of the sending window) and also, I need to get a response from my script which I can then append to the href link.
For example, if the form records the user's data on line 5 on my server, the script will return "id=5" I would then make the hyperlink "click2sell.asp?cp_id=5"
As I've said, I suspect this is a job for Ajax and a HttpRequest ... which is a whole new area to me. Any advice?
For the first problem, it opens a new tab because you have target="no-show" on your form.
For the second problem, if you want to use Ajax, I recommend you use jQuery, it will simplify a lot of the code.
But the best option is probably that you completely remove the direct link to click2sell, and just add a submit button to your form. Post the form to your site, which will store whatever info it needs, assigns an ID, and builds the click2sell URL with the ID in one of the parameters, and redirect to it.
Now how you would do that depends on what server-side language you use.
(I think) I have managed to find a work around, which was using the first option to reconstruct the href link. I couldn't iterate through the form as there are values that don't need to be forwarded. First I get the value, load it into a variable, then use an encode function I discovered online, and then reassign to the form ...
var cp_cc=document.getElementById('cc').value;
var cp_cs=document.getElementById('cs').value; // plus 10 other values
var str='&cp_cc='+encodeURIComponent(cc)+'&cp_cs='+encodeURIComponent(cs)+ // etc
var send_str=document.getElementById('c2s_bn_lnk_36288').href;
document.getElementById('c2s_bn_lnk_36288').href=send_str+str;
The "no-show" was a slip up in my typing! Alas, the answer given above wouldn't work as the Click2sell button also includes two calls to external JS files - and they give you no idea what they do, but is something to do with initializing the button, (it passes the "36288" to the script to do ???). And whilst using "Location: ..\n\n" on my server would redirect to their site, it wouldn't action whatever those external files do. (OK, so I didn't give the full facts, but I didn't want to increase the post size with data I felt didn't relate to problem)
** Now got to amend the listening scripts such that rather than set the ID number up front then jump to C2S, it now waits for C2S to send the data back to me and then sets up the database!!

How to create a form with a text area and two buttons, each with a different action?

I'm using Express.js and Jade and would like to create a form that consists of a textarea and two buttons, each of which invokes a different action. I came up with this but not sure if that's the proper way to do this since pressing the button only redirects but making one button submit does not differentiate it from pressing the other button:
form(method='post', action='')
textarea(wrap="soft" placeholder="Leave a reply...").fixit-reply
a.btn.btn-primary(href="/resolve") Resolve
a.btn.btn-warning(href="/comment") Comment
Ideally, one action would be caught with app.post('/resolve', handle); and the other with app.post('/comment', handleC);.
(As requested, my original comments formed up into an answer.)
Although this can be handled client-side with JS, I'm not familiar with Express.js or Jade so I don't know how to integrate a JS solution with your existing code.
However, if both buttons are submit buttons you can test server-side which one was pressed and redirect as appropriate, thus avoiding the need for any client-side JS. The name and value of whichever submit button is clicked will be submitted along with other form data. The button that wasn't clicked will not be included in the form data. So you could give both buttons name="action" and then server-side you'd test that parameter and redirect according to the associated value. (Or give your buttons different name attributes and test server-side whether the parameter for a particular button exists at all.) Of course you'd need to give your form an action="something" attribute corresponding to the server-side action that does the test and redirect.
In my opinion a server-side only solution is better for this particular requirement because it's easy to do, it keeps the client-side stuff simple, and (obviously) will work even in browsers where the end user has disabled JavaScript (not that many users do that, but it does happen).
Client side, jade template, 2 buttons, fulfill "xss" with different data from different button:
form#formTestHtml1(name="htmlForm",method="post",action="/testhtml")
button#btnSubmit1(type="submit" name="xss" value="s-html") Submit to sanitize-html
br
button#btnSubmit2(type="submit" name="xss" value="bleach") Submit to bleach
Server side, check the value of "xss" ( I used node.js and express for routing in the example)
router.post('/testhtml', function (req, res, next) {
var sanitizedStr = "";
if ( req.body.xss && req.body.xss == "sanitize-html" ) {
sanitizedStr = "sanitize-html";
} else
if ( req.body.xss && req.body.xss == "bleach" ) {
sanitizedStr = "bleach";
} else {
sanitizedStr = "xss undefined or unknown";
}
res.render(sanitizedStr);
});
It's a real-life example, I took it from a page, when i test snippets for XSS with different html/css sanitizers. Simplified, ofc.

Categories

Resources