Ignas
Ignas

Reputation: 61

how to send form values to php using AJAX without reloading page?

I have this AJAX function which starts PHP function in server without reloading page and sends back generated info, but I also need to send a form input values to that PHP script how do I do that?

AJAX:

    function sorting() 
{

  var ajax = getRequest();
  ajax.onreadystatechange = function()
  {
      if(ajax.readyState == 4)
      {
          document.getElementById('main').innerHTML = ajax.responseText;
      }

  }
  document.getElementById('main').innerHTML = "<br/><img src=img/ajax-loader.gif><br/><br/>";
  ajax.open("POST", "sorting.php", true);
  ajax.send(null);
}

Truncated HTML form:

 <form method="post"  action="" name="dateform" id="dateform">

<select name="n_metai" id="n_metai" ><option value="1">1</option>... 
</select>   

<select name="n_menuo" id="n_menuo" ><option value="2">2</option>... 
</select> 

<input type="text" name="skaitliukas" id="skaitliukas" size="3" value="1" title="Mažiausias skambučių pasikartojimas">

<input type="checkbox" name="nuliniai" id="nuliniai"   value="1" title="Rodyti tik su nulinėmis trukmėmis">

<button name="submit_button" onclick='sorting(); return false;'> Pateikti</button>
</form>

Upvotes: 1

Views: 1941

Answers (2)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76408

The problem is this line:

ajax.send(null);

If you were to send a GET request, then you pass nothing (or null) to the send call, but you're POST-ing data, so you'll have to pass the data through there.
A basic way to do that, would be this:

var frm = document.getElementById('dateform'),
data = [];//empty array
for (var i=0;i<frm.elements.length;i++)
{
    data.push(frm.elements[i].name + '=' + frm.elements[i].value);
}
ajax.send(data.join('&'));

Upvotes: 1

Yura Sokolov
Yura Sokolov

Reputation: 207

You can use jQuery for that.

$.ajax({
type: "post", //methos
url: "yourpage.php", //where to post
data: { //parameters
    n_metai: $('select[name="n_metai"] option:selected').val(), 
    skaitliukas: $('#skaitliukas').val()
    //etc...
}
}).done(function(msg) {
    alert( "Done: " + msg ); //display message box with replay
});

Upvotes: 1

Related Questions