Reputation: 87
I've been reluctant to open a question, but after fighting this for 6+ hours I'm now cross-eyed. I've got some experience with PHP and HTML but Ajax and jQuery is new to me (I first heard about it yesterday).
I want the page to display the submitted values inside the div class="result" without refreshing. Anyway, the workflow:
j.php loads > user fills out two text fields (phone and gz) > click Submit button > jpost.php is called and echos variables > PHP variables need to display is div class=result on j.php
j.php =
<html>
<head>
<script src="//code.jquery.com/jquery-latest.js"></script> <!-- load jquery via CDN -->
<script>
$(document).ready(function() {//start document ready
$('#submit-button').click(function (){
$.ajax({
type: 'POST',
url: 'jpost.php',
data: $("#cdr").serialize(),
success: function(d){
$(".result").html(d);
}
});
});
});//end document ready
</script>
</head>
<body>
<div id="cdr">
<div>
<input type="text" id="phone" name="phone" value="" placeholder="phone" size="40" />
</div>
<div>
<input type="text" id="gz" name="gz" value="" placeholder="gz" size="40" />
</div>
<div>
<button id="submit-button">Submit</button>
</div>
</div>
<div class="result"></div>
</body>
</html>
jpost.php
<?php
$phone = $_POST['phone'];
$gz = $_POST['gz'];
echo $phone;
echo $gz;
print_r($_POST);
echo "grrrr"
?>
So all I want is $gz and $phone to echo out in my result div on j.php, but all that shows up is:
Array ( ) grrrr
This makes me believe that my variables are being lost somewhere :P or I'm echoing them incorrectly.
Thanks so much for any help!
Upvotes: 0
Views: 3933
Reputation: 1534
Short
The problem was :
1.You need a form in order to serialise the data ( and not a div ) 2. You need to prevent the default behaviour of the event
Long
In order to serialise the data, you need to have a form. i created the form with id #cdr-form
Also, you need to make sure to prevent the default behaviour of the button ( event ) with e.preventDefault()
. Read more about it here
<html>
<head>
<script src="//code.jquery.com/jquery-latest.js"></script> <!-- load jquery via CDN -->
<script>
$(document).ready(function() {//start document ready
$('#submit-button').click(function (e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'http://localhost/~metaly/tests/j.php',
data: $("#cdr-form").serialize(),
success: function(d){
$(".result").html(d);
}
});
});
});//end document ready
</script>
</head>
<body>
<div id="cdr">
<form id="cdr-form">
<div>
<input type="text" id="phone" name="phone" value="" placeholder="phone" size="40" />
</div>
<div>
<input type="text" id="gz" name="gz" value="" placeholder="gz" size="40" />
</div>
<div>
<button id="submit-button">Submit</button>
</div>
</form>
</div>
<div class="result"></div>
</body>
</html>
Upvotes: 2