I went through solutions provided to similar questions in Stack Overflow and other as well. (Seems like its not only me with this problem ). So I finally am posting the question with a hope to find some solution.
I am sending two numbers to PHP function via ajax call and expect to get sum from function. I think I am right not sure though, that half of the ajax is right and half not i.e. I can send values to PHP function (i think) but I can't get sum instead in success message I get "html data of the page" :D
Can you please point my mistake and viable solution.
Ajax:
$(document).ready(function(){
$('#myForm').submit(function(event){
var num1 = Number($('#num1').val());
var num2 = Number($('#num2').val());
var summ = num1+num2;
//var data = $('#myForm').serialize();
console.log(" nums are " + summ); //totally works
var myNums = "num1= " + num1 + " & num2=" + num2;
alert(myNums); //totally works
event.preventDefault();
$.ajax({
url:'arrayTest.php',
type: 'POST',
data: {num1 : num1,
num2 : num2 },
success:function(data){
console.log(" <br>success yr data is " + myNums);
var results = data;
alert(data); // i get html of the entire page containing form
return false;
},
error:function(error){
console.log(" sorry error " + error); // get this when i add header in php
}
});
});
});
html :
<form id ="myForm" method="post" action="">
number1: <input type="number" name="num1" id="num1">
<br><br>
number2: <input type="number" name="num2" id="num2">
<br><br>
<br><br>
<input type="submit" id ="submit" name="submit" value="add">
</form>
php:
if(isset($_POST['submit'])){
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$result= $num1 + $num2;
//echo "num1 is ".$num1;// **i didnt see any echo**
echo " your result ". $result; // **i didnt see any echo**
return ($result);
}
PS: html and ajax is in same page, php function in another; I see message
XHR finished loading: POST "http://localhost/phpTest/arrayTest.php"."
in console (I don't have idea what it means!)
$_POST['submit']is the culprit here. The POST data you send along with your request doesn't have a key called'submit'in it, so the PHP code never executes like you expect.