10

I am injecting javascript into a PHP website to avoid a pop-up, to submit a form automatically. Also, there is an issue with jquery so I am using plain javascript.

This is the form on the page:

<form action='http://mywebsite.com/index.php?&act=MYFUNCTION&CODE=01&CookieDate=1' name='subscribe_check' method='POST'>
<input type='hidden' name='value1' value='dynamicallygenerated'>
<input type='hidden' name='Value2' value='BlogSection'>
<input type='hidden' name='Value3' value='BlogName'>
<select class='forminput' name='sub_id' onchange='this.form.submit()'>
<option value='------------' selected='selected'>To read this article, you must choose a subscription level</option>
<option value='1'>Subscribe to daily updates</option>
<option value='2'>Subscribe to promotional emails</option>
<option value='3'>No thanks, I'm not interested in being healthy</option>
</select>
</form>

This is my javascript:

  // unselect any selected item on the SELECT
  if( document.getElementsByName('subscribe_check').selectedIndex )
    document.getElementsByName('subscribe_check')[document.getElementsByName('subscribe_check').selectedIndex].selected = false;

  // select select the last option
  document.getElementsByName('subscribe_check')[1][3].selected = true;
  // submit the form
  document.forms[0].submit();

When I manually click on the form, I know that these values are set

  value1: dynamicallygenerated
  value2: HealthyFoodSection
  value3: HealthyFoodFunBlog

But when my javascript submits the form, these values are submitted

  value1: dynamicallygenerated
  value2: BlogSection
  value3: BlogName

I am 100% sure there is no other javascript that is firing to change the values - there can't be, the onchange calls submit() directly.

I don't understand why my javascript submitting the form doesn't change the values like clicking it manually does? If there is PHP happening, I don't understand how it would even detect that my javascript submitted the form versus me clicking submit, a submit click is a submit click, right?

4
  • 1
    can you please add the code where you are changing the hidden values (value1, value2...3) from BlogSection and BlogName to HealthyFoodSection and HealthyFoodFunBlog?? i don't see "how" you are even able to submit those values (they'r never there). Commented Apr 17, 2019 at 2:15
  • btw. maybe your problem is the name attribute of the inputs: for values 2 and 3 your are using Value2 and Value3 instead of value2 and value3 (lower case) Commented Apr 17, 2019 at 2:18
  • it's not clear to me when this Javascript code is being executed (is it inside an event listener?). But I also see some errors here. selectedIndex is a property on the select DOM element, but the only element I see with name subscribe_check is the form itself. (The select has name sub_id.) Also getElementsByName returns a collection, so you can't access properties of one element directly on it anyway. Commented Apr 17, 2019 at 8:54
  • 1
    Please post the code where the values of hidden elements are set. Commented Apr 18, 2019 at 15:28

5 Answers 5

6
+250

First, this question is about JS only, no PHP involved,

About your original question there's no difference between a JS submit and a user click, a real difference would be only the event triggering the submit action (events click or change, where evt.target is the dom triggering the event).

As a recomendation bind your events using addEventListener instead of using directly the onchange attribute, it'll look like this:

document.getElementsByName('sub_id')[0].addEventListener("onchange", function(evt) {
    document.forms[0].submit();
});

Please try the following solutions:

1. Fix the input names:

From this:

<input type='hidden' name='Value2' value='BlogSection'>
<input type='hidden' name='Value3' value='BlogName'>

To this, accourding to your question they all should be lower case:

<input type='hidden' name='value2' value='BlogSection'>
<input type='hidden' name='value3' value='BlogName'>

2. Fix your JS onclick implementation:

From this:

  // unselect any selected item on the SELECT
  if( document.getElementsByName('subscribe_check').selectedIndex )
    document.getElementsByName('subscribe_check')[document.getElementsByName('subscribe_check').selectedIndex].selected = false;
  // select select the last option
  document.getElementsByName('subscribe_check')[1][3].selected = true;

To this, according to your question they should be pointing to sub_id, also watch the last line index (idx [1][3] doesn't exists, it should be [0][3]):

  // unselect any selected item on the SELECT
  if( document.getElementsByName('sub_id').selectedIndex )
    document.getElementsByName('sub_id')[document.getElementsByName('sub_id').selectedIndex].selected = false;
  // select select the last option
  document.getElementsByName('sub_id')[0][3].selected = true;

3. Execute the same submit function

Change your HTML from this:

<select class='forminput' name='sub_id' onchange='this.form.submit()'>

To this:

<select class='forminput' name='sub_id' onchange='document.forms[0].submit()'>

Also...

Just to be sure there's nothing else modifying your input values print them just after the onchange is triggered, like this... and also delay the submit and print them again, that should give a good look of whatever is happening:

document.getElementsByName('sub_id')[0].addEventListener("onchange", function(evt) {
    console.log(document.getElementsByName('value2'), document.getElementsByName('value3'));
    setTimeout(function() {
         console.log(document.getElementsByName('value2'), document.getElementsByName('value3'))
         document.forms[0].submit();
    },100);
});
Sign up to request clarification or add additional context in comments.

1 Comment

This answer was slightly more handy than @Sajan's Also, it turns out I had to trigger the event because it was done in the code : stackoverflow.com/questions/7055729/…
4

there is some event-driven functionality is involved for updating Value2 and Value3, it's not working when you submitting the form by js.

In order to fix this issue, you need to trigger the event your self

    function autoFormSubmit(){
        var selectElement = document.querySelector('form[name="subscribe_check"] select[name="sub_id"]');//get the element
        selectElement.addEventListener('change',onchangeEventListener) //attaching onchange  Listener, you can do this in document ready function, if you have any
        selectElement.selectedIndex = selectElement.length -1;//choose last item
        selectElement.dispatchEvent(new Event('change'))//trigger change event;

    }

    function onchangeEventListener(event){ //change event listener
        event.preventDefault();
        var form = this.form;
        setTimeout(function(){
            form.submit();
        },500)//wait few milliseconds before submitting form
    }

you can remove

 onchange='this.form.submit()'

form html code

full code

var selectElement;

function autoFormSubmit() {
    selectElement.selectedIndex = selectElement.length - 1; //choose last item
    selectElement.dispatchEvent(new Event('change')) //trigger change event;

}

function onchangeEventListener(event) { //change event listener
    event.preventDefault();
    var form = this.form;
    setTimeout(function () {
        form.submit();
    }, 500) //wait few milliseconds before submitting form
}

document.onreadystatechange = function () {
    if (document.readyState === "complete") { //page is loaded 
        selectElement = document.querySelector('form[name="subscribe_check"] select[name="sub_id"]'); //getting element
        selectElement.addEventListener('change', onchangeEventListener) //attaching listner
        autoFormSubmit();
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>

</head>

<body>
  <form action='http://mywebsite.com/index.php?&act=MYFUNCTION&CODE=01&CookieDate=1' name='subscribe_check' method='POST'>
    <input type='hidden' name='value1' value='dynamicallygenerated'>
    <input type='hidden' name='Value2' value='BlogSection'>
    <input type='hidden' name='Value3' value='BlogName'>
    <select class='forminput' name='sub_id'>
      <option value='------------' selected='selected'>To read this article, you must choose a subscription level</option>
      <option value='1'>Subscribe to daily updates</option>
      <option value='2'>Subscribe to promotional emails</option>
      <option value='3'>No thanks, I'm not interested in being healthy</option>
    </select>
  </form>
</body>

</html>

Comments

3

PHP is server side only, so can't detect what happened in the DOM, meaning it won't know which event triggered the form submit.

You may have some JS that is altering the posted values.

Comments

1

There may not be any other js in play, but what about another form in the html? As shown, this code will submit these values:

value1: dynamicallygenerated
value2: BlogSection
value3: BlogName 

And this document.getElementsByName('subscribe_check')[1][3].selected = true;1 will give an error, because there is only one element named 'subscribe_check', so there is no index 1.

1 Comment

There are other forms in the HTML but I am sure none of them interact with this part
1
  1. First of all you need to refer to the right element to deselect any selected item, in your case you are referencing the form (actually even not the form but the nodeList containing the form). document.getElementsByName('subscribe_check') returns a nodeList, which doesn't have selectedIndex property, so document.getElementsByName('subscribe_check').selectedIndex will always return an undefined.
  2. I'm not sure why you are deselecting the select value, cause directly setting the value to desired value without deselect will be enough IMHO.
  3. No need to get the option element and set it by .selected = true; just change the selectedIndex of the select element i.e. document.getElementsByName('sub_id')[0].selectedIndex = 3
  4. A hidden field let web developers include data that cannot be seen or modified by users so the hidden input values are 100% changed from the other script.
  5. Dispatch an event to trigger all the handlers for select box (the form submit included) i.e. document.getElementsByName('sub_id')[0].dispatchEvent(new Event('change')); I guess this will make the hidden inputs to change their values as well.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.