39

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;
}
Erick Petrucelli
  • 14,386
  • 8
  • 64
  • 84
Butterflycode
  • 759
  • 2
  • 10
  • 23
  • You can use the following jQuery plugin: https://github.com/jinujd/jQuery-Async-Form – Jinu Joseph Daniel Aug 20 '15 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. – user2225804 Oct 18 '20 at 13:58

4 Answers4

52

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);
    }
}
Matt Bryant
  • 4,841
  • 4
  • 31
  • 46
  • 9
    +1 for the AJAX with on JQuery – Dmitri Sep 04 '14 at 22:00
  • 2
    ^ Very handy for those of us doing pages on embedded systems. – Dmitri Sep 04 '14 at 22:16
  • 1
    This still seems to reload the page for me. Anybody else? – jordan Jan 21 '15 at 22:18
  • 14
    This will only execute the javascript function without reloading the page – s-hunter Mar 11 '16 at 01:36
  • Does not pass parameters for me. Nice code, exactly what I need... – 3xCh1_23 Jan 13 '17 at 14:54
  • How to use this without reloading the page? – Dumb Question Feb 06 '17 at 03:24
  • 1
    Not working, page is reloading. – Markus L Jun 19 '17 at 14:12
  • Is this secure? As far as I understand, retreiving things like login credentials from html to Javascript makes things for hackers easyer right? Or does a simple ssl fix this? I know ssl makes the ajax call secure. – Allart Jan 20 '21 at 12:25
  • @s-hunter My page reloads, even when I use that trick. – Darien Marks Apr 17 '21 at 13:10
  • 1
    Can't add a new answer, but the page reloads because that's the default behavior on form submission. To prevent this, we have to prevent the default behavior. 1) Alter the JS function definition to capture the submission event: `function submitForm(evt) {` 2) Prevent the event's default behavior with this line anywhere within the `submitForm()` function: `evt.preventDefault();` – Darien Marks Apr 17 '21 at 13:46
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.
});
Ahsan Shah
  • 3,931
  • 1
  • 34
  • 48
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; 
}
SarathSprakash
  • 4,614
  • 2
  • 19
  • 35
-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 = "";
Butterflycode
  • 759
  • 2
  • 10
  • 23