0

I Have an requirement to pass form data to php using ajax and implement it in php to calculate the sum , division and other arithmetic methods I am a new to ajax calls trying to learn but getting many doubts.... It would be great help if some one helps me out with this

index.html

<script type="text/javascript">
$(document).ready(function(){

  $("#submit_btn").click(function() {
         $.ajax({

      url: 'count.php',

    data: data,
        type: 'POST',
        processData: false,
        contentType: false,
        success: function (data) {
            alert('data');
        }
     })

});
    </script>
</head>

<form name="contact" id="form" method="post" action="">

      <label  for="FNO">Enter First no:</label>
      <input type="text" name="FNO" id="FNO" value=""  />
label for="SNO">SNO:</label>
                        <input type="text" name="SNO" id="SNO" value="" />

      <input type="submit" name="submit" class="button" id="submit_btn" value="Send" />

  </form>

In count.php i want to implement

<?php
$FNO = ($_POST['FNO']);
$SNO=($_post['SNO']);


$output=$FNO+$SNO;
echo $output;

?>

(i want to display output in count.php page not in the first page index.html) Thanks for your help in advance.

1
  • Please review the current answers. Make sure you accept an answer so others can see the correct answer to your question in case someone else has the same issue. Commented Apr 10, 2013 at 2:24

4 Answers 4

2

You can use a simple .post with AJAX. Take a look at the following code to be able to acheive this:

$('#form').submit(function() {  
alert($(this).serialize()); // check to show that all form data is being submitted
$.post("count.php",$(this).serialize(),function(data){
    alert(data); //check to show that the calculation was successful                        
});
return false; // return false to stop the page submitting. You could have the form action set to the same PHP page so if people dont have JS on they can still use the form
});

This sends all of your form variables to count.php in a serialized array. This code works if you want to display your results on the index.html.

I saw at the very bottom of your question that you want to show the count on count.php. Well you probably know that you can simply put count.php into your form action page and this wouldn't require AJAX. If you really want to use jQuery to submit your form you can do the following but you'll need to specify a value in the action field of your form:

$("#submit_btn").click(function() {
    $("#form").submit();
});
Sign up to request clarification or add additional context in comments.

Comments

2

I have modified your PHP code as you made some mistakes there. For the javscript code, i have written completely new code for you.

Index.html

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

</head>
<body>
<form name="contact" id="contactForm" method="post" action="count.php">

      <label  for="FNO">Enter First no:</label>
      <input type="text" name="FNO" id="FNO" value=""  />
<label for="SNO">SNO:</label>
                        <input type="text" name="SNO" id="SNO" value="" />

      <input type="submit" name="submit" class="button" id="submit_btn" value="Send" />

  </form>

  <!-- The following div will use to display data from server -->
<div id="result"></div>
</body>


  <script>

  /* attach a submit handler to the form */
  $("#contactForm").submit(function(event) {
  /* stop form from submitting normally */  
  event.preventDefault();

  /* get some values from elements on the page: */
  var $form = $( this ),
  //Get the first value
  value1 = $form.find( 'input[name="SNO"]' ).val(),
  //get second value
  value2 = $form.find( 'input[name="FNO"]' ).val(),
  //get the url. action="count.php"
  url = $form.attr( 'action' );

  /* Send the data using post */
  var posting = $.post( url, { SNO: value1, FNO: value2 } );

  /* Put the results in a div */
  posting.done(function( data ) {

  $( "#result" ).empty().append( data );
  });
  });
  </script>
</html>

count.php

<?php
$FNO =  $_POST['FNO'];
$SNO= $_POST['SNO'];


$output = $FNO + $SNO;
echo $output;

?>

Comments

1

There are a few things wrong with your code; from details to actual errors.

If we take a look at the Javascript then it just does not work. You use the variable data without ever setting it. You need to open the browser's Javascript console to see errors. Google it.

Also, the javascript is more complicated than is necessary. Ajax requests are kind-of special, whereas in this example you just need to set two POST variables. The jQuery.post() method will do that for you with less code:

<script type="text/javascript">
$(document).ready(function(){
  $("#form").on("submit", function () {
    $.post("/count.php", $(this).serialize(), function (data) {
      alert(data);
    }, "text");
    return false;
  });
});
</script>

As for the HTML, it is okay, but I would suggest that naming (i.e. name="") the input fields using actual and simple words, as opposed to abbreviations, will serve you better in the long run.

<form method="post" action="/count.php" id="form">
  <label  for="number1">Enter First no:</label>
  <input type="number" name="number1" id="number1">
  <label for="number2">Enter Second no:</label>
  <input type="number" name="number2" id="number2">
  <input type="submit" value="Calculate">
</form>

The PHP, as with the Javascript, just does not work. PHP, like most programming languages, are very picky about variables names. In other words, $_POST and $_post are not the same variable! In PHP you need to use $_POST to access POST variables.

Also, you should never trust data that you have no control over, which basically means anything that comes from the outside. Your PHP code, while it probably would not do much harm (aside from showing where the file is located on the file system, if errors are enabled), should sanitize and validate the POST variables. This can be done using the filter_input function.

<?php
$number1 = filter_input(INPUT_POST, 'number1', FILTER_SANITIZE_NUMBER_INT);
$number2 = filter_input(INPUT_POST, 'number2', FILTER_SANITIZE_NUMBER_INT);
if ( ! ctype_digit($number1) || ! ctype_digit($number2)) {
  echo 'Error';
} else {
  echo ($number1 + $number2);
}

Overall, I would say that you need to be more careful about how you write your code. Small errors, such as in your code, can cause everything to collapse. Figure out how to detect errors (in jQuery you need to use a console, in PHP you need to turn on error messages, and in HTML you need to use a validator).

Comments

0

You can do like below to pass form data in ajax call.

var formData = $('#client-form').serialize();

$.ajax({

url: 'www.xyz.com/index.php?' + formData,

type: 'POST',

data:{

},

success: function(data){},

error: function(data){}, })

Comments

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.