1

Im making some web appication which loads pages without refresching te page. This all works great but now i have a form on one of these pages. I want to submit the form without the page to refresh. But when i submit the form after i loaded it with ajax the url in the browser will change from

localhost/documents/projects/test/

to

localhost.documents/projects/test/?form_type=register&Username=&first_name=&surname_prefix=&surname=&surname=&email=

When i just put the form html in my index.php and submit it there it works fine. I hope someone can tell me what im doing wrong and how to fix it.

part of index.php

<div class="message"></div>
<div id="content">
    <div id="page">
<div class="form_container">
<form id="form">
    <input type="hidden" name="form_type" value="register" />
    <input class="type_text" type="text" name="username"  maxlength="20" placeholder="username" />
    <input class="type_text" type="text" name="first_name" maxlength="50" placeholder="First Name" />
    <input class="type_text" type="text" name="surname_prefix" maxlength="20" placeholder="Surname Prefix" />
    <input class="type_text" type="text" name="surname" maxlength="50" placeholder="Surname" />
    <label class="label" for="birth_date">dd-mm-jjjj</label>
    <input id="birth_date" class="type_text" type="text" name="birth_date" maxlength="10" placeholder="Birth Date" />       
    <input class="type_text" type="text" name="email" placeholder="Email Address" />
    <input class="type_submit" type="submit" value="Register" />
</form>
</div>
</div>  

pageHandler.js

$(document).ready(function() {
var request;

    //page handler
    //pageRequest('home');
$('.click').click(function(event) {
    var temp = $(this).attr('id');
    var pages = ['home','register'];
    if($.inArray(temp, pages) !== -1) {
        pageRequest(temp);
        //$('.message').html(temp);
    }   
    event.preventDefault();
}); 

function pageRequest(temp) {
    var page = $('#page');
    if(typeof ajax_request !== 'undefined') {
        request.abort();
    }       
    request = $.ajax({
        type: "POST",       
        url: "core/posts.php",
        data: 'temp=' + temp
    });
    request.done(function(data) {
        page.fadeOut(function() {
            page.html('');
            page.html(data).fadeIn();
        }); 
    });
    request.fail(function(jqXHR, textStatus) {
        page.fadeOut(function() {
            page.html('');
            page.html(textStatus).fadeIn();
        });
    }); 
}

//form handler
$('#page').delegate( "#form", "submit", function(event) {
    var $form = $(this);
    var $inputs = $form.find("input, select, button, textarea");
    var serializedData = $form.serialize();
    $inputs.prop("disabled", true);
    formRequest(serializedData);
    event.preventDefault();     
});     

function formRequest(values) {
    var message = $('.message');
    if(typeof ajax_request !== 'undefined') {
        request.abort();
    }       
    request = $.ajax({
        url: "core/posts.php",
        type: "POST",
        data: values
    }); 
    request.done(function(data) {
        message.fadeOut(function() {
            message.html('');
            message.html(data).fadeIn();
        });
    });
    request.fail(function(jqXHR, textStatus) {
        message.fadeOut(function() {
            message.html('');
            message.html(textStatus).fadeIn();
        });
    }); 
}   
});

posts.php

If(isset($_POST['temp'])) {
    $temp = $_POST['temp'];
    $url = '../content/templates/'.$temp.'.html';
    if(file_exists($url)) {
        $html = file_get_contents($url);
        echo $html;
    }
    else {
        echo 'Sorry, couldn\'t find the page.';
    }       
}
//form handler
if(isset($_POST['form_type'])) {
    require_once('../admin/config/database.functions.php');
    $function = new myDBFunctions();
    switch($_POST['form_type']) {
        case 'register' :
            $username = $_POST['username'];
            $firstname = $_POST['first_name'];
            $surnamep = $_POST['surname_prefix'];
            $surname = $_POST['surname'];
            $birthdate = $_POST['birth_date'];              
            $email = $_POST['email'];
            echo 'Thanks for your registration';                    
            break;
        case 'login' :
            echo 'login';
            break;
        case 'password_recovery' :
            echo 'password recovery';
            break;  
    }
}

I have found the problem but not why it occured. I had a $_POST['username'] in my posts.php file while the the name of the html input field was Username. I have changed this and now the url in the browser doesn't change anymore. I'm happy I've found the problem but i still dont get why the data send by ajax would appair in the url.

1 Answer 1

0

"I want to submit the form without the page to refresh"

There are a few ways to do this, I think the easiest is to intercept and stop the form from actually submitting like a regular HTML form and instead make an ajax call with the data in the form fields.

To do this, you will need to intercept the submit event of the form, get the values of all the inputs in the form and make an ajax call with the data to the server:

<form id="myForm">
  ....
</form>
<script>
$('#form').on("submit", function(event) {
  // stop the form from submitting
  event.preventDefault();

  // get data in the inputs of the form
  var data = {};
  var $inputs = $('#form').children("input, select, textarea");
  inputs.each(function($element){
    data[$element.attr('name')] = $element.val();
  });

  // submit data to the backend
  request = $.ajax({
    type: "POST",       
    url: "",
    data: data
  });
});
</scipt>
Sign up to request clarification or add additional context in comments.

1 Comment

hmm I already have this. Using on() instead of deligate() didn't make a difference also getting the input values like that instead of using serialize didn't make a difference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.