1
\$\begingroup\$

Just asking to if following code is ok since i needed didn't find equivalent of .serialize() for vanilla JS. So i invented my own function for plain ol' JS.

    function uzim_vred(phpdoc,parent_id){

    var name = "";
    var val = "";
    var str = phpdoc+"?,";
    var len = ($("#"+parent_id+" [name]").length);
    var i = 0;

    $("#"+parent_id+" [name]").each(function(){

        i++;
        name = $(this).attr('name');
        val = $(this).val();

        str += name+"="+val;

        if(i<len){
            str += "&,"
        }

    });

    i = 0;
    var elems = str.split(",");

    str = "";
    while(i<=len){
        str += elems[i];
        i++
    }


        var xhttp = new XMLHttpRequest();

        xhttp.onreadystatechange = function() {

            if((document.getElementById("raport")!=undefined || document.getElementById("raport")!=null) && this.readyState == 4 && this.status == 200){
                document.getElementById("raport").innerHTML = this.responseText;
            }

        };

        xhttp.open("GET", str, false);      
        xhttp.send();

}

How to envoke it:

<button type="button" onclick="uzim_vred('yourPHPscript.php',$(this).parent().attr('id'))">Send</button>

First argument is a path to and name of php script, second is used for id of form element from whom you want to "serialize" values.

\$\endgroup\$
3
\$\begingroup\$

You are not really implementing in plain JavaScript in that you are using jQuery inside the function. This seems to be an odd choice. Are you using jQuery or not? You should make a decision. If you are using jQuery, then I don’t know why this function would exist at all.

The function name itself is meaningless and does not at all convey what the function does.

You are not url encoding your query string.

You are not handling case where your asynchronous fails to return 200 response.

You are using loop counters where you don’t really need to.

It makes no sense how you build a query string then split it apart and then reassemble it.

Code style is problematic:

  • inconsistent indentation
  • lines of code that are too long
\$\endgroup\$
  • \$\begingroup\$ Concerning "inconsistent indentation", couldn't get to display properly when code is pasted. About second remark, i guess it is about addressing too long if's ... whose checks are needed. About 200 response thingy concern ... there is a check for it, look it up. About loops, i needed it since first parameter is name used in $_GET variable and second is value for said variable e.g $_GET["firstname"], has value "John" for example. Loops are used for proper appending of string in correct format for sending to php file. \$\endgroup\$ – Veljko Stefanovic Feb 22 '18 at 16:26
  • \$\begingroup\$ And sorry for not implement in full in plain JS as i previously stated. Long night -> no sleep. This has been rectified. \$\endgroup\$ – Veljko Stefanovic Feb 22 '18 at 16:37
  • \$\begingroup\$ @VeljkoStefanovic Please see What to do when someone answers. I have rolled back Rev 3 → 1. \$\endgroup\$ – 200_success Feb 22 '18 at 17:28
  • \$\begingroup\$ Code is edited according to your remarks. \$\endgroup\$ – Veljko Stefanovic Feb 22 '18 at 17:51
1
\$\begingroup\$
$("#"+parent_id+" [name]")

If you are using jQuery, then why not use the serialize method? I think that is what Mike was suggesting.

\$\endgroup\$
  • \$\begingroup\$ For some strange way, .serialize() didn't work properly in my implementation of it. So i needed alternative way to serialize inputs and selects. \$\endgroup\$ – Veljko Stefanovic Feb 22 '18 at 17:56
  • \$\begingroup\$ It would help to see your html. For example, serialize won't work if you don't have your inputs within a form. \$\endgroup\$ – Pslice Feb 22 '18 at 18:00
  • \$\begingroup\$ @VeljkoStefanovic: So $(parent_id).serialize() doesn't work? Sounds like you are using the serialize method wrong. \$\endgroup\$ – Greg Burghardt Feb 22 '18 at 18:00
  • \$\begingroup\$ @Greg Burghardt it is working, but not in this particular case. And yes, i tried it and used it many times. I don't if it's because browser, xampp, my version of php or something else, but in this particular case with this particular code doesn't work ... as intended that is. \$\endgroup\$ – Veljko Stefanovic Feb 22 '18 at 18:11
  • \$\begingroup\$ @Pslice It's modified bootstrap form which needs to be modified in this particular case. Don't want to paste it here, since by guidelines this is code review offshoot of SO. \$\endgroup\$ – Veljko Stefanovic Feb 22 '18 at 18:21
0
\$\begingroup\$

Revised code as per remarks of Mike Brant and 200_success:

function serialization(phpdoc,me){

    var parent_id = me.parentNode.id
    var name = "";
    var val = "";
    var str = phpdoc+"?,";
    var i = 0;

    var net = document.getElementById(parent_id).querySelectorAll("#"+parent_id+" [name]");
    var len = document.getElementById(parent_id).length-1;

    while(i<len) {

        name = net[i].getAttribute("name");
        val = net[i].value;

        i++
        str += name+"="+val;

        if(i<len){
            str += "&,"
        }

    }

    i = 0;
    var elems = str.split(",");

    str = "";
    while(i<=len){
        str += elems[i];
        i++
    }
    str = encodeURI(str);

    var xhttp = new XMLHttpRequest();

    xhttp.onreadystatechange = function() {

        if((document.getElementById("raport")!=undefined || document.getElementById("raport")!=null) && this.readyState == 4 && this.status == 200){
            document.getElementById("raport").innerHTML = this.responseText;
        }

    };

    xhttp.open("GET", str, false);      
    xhttp.send();

}

And how to envoke it:

<button type="button" onclick="serialize('yourPHPscript.php',this)">Send</button>
\$\endgroup\$
  • 1
    \$\begingroup\$ Could you please summarize the changes you've made? It's currently a code dump and this is off-topic. \$\endgroup\$ – t3chb0t Feb 22 '18 at 20:42
  • \$\begingroup\$ @t3chb0t Well i renamed function for easier understanding what it does in english as opposite was doing before i.e. "uzim_vred" in my language basically means tak_val or gat_val for taking or gathering values. Indentations were ok in my code editor but got little jittery when i pasted here, that's one of a changes. Also added encoding if you send data to remote location. Also in previous iteration of code, as a second parametar i used Jquery code that envoke parent element id, currently it uses 'this' keyword because i intended to use vanilla JS but couldn't implement it at a time. \$\endgroup\$ – Veljko Stefanovic Feb 23 '18 at 16:55
  • \$\begingroup\$ @ t3chb0t They both work identically, but second iteration is completely done in JS AJAX, first is mix of JS and it's framework JQuery as you can see. \$\endgroup\$ – Veljko Stefanovic Feb 23 '18 at 16:55
  • \$\begingroup\$ @t3chb0t Instead var parent_id = me.parentNode.id , change it to var FormId = me.form.id; And change it whenever is mentioned. At first didn't count usage when element is nested inside another element. Sorry, my bad. \$\endgroup\$ – Veljko Stefanovic Mar 3 '18 at 0:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.