38

I have a function built in JavaScript that I want to be executed after a form submit is hit. It basically changes the look of the page completely. But I need a variable from the search box to still go through to the JavaScript. At the moment it flashes and resets what was there because it reloads the page.

So I set up a return false in my function which keeps it from doing that but the variable I want doesn't get submitted through the form. Any ideas on what I should do to get it? It's okay for the page to refresh as long as the updateTable() function works and isn't reset by the page reset.

<form action="" method="get" onsubmit="return updateTable();">
  <input name="search" type="text">
  <input type="submit" value="Search" >
</form>

This is the updateTable function:

function updateTable() { 
  var photoViewer = document.getElementById('photoViewer');
  var photo = document.getElementById('photo1').href;
  var numOfPics = 5;
  var columns = 3; 
  var rows = Math.ceil(numOfPics/columns);
  var content="";
  var count=0;

  content = "<table class='photoViewer' id='photoViewer'>";
  for (r = 0; r < rows; r++) {
    content +="<tr>";
    for (c = 0; c < columns; c++) {
      count++;
      if(count == numOfPics) break; // check if number of cells is equal number of pictures to stop
      content +="<td><a href='"+photo+"' id='photo1'><img class='photo' src='"+photo+"' alt='Photo'></a><p>City View</p></td>";
    }
    content +="</tr>";
  }
  content += "</table>";
  photoViewer.innerHTML = content;
}
2
  • You can use the following jQuery plugin: github.com/jinujd/jQuery-Async-Form Aug 20, 2015 at 20:55
  • 2
    This should not be closed. The link above goes to a page that mostly forces the use of jquery. The accepted answer here uses XMLHttpRequest, which I believe is the modern solution, and in any event does not require adding a jquery dependency for form submission. Oct 18, 2020 at 13:58

4 Answers 4

51

You can't do this using forms the normal way. Instead, you want to use AJAX.

A sample function that will submit the data and alert the page response.

function submitForm() {
    var http = new XMLHttpRequest();
    http.open("POST", "<<whereverTheFormIsGoing>>", true);
    http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    var params = "search=" + <<get search value>>; // probably use document.getElementById(...).value
    http.send(params);
    http.onload = function() {
        alert(http.responseText);
    }
}
10
  • 9
    +1 for the AJAX with on JQuery
    – Dmitri
    Sep 4, 2014 at 22:00
  • 2
    ^ Very handy for those of us doing pages on embedded systems.
    – Dmitri
    Sep 4, 2014 at 22:16
  • 1
    This still seems to reload the page for me. Anybody else?
    – jordan
    Jan 21, 2015 at 22:18
  • 14
    <form action="" method="get" onsubmit="updateTable();return false;"> This will only execute the javascript function without reloading the page
    – s-hunter
    Mar 11, 2016 at 1:36
  • 1
    Not working, page is reloading.
    – Markus L
    Jun 19, 2017 at 14:12
38

You can use jQuery serialize function along with get/post as follows:

$.get('server.php?' + $('#theForm').serialize())

$.post('server.php', $('#theform').serialize())

jQuery Serialize Documentation: http://api.jquery.com/serialize/

Simple AJAX submit using jQuery:

// this is the id of the submit button
$("#submitButtonId").click(function() {

    var url = "path/to/your/script.php"; // the script where you handle the form input.

    $.ajax({
           type: "POST",
           url: url,
           data: $("#idForm").serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert(data); // show response from the php script.
           }
         });

    return false; // avoid to execute the actual submit of the form.
});
3
  • 5
    The question is not tagged jQuery, though serialize() is pretty neat. Aug 11, 2013 at 8:13
  • 4
    Why the downvote though? I see people posting jQuery answers all the time, even when jQuery is not tagged... Aug 11, 2013 at 8:22
  • 3
    @AhsanShah There are other frameworks as well. Maybe (and probably) the OP is learning Javascript and wants to know how it should be done.
    – the_drow
    Aug 11, 2013 at 8:40
0

I guess this is what you need. Try this .

<form action="" method="get">
                <input name="search" type="text">
                <input type="button" value="Search" onclick="return updateTable();">
                </form>

and your javascript code is the same

function updateTable()
    {   
        var photoViewer = document.getElementById('photoViewer');
        var photo = document.getElementById('photo1').href;
        var numOfPics = 5;
        var columns = 3; 
        var rows = Math.ceil(numOfPics/columns);
        var content="";
        var count=0;

        content = "<table class='photoViewer' id='photoViewer'>";
            for (r = 0; r < rows; r++) {
                content +="<tr>";
                for (c = 0; c < columns; c++) {
                    count++;
                    if(count == numOfPics)break; // here is check if number of cells equal Number of Pictures to stop
                        content +="<td><a href='"+photo+"' id='photo1'><img class='photo' src='"+photo+"' alt='Photo'></a><p>City View</p></td>";
                }
                content +="</tr>";
            }
        content += "</table>";

        photoViewer.innerHTML = content; 
}
1
  • 3
    What about if you have got 100 radiobuttons generated on fly?
    – NoWar
    May 19, 2015 at 15:09
-2

I did it a different way to what I was wanting to do...gave me the result I needed. I chose not to submit the form, rather just get the value of the text field and use it in the javascript and then reset the text field. Sorry if I bothered anyone with this question.

Basically just did this:

    var search = document.getElementById('search').value;
    document.getElementById('search').value = "";

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