Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    New Coder
    Join Date
    May 2013
    Posts
    41
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Json, Ajax, PHP - form send does not work

    Hi.

    I'm not sure this this is the right forum to post my problem. If not, I'm really sorry.

    I downloaded an Ajax and PHP based Contact Form, and adapted it to match my form and my purpose. The downloaded file works the way I want, but the changed file doesn't. The only thing I get after submitting the form is a message with null. I can't find what is wrong. Can some one help me finding the problem? Here is my code:

    index.html

    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <title>Formulário de Registo</title>
    
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    
    <script type="text/javascript">
    $(document).ready(function() {
        $("#submit_reg_form").click(function() { 
            //get input field values
            var first_name       = $('input[name = fname]').val(); 
            var last_name        = $('input[name = lname]').val(); 
            var user_email       = $('input[name = email]').val();
            var password1        = $('input[name = pwd1]').val();
            var password2        = $('input[name = pwd2]').val();
    
            //simple validation at client's end
            //we simply change border color to red if empty field using .css()
            var proceed = true;
            if(first_name==""){ 
                $('input[name = fname]').css('border-color','red'); 
                proceed = false;
            }
            if(last_name==""){ 
                $('input[name = lname]').css('border-color','red'); 
                proceed = false;
            }
            if(user_email==""){ 
                $('input[name = email]').css('border-color','red'); 
                proceed = false;
            }
            if(password1=="") {    
                $('input[name = pwd1]').css('border-color','red'); 
                proceed = false;
            }
            if(password2=="") {    
                $('input[name = pwd2]').css('border-color','red'); 
                proceed = false;
            }
    
            //everything looks good! proceed...
            if(proceed) 
            {
                //data to be sent to server
                post_data = {'fname':first_name, 'lname':last_name, 'email':user_email, 'pwd1':password1, 'pwd2':password2};
                
                //Ajax post data to server
                $.post('contact_me.php', post_data, function(response){  
    
                    //load json data from server and output message     
    				if(response.type == 'error')
    				{
    					output = '<div class="error">'+response.text+'</div>';
    				}else{
    				    output = '<div class="success">'+response.text+'</div>';
    					
    					//reset values in all input fields
    					$('#regist_form input').val(''); 
    				}
    				
    				$("#result").hide().html(output).slideDown();
                }, 'json');
    			
            }
        });
        
        //reset previously set border colors and hide all message on .keyup()
        $("#regist_form input, #regist_form textarea").keyup(function() { 
            $("#regist_form input, #regist_form textarea").css('border-color',''); 
            $("#result").slideUp();
        });
        
    });
    </script>
    <link href="style.css" rel="stylesheet" type="text/css" />
    </head>
    
    <body>
      <fieldset id="regist_form">
      <legend>Sua Identificação</legend>
          <label for="fname"><span>Primeiro Nome: </span>
          <input type="text" name="fname" id="fname" placeholder="Primeiro nome" />
          </label>
          
          <label for="lname"><span>Último Nome: </span>
          <input type="text" name="lname" id="lname" placeholder="Último nome" />
          </label>
          
          <label for="email"><span>Endereço de Email: </span>
          <input type="email" name="email" id="email" placeholder="Endereço de email" />
          </label>
          
          <label for="pwd1"><span>Senha: </span>
          <input type="password" name="pwd1" id="pwd1" placeholder="Senha" />
          </label>
          
          <label for="pwd2"><span>Confirme a Senha: </span>
          <input type="password" name="pwd2" id="pwd2" placeholder="Confirme a senha" />
          </label>
          
         <label><span>&nbsp;</span>
          <button class="submit_reg_form" id="submit_reg_form">Registar</button>
          </label>
      </fieldset>
    </body>
    </html>
    The contact_me.php

    Code:
    <?php
    
    if($_POST)
    {
    	//check if its an ajax request, exit if not
        if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
    	
    		//exit script outputting json data
    		$output = json_encode(
    		array(
    			'type'=>'error', 
    			'text' => 'Request must come from Ajax'
    		));
    		
    		die($output);
        } 
    	
    	//check $_POST vars are set, exit if any missing
    	if(!isset($_POST["fname"]) || !isset($_POST["lname"]) || !isset($_POST["email"]) || !isset($_POST["pwd1"]) || !isset($_POST["pwd2"]))
    	{
    		$output = json_encode(array('type'=>'error', 'text' => 'Há campos vazios! Todos os campos são obrigatórios'));
    		die($output);
    	}
    
    	//Sanitize input data using PHP filter_var().
    	$first_name = filter_var($_POST["fname"], FILTER_SANITIZE_STRING);
    	$last_name  = filter_var($_POST["lname"], FILTER_SANITIZE_STRING);
    	$user_email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
    	$password1  = filter_var($_POST["pwd1"], FILTER_SANITIZE_STRING);
    	$password2  = filter_var($_POST["pwd2"], FILTER_SANITIZE_STRING);
    
    	//additional php validation
    	if(strlen($first_name)<2) // If length is less than 2 it will throw an HTTP error.
    	{
    		$output = json_encode(array('type'=>'error', 'text' => 'Primeiro Nome tem menos de 2 caracteres ou está vazio'));
    		die($output);
    	}
    
    	if(strlen($last_name)<2) // If length is less than 2 it will throw an HTTP error.
    	{
    		$output = json_encode(array('type'=>'error', 'text' => 'Ultimo Nome tem menos de 2 caracteres ou está vazio'));
    		die($output);
    	}
    
    	if(!filter_var($user_email, FILTER_VALIDATE_EMAIL)) //email validation
    	{
    		$output = json_encode(array('type'=>'error', 'text' => 'Introduza um email válido'));
    		die($output);
    	}
    
    	if(strlen($password1)<5) // If length is less than 2 it will throw an HTTP error.
    	{
    		$output = json_encode(array('type'=>'error', 'text' => 'Senha tem menos de 2 caracteres ou está vazia'));
    		die($output);
    	}
    
    	if(strlen($password2)<5) // If length is less than 2 it will throw an HTTP error.
    	{
    		$output = json_encode(array('type'=>'error', 'text' => 'Confimação da senha tem menos de 2 caracteres ou está vazia'));
    		die($output);
    	}
    
    	if($password1 != $password2) //check if passwords are the same
    	{
    		$output = json_encode(array('type'=>'error', 'text' => 'As Senhas não coorrespondem'));
    		die($output);
    	}
    }
    ?>
    Can some one help me?

    Thank you

  • #2
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    4,606
    Thanks
    24
    Thanked 647 Times in 646 Posts
    I believe your output should write to something with an ID of result. I don't see one in your HTML.
    Evolution - The non-random survival of random variants.

    "If you leave hydrogen alone, for long enough, it begins to think about itself."

  • #3
    Senior Coder
    Join Date
    Sep 2010
    Posts
    2,451
    Thanks
    17
    Thanked 275 Times in 275 Posts
    I only see some if(!isset) statements, and not an if(isset) , so it doesn't appear as if the form will submit to the php.
    Welcome to http://www.myphotowizard.net

    where you can edit images, make a photo calendar, add text to images, and do much more.


    When you know what you're doing it's called Engineering, when you don't know, it's called Research and Development. And you can always charge more for Research and Development.

  • #4
    Senior Coder
    Join Date
    Jan 2011
    Location
    Missouri
    Posts
    4,606
    Thanks
    24
    Thanked 647 Times in 646 Posts
    @DrDOS
    I think your looking at his "contact_me.php". His "index.html" does submit via Jquery, but to call it a form is stretching things. It's a group of input tags with a button.
    Evolution - The non-random survival of random variants.

    "If you leave hydrogen alone, for long enough, it begins to think about itself."

  • #5
    New Coder
    Join Date
    Aug 2014
    Posts
    27
    Thanks
    0
    Thanked 1 Time in 1 Post
    to submit a form with AJAX:
    $j('#myForm').submit();


    $j.ajax({
    type: 'POST',
    url: 'one.php',
    data: {
    myText: $j('#myText').val(),
    myButton: $j('#myButton').val()
    },
    success: function(response, textStatus, XMLHttpRequest) {
    $j('div.ajax').html(response);
    }
    });


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •