Monday, March 19, 2012

Pass all the Form elements to call JSON


If you call any server file on the live server to get json data, then may be you need to transfer some variables with value. for ex. if you need to insert data to your server then you must haveto post all data to server file.

First you need to follow my previous blog(get-data-using-cross-domain-request).

Create one form element and create all the variable into the form tag that you want to post on the server.
Create below function in the .js file.

function createQuery(fname)
{
     var formname= fname;
     var elements = document.getElementById(formname).elements;
     var pairs = new Array();
var next_el = "";
var checkdetail=""
    for (var i = 0; i < elements.length; i++)
   {

       if ((name = elements[i].name) && (value = elements[i].value))
//alert(elements[i].type);
if(elements[i].type == 'select-multiple')
{
ob=elements[i].length;
var selected_op = "";
for(var j = 0; j < ob; j++)
{
if(elements[i].options[j].selected)
{
selected_op+= '|'+elements[i].options[j].value;
}
}
lastin = selected_op.length;
selected_op = selected_op.substring(1,lastin);
pairs.push(name + "=" + encodeURIComponent(selected_op));
}
else if(elements[i].type == 'radio')
{
if(elements[i].checked)
{
pairs.push(name + "=" + encodeURIComponent(value));
}
}
else if(elements[i].type == 'checkbox' )
{
if(elements.length != i)
               {
next_el = elements[i+1].name;
}
if(elements[i].checked)
{
checkdetail+= '|'+value;
}
if(next_el != elements[i].name || elements.length == i)
{
lastin = checkdetail.length;
checkdetail = checkdetail.substring(1,lastin);
pairs.push(name + "=" + encodeURIComponent(checkdetail));
checkdetail ="";
}
}
else
{
pairs.push(name + "=" + encodeURIComponent(value));
}
    }
    return pairs.join("&");
}

Create one function to call createQuery function.

function postdatato_server(){
     var url="www.yourserver.com/save.php";
    query= createQuery("formname");
  var path=url+ "?"+ query;
  requestCrossDomain(path, function(results) {
$('#result').html(results);
});
return false;
}

Alert path variable and check the URL

Cheers...:)

No comments:

Post a Comment