aldito2
aldito2

Reputation: 94

How do I get javascript to send form to php

I have searched the questions and none directly addresses the issue I'm having. Please forgive me if it has been addressed; I could not find it. I am making a form using JavaScript and trying to submit it, but when I do form.submit nothing happens. The page reloads, but it never gets to the PHP page to which I am directing it.

the JavaScript:

    function voteForName(name){
       var form2 = document.createElement("form");
       form2.setAttribute("method", "get");
       form2.setAttribute("action", "../php/namesSuggest.php");

       var hiddenField = document.createElement("input");
       hiddenField.setAttribute("type", "text");
       hiddenField.setAttribute("name", "babyName");
       hiddenField.setAttribute("value", name);
       form2.appendChild(hiddenField);

       document.body.appendChild(form2);
       alert(form2.outerHTML);
       form2.submit();  
     }

the html

            '<tr>
                <td width="33%"></td> 
                <td width="33%" align="center"><a href><p onclick="voteForName(\''. $obj["name"] .'\')" title="Click to vote for this name!" id="123'. $obj["name"] .'" >'
                    . $obj["name"] . 
                '</p></a></td>
                <td width="33%"></td>
              </tr>';

the html is being formed using php. the folders are set up

site
    home
        fileWhereJSIsCalled.php
    php
        namesSuggestions.php
    js
        myJSfile.js

Any suggestions would be appreciated.

Upvotes: 0

Views: 65

Answers (2)

aldito2
aldito2

Reputation: 94

Adding href to the <a> tag would refresh the page and not let the javascript do it's thing.

Very silly mistake, but I am going to add the answer here just in case anyone else has this problem

Upvotes: 0

Avinash Ware
Avinash Ware

Reputation: 158

try this

form2.setAttribute("action", "php/namesSuggest.php");

Upvotes: 1

Related Questions