При добавлении тега HTML Form JavaScript выполняется, но волшебным образом исчезает - PullRequest
0 голосов
/ 06 июля 2019

У меня было успешное выполнение до добавления тега формы.Но почему-то JavaScript заменен.Есть ли способ обойтись без подачи этой формы.Мне нужно передать данные в PHP.Заранее спасибо ..

Это html Я пытался

<!DOCTYPE html> 
<html> 

<head> 
    <script src="riu003.js"></script> 
</head> 

<body> 
    <form name="myform" method="post" action="/riu/riu-01/riu001.php" enctype="multipart/form-data"> 
        <div id="aaa"> 
        </div> 
        <button style="width: 100%" class="bbb" onclick="addfielderbutt()">Add Fields</button> 
        <button style="width: 100%; height: 45px; background-color: dodgerblue" onclick="submity()" type="Submit" value="submit">SUBMIT</button> 
    </form> 
</body> 

</html>

А вот файл JavaScript .

function createElemented(element, attribute, inner) {
    if (typeof(element) === "undefined") { return false; }
    if (typeof(inner) === "undefined") { inner = ""; }
    var el = document.createElement(element);
    if (typeof(attribute) === 'object') {
        for (var key in attribute) {
            el.setAttribute(key, attribute[key]);
        }
    }
    if (!Array.isArray(inner)) { inner = [inner]; }
    for (var k = 0; k < inner.length; k++) {
        if (inner[k].tagName) {
            el.appendChild(inner[k]);
        } else {
            el.appendChild(document.createTextNode(inner[k]));
        }
    }
    return el;
};
var noofclicks = 0;

function addfielderbutt() {
    noofclicks = noofclicks + 1;
    var uptexty = createElemented("TEXTAREA", { class: "upt_" + noofclicks, name: "positiveuse_" + noofclicks, type: "text" }, "Type the postive uses here...");
    var nptexty = createElemented("TEXTAREA", { class: "unt_" + noofclicks, name: "negativeuse_" + noofclicks, type: "text" }, "Type the negative uses here...");
    var dptexty = createElemented("TEXTAREA", { class: "dpt_" + noofclicks, name: "positivedisuse_" + noofclicks, type: "text" }, "Type the postive disuses here...");
    var dntexty = createElemented("TEXTAREA", { class: "dnt_" + noofclicks, name: "negativedisuse_" + noofclicks, type: "text" }, "Type the negative disuses here...");
    var breakkk = createElemented("BR");
    document.getElementById("aaa").appendChild(uptexty);
    document.getElementById("aaa").appendChild(nptexty);
    document.getElementById("aaa").appendChild(dptexty);
    document.getElementById("aaa").appendChild(dntexty);
    document.getElementById("aaa").appendChild(breakkk);
}

function submity(){  
    document.cookie = "numberofclicks="+noofclicks; 
}

Ответы [ 2 ]

0 голосов
/ 06 июля 2019

Я вполне уверен, что понимаю проблему с вашим исходным кодом - невозможность предотвратить действие по умолчанию при использовании кнопки.Я немного изменил код и добавил функцию ajax, которая позволяла бы отправлять данные формы без перезагрузки страницы.По сути тот же код, но переписанный для использования внешних прослушивателей событий, а не встроенных вызовов обработчиков событий.Надеюсь, я помогу.

<?php

    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        /* 

            this is to emulate whatever code you have in 
            the form action /riu/riu-01/riu001.php

        */
        exit( json_encode( $_POST ) );
    }

?>
<!DOCTYPE html> 
<html>
<head>
    <title>You have got to have a title...</title>
    <style>
        button{ width: 100%;height:45px;background-color: dodgerblue }
        .bbb{}
        fieldset{border:none;}
    </style>
    <script>
        document.addEventListener('DOMContentLoaded',()=>{
            /*
                presumably this will be in riu003.js
                ------------------------------------
            */

            let counter = 0; // the counter to be incremented.
            let url=location.href; // change this to "/riu/riu-01/riu001.php"




            const submity=function(e){
                /*
                    explicitly prevent the default form submission
                */
                e.preventDefault();

                /* The payload is a FormData object */
                let payload=new FormData( document.querySelector('form[name="myform"]') );
                /*
                    The callback can do far more than this...
                */
                let callback=function( r ){
                    alert( r )
                }
                /*
                    send the ajax request to the backend PHP script.
                    The actual url used will not be `location.href`
                    according to the original code...
                */
                ajax.call( this, url, payload, callback );
            };


            /* a variation on the createElemented function */
            const create=function(type,attributes,parent){
                try{
                    let el = ( typeof( type )=='undefined' || type==null ) ? document.createElement( 'div' ) : document.createElement( type );
                    let _arr=['innerhtml','innertext','html','text'];
                    for( let x in attributes ) if( attributes.hasOwnProperty( x ) && !~_arr.indexOf( x ) ) el.setAttribute( x, attributes[ x ] );
                    if( attributes.hasOwnProperty('innerHTML') || attributes.hasOwnProperty('html') ) el.innerHTML=attributes.innerHTML || attributes.html;
                    if( attributes.hasOwnProperty('innerText') || attributes.hasOwnProperty('text') ) el.innerText=attributes.innerText || attributes.text;
                    if( parent!=null ) typeof( parent )=='object' ? parent.appendChild( el ) : document.getElementById( parent ).appendChild( el );
                    return el;
                }catch( err ){
                    console.warn( err.message );
                }
            };

            /* ultra basic ajax function to send a POST request */
            const ajax=function(url,payload,callback){
                let xhr=new XMLHttpRequest();
                    xhr.onreadystatechange=function(){
                        if( this.status==200 && this.readyState==4 )callback.call( this, this.response );
                    }
                    xhr.open('POST',url,true);
                    xhr.send(payload);
            };

            const addfielderbutt=function(e){
                counter++;

                /* explicitly prevent the default action being triggered */
                e.preventDefault();

                /* create a fieldset and append new children to it */
                let fieldset=create( 'fieldset', {}, document.getElementById('aaa') );

                /* add the children */
                create( 'textarea',{ 'class':'upt_' + counter, name:'positiveuse_' + counter },fieldset );
                create( 'textarea',{ 'class':'unt_' + counter, name:'negativeuse_' + counter },fieldset );
                create( 'textarea',{ 'class':'dpt_' + counter, name:'positivedisuse_' + counter },fieldset );
                create( 'textarea',{ 'class':'dnt_' + counter, name:'negativedisuse_' + counter },fieldset );
            };

            /*
                Bind the event handlers to the buttons
            */
            document.querySelector( 'button.bbb' ).addEventListener( 'click', addfielderbutt );
            document.querySelector( 'button[ type="submit" ]' ).addEventListener( 'click', submity );
        });
    </script>
</head>
    <body> 
        <form name='myform' method='post'> 
            <div id='aaa'>
                <!-- generated content will appear here -->
            </div>

            <button class='bbb'>Add Fields</button> 
            <button type='Submit' value='submit'>SUBMIT</button> 
        </form> 
    </body>
</html>
0 голосов
/ 06 июля 2019

Возможно, проблема в том, что ваша кнопка отправки имеет type="submit".Поскольку вы упоминали, что он работал до добавления тега формы, я предполагаю, что submity() - это функция, которая отправляет данные в PHP, но теперь, когда вы добавили тег формы, он не будет выполнен.Это происходит потому, что нажатие кнопки с type="submit" внутри тега формы не только отправляет данные формы по ссылке в атрибуте действия, но и перемещается к нему.

...