Asked  8 Months ago    Answers:  5   Viewed   38 times

I have looked through all the similar posts out there but nothing seems to help. This is what I have

HTML:

<section>
  <form id="contact-form" action="" method="post">
    <fieldset>
      <input id="name" name="name" placeholder="Name" type="text" />
      <input id="email" name="email" placeholder="Email" type="text" />
      <textarea id="comments" name="comments" placeholder="Message"></textarea>
      <div class="12u">
        <a href="#" id="form-button-submit " class="button" onClick="sendForm()">Send Message</a>
        <a href="#" id="form-button-clear" class="button" onClick="document.getElementById('contact-form').reset()">Clear Form</a>
      </div>
      <ul id="response"></ul>
    </fieldset>
  </form>
</section>

JavaScript/jQuery:

function sendForm() {
  var name = $('input#name').val();
  var email = $('input#email').val();
  var comments = $('textarea#comments').val();
  var formData = 'name=' + name + '&email=' + email + '&comments=' + comments;
  $.ajax({
    type: 'post',
    url: 'js/sendEmail.php',
    data: formData,
    success: function(results) {
      $('ul#response').html(results);
    }
  }); // end ajax
}

What I am unable to do is prevent the page refresh when the #form-button-submit is pressed. I tried return false; I tried preventDefault() and every combination including return false; inside the onClick. I also tried using input type="button" and type="submit" instead and same result. I can't solve this and it is driving be nuts. If at all possible I would rather use the hyperlink due to some design things. I would really appreciate your help on this.

 Answers

13

Modify the function like this:

function sendForm(e){
  e.preventDefault();
}

And as comment mentions, pass the event:

onclick = sendForm(event);

Update 2:

$('#form-button-submit').on('click', function(e){
   e.preventDefault();

   var name = $('input#name').val(),
       email = $('input#email').val(),
       comments = $('textarea#comments').val(),
       formData = 'name=' + name + '&email=' + email + '&comments=' + comments;

    $.ajax({
      type: 'post',
      url: 'js/sendEmail.php',
      data: formData,
      success: function(results) {
        $('ul#response').html(results);
      }
    });
});
Wednesday, March 31, 2021
 
dimitarvp
answered 8 Months ago
13

OOOHHHHHH I've written the .load()at the wrong place now it works:

$.ajax({
    type:"POST",
    url:"/update_rows.php",
    data:"delete_id="+$(this).attr("row"),
    success:function(data) {
        if(data) {

        } else {
            $(".refresh-after-ajax").load(window.location + " .refresh-after-ajax");
        }

    }
});

Thanks for the help, the $(this).remove() would also have been a nice solution

Wednesday, March 31, 2021
 
pamelus
answered 8 Months ago
44

i think you have to change the logic flow to do so. try the following code which i have tested on my PC.

<script src="jquery-1.11.1.js"></script>
<form id="myData" class="form_pro" method="post" role="form">

    <input type="text" class="form" name="E-mail" placeholder="E-mail" value="">
    <div class="error"></div>
    <button name="submit" type="button" class="action_button" onclick="doSubmit();">OK</button>
 </form>

<script>
    function doSubmit(){
        $.ajax({
            url:'interuni_process.php',
            data:$("#myData").serialize(),
            type:'POST',
            success: function (data, textStatus, jqXHR) {
                if(data==="SUCCESS"){
                    $(".error").text("No error occurred");
                }else{
                    $(".error").text("Error occurred: "+ data);
                }
            }
        });
    };
</script>

and sample code for "interuni_process.php" is

<?php
    $eMail=$_POST["E-mail"];

    if($eMail===""){ //or whatever process condition you want to do
        echo "Email cannot be blank";
    }else{
        echo "SUCCESS";
    }
?>

modify business logic as your per requirement

Saturday, May 29, 2021
 
BrunoRamalho
answered 5 Months ago
36

In your case the best option to retrieve values as JSON format using json_encode in your PHP code and then accessing these values through data object.

Example:

PHP code:

if($_POST)
{
    $result['firstname'] = $_POST['firstname'];
    $result['lastname'] = $_POST['lastname'];

    echo json_encode($result);
    die(); // Use die here to stop processing the code further 
}

JS code:

$("#myform").submit(function (e) {

    $.ajax({
        type : "POST",
        url : 'new1.php',
        dataType : 'json', // Notice json here
        data : $("#myform").serialize(), // serializes the form's elements.
        success : function (data) {
            alert('yeah'); // show response from the php script.
            // make changed here
            $('input[name="firstname"]').text(data.firstname);
            $('input[name="lastname"]').text(data.lastname);
        }
    });

    e.preventDefault(); // avoid to execute the actual submit of the form.
});
Saturday, May 29, 2021
 
mnagel
answered 5 Months ago
70

You have an error in jQuery code:

Error:

buildingVal = $("#building").val();
levelVal = $("#level").val();
data = 'building=' + buildingVal.val() + 'level=' + levelVal.val();

Solution:

buildingVal = $("#building");
levelVal = $("#level");
data = 'building=' + buildingVal.val() + '&level=' + levelVal.val();

Complete code js:

$('#submit_button').click(function () {        

   var 
       buildingVal = $("#building"),
       levelVal = $("#level"),
       data = 'building=' + buildingVal.val() + '&level=' + levelVal.val();


   $.ajax({
      'url': 'res.php', 
      'type': 'POST',
      'data': data,     
      'success': function (data) {
      }
   });

   return false;

});

Edit

If your ever going to use this form to send data by ajax, the best way is to cancel the event "submit" the form:

HTML:

<form id="myform" method="post" action="<?php echo $_SERVER['PHP_SELF'] ;?>" >
...
</form>

JS:

$('#myform').bind('submit', function(event) {

     return false;
});

$('#submit_button').bind('click', function () {        

   var 
       buildingVal = $("#building"),
       levelVal = $("#level"),
       data = 'building=' + buildingVal.val() + 'level=' + levelVal.val();


   $.ajax({
      'url': 'res.php', 
      'type': 'POST',
      'data': data,     
      'success': function (data) {
      }
   });

});
Saturday, May 29, 2021
 
avon_verma
answered 5 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :