1
\$\begingroup\$

I didn't find an equivalent of .serialize() for vanilla javascript, so I rolled my own.

    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 Answers 3

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\$
4
  • \$\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\$ Feb 22, 2018 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\$ Feb 22, 2018 at 16:37
  • \$\begingroup\$ @VeljkoStefanovic Please see What to do when someone answers. I have rolled back Rev 3 → 1. \$\endgroup\$ Feb 22, 2018 at 17:28
  • \$\begingroup\$ Code is edited according to your remarks. \$\endgroup\$ Feb 22, 2018 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\$
5
  • \$\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\$ Feb 22, 2018 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, 2018 at 18:00
  • \$\begingroup\$ @VeljkoStefanovic: So $(parent_id).serialize() doesn't work? Sounds like you are using the serialize method wrong. \$\endgroup\$ Feb 22, 2018 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\$ Feb 22, 2018 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\$ Feb 22, 2018 at 18:21
1
\$\begingroup\$

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

  • Renamed function for easier understanding what it does.
  • Improved indentation.
  • Added encoding if you send data to remote location.
  • Use this keyword instead of using jQuery to invoke parent element id.
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 invoke it:

<button type="button" onclick="serialize('yourPHPscript.php',this)">Send</button>
\$\endgroup\$
0

Your Answer

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

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