aleczandru
aleczandru

Reputation: 5449

Return from Ajax gives back entire html structure

Hi I am just learning to work with jQuery/ajax.And I seem to be having some problems.When I trying to post some form data , I get back from the server my entire html structure and the data I am returning.

This is my html:

   ....
   <form id="submitData" method="post" action="">
        <div>
            <label for="FirstName">First Name:</label>
            <input type="text" id="FirstName" name="FirstName"/><span class="error">*</span>
        </div>
        ........
        <div id="textearea">
            <label for="Message">Message:</label>
            <textarea name="Message"></textarea><span class="error">*</span>
        </div>
        <input type="submit" id="submit" name="submit" value="Submit"/>
    </form>
    .....

This is my php code :

<?php
      if(isset($_POST['data'])){
          $jsonData = json_encode($_POST['data']);

          return $jsonData;
      }
   ?>

And this is my jQuery code:

$(document).on('submit' , 'form#submitData' , function(e){

     var formData = $(this).serializeArray();
     console.log(formData);

     $.ajax({
         url:'index.php',
         type:'POST',
         datatype:'json',
         data: { data : formData},
         success : function(data){
             for(var i = 0; i < data.length; i++){
                 console.log(data);

             }
         },
         error : function(s , i , error){
             console.log(error);
         }
     })
     e.preventDefault();
 });

I have tryed accesing the data in a loop but I seem to be getting back the letter from the html structure.I should also mention that that the html for the form is loaded into the page using jquery load().

How can I make it so that I ge back only the encoded data ?

Upvotes: 1

Views: 437

Answers (1)

Louis XIV
Louis XIV

Reputation: 2224

get it from a separate PHP page :

$(document).on('submit' , 'form#submitData' , function(e){

     var formData = $(this).serializeArray();
     console.log(formData);

     $.ajax({
         // change here
         url:'ajax.php',
         type:'POST',
         datatype:'json',
         data: { data : formData},
         success : function(data){
             for(var i = 0; i < data.length; i++){
                 console.log(data);

             }
         },
         error : function(s , i , error){
             console.log(error);
         }
     })
     e.preventDefault();
 });

and put your PHP code there.

Upvotes: 2

Related Questions