PHP not echoing back data from form submit - php

My page has an html form to collect email, first name, last name and a checkbox. The form begins with this header:
<form action="echo_test.php" method="post" name='register' id='register'>
I submit the form with this button:
<div class="EMail_Pwd_JoinPage"><button class="btn_joinnow" style="color:rgb(255,255,255);" id="btn_submit" onclick="GetDate(); GetCkBx();">Submit data</button></div>
That calls this jquery function:
<script type="text/javascript">
$("#btn_submit").on("click", function (event) {
event.preventDefault();
form_data = $('form').serialize()
console.log("Okay, I'm starting");
console.log(form_data);
console.log("More Info");
GetDate();
return $.ajax({
type: "POST",
url: "echo_test.php",
data: form_data,
success: function (responseText) {
console.log("Server Reply " + responseText);
},
error: function (error) {
console.log("Okay, I failed" + error);
}
});
});
</script>
It submits to echo_test.php on my server:
<?php
echo 'Hello ' . htmlspecialchars($_POST["firstname"]) . '!';
?>
In the onclick event submit code above it should reply from the server:
success: function (responseText) {
console.log("Server Reply " + responseText);
},
But the Chrome dev console does not show any reply. The other console.log messages above do appear correctly (including the serialized form data).
I asked a similar question back in May, but the situation is different here.
Why doesn't this code echo back from the server?

Idk what does onclick attribute mean,
onclick="GetDate(); GetCkBx();"
So i think just remove onclick attribute. And here new code,
<div class="EMail_Pwd_JoinPage"><button type="submit" class="btn_joinnow" style="color:rgb(255,255,255);" id="btn_submit">Submit data</button></div>
Also update your button action jQuery code,
$("#btn_submit").on("submit",

As per my comment, remove onclick="GetDate(); GetCkBx();" from the button tag and call those two functions in the click event handler you created.
New Button Tag:
<button class="btn_joinnow" style="color:rgb(255,255,255);" id="btn_submit">Submit data</button>

in echo_test.php return the echo statement or use die().
<?php
echo 'Hello ' . htmlspecialchars($_POST["firstname"]) . '!';
return;
?>

Related

How to send jquery post request using button

I am trying to send post request using jquery. This is the request i am trying to send
$.post("https://api.steampowered.com/IEconService/DeclineTradeOffer/v1/", {
key: "1234567891011121314151617181920",
tradeofferid: "$offerid"
}).done(function(data) {
alert("Data Loaded: " + data);
});
Inside my php i have $offerid , and key is always the same .
I want to send it on button click so i created button inside my php
$offerid = $value2['tradeofferid'];
echo '<button id="cancel-offer"> Cancel offer </button>';
how i can connect button with jquery request and send $offerid to the request ?
You just need to select the button by its id attribute, then add a click handler:
$('#cancel-offer').click(function() {
$.post("https://api.steampowered.com/IEconService/DeclineTradeOffer/v1/", {
key: "1234567891011121314151617181920",
tradeofferid: "<?= $offerid ?>"
}).done(function(data) {
alert("Data Loaded: " + data);
});
});
I would suggest you have a quick read through the jQuery documentation. It makes a great reference, and also gives you an idea of what jQuery is and is not capable of.
Modify your code like this:
php:
echo '<button id="cancel-offer" data-id="'.$offerid.'"> Cancel offer </button>';
js:
$('#cancel-offer').click(function(){
$.post( "https://api.steampowered.com/IEconService/DeclineTradeOffer/v1/", { key: "1234567891011121314151617181920", tradeofferid: $(this).attr('data-id') },function( data ) {
alert( "Data Loaded: " + data );
});
});

Ajax call and returning result

I don't know what i did wrong in the ajax call. I want to return the data back to my script and work with it but its not returning result. Here are some things i will like to clarify as well as i am new to ajax programming. if the ajax call is successful and it returns result to the script. Where in the script will the result be. Will i have to create an array that holds the result or ...
Here is the html
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" id="reserveform">
<div id="response"></div>
<div>
<label>Name</label><input type="text" name="name" id="nameid">
</div>
<div>
<label>Phone Number</label><input type="text" name="phone" id="phoneid">
</div>
<div>
<button type="submit" class="btn" id="btnsubmit">Submit</button>
</div>
</form>
<div id="success"></div>
//my script
$('#btnsubmit').click(function(e){
e.preventDefault();
var nameid = $('#nameid').val();
var phoneid = $('#phoneid').val();
var validate_msg = '';
if (nameid == ''){
validate_msg = '<p> Name is Required. </p>';
}
if (phoneid == '' || ($.isNumeric(phoneid) == false)){
validate_msg += '<p> Phone field is either empty or non numeric. </p>';
}
if (validate_msg != ''){
$('#response').addClass('error').html('<strong>Please correct the errors below </strong>' + validate_msg);
} else {
var formData = $('form #reserveForm').serialize();
submitForm(formData);
}
});
function submitForm(formData){
$.ajax({
type: 'POST',
url: 'reservation.php',
data:formData,
dataType:'json',
success: function(data){
$("#success").html(data);
},
error: function(XMLHttpResponse, textStatus, errorThrown){
$('#success').removeClass().addClass('error').html('<p>There was an ' + errorThrown + ' due to ' + textStatus + 'condition');
}
});
}
If you are trying ajax form submission and need to populate the result in the success div without refresh, you need return false
Don't use
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" id="reserveform">
Here don't need the action in form, try like
<form id="reserveform" onsubmit="return submitForm();">
In function use form serialize so all input elements value in form will available
function submitForm(){
var formData = $("#reserveform").serialize();
$.ajax({
type: 'POST',
url: 'reservation.php',
data:formData,
dataType:'json',
success: function(data){
$("#success").html(data);
},
error: function(XMLHttpResponse, textStatus, errorThrown){
$('#success').removeClass().addClass('error').html('<p>There was an ' + errorThrown + ' due to ' + textStatus + 'condition');
}
});
return false; // use this otherwise the form will be submitted and results an entire page refresh
}
please try this
you have to put the btnsubmit click event inside onload or document ready
$(document).ready(function()
{
$('#btnsubmit').click(function(e){
e.preventDefault();
var nameid = $('#nameid').val();
var phoneid = $('#phoneid').val();
var validate_msg = '';
if (nameid == ''){
validate_msg = '<p> Name is Required. </p>';
}
if (phoneid == '' || ($.isNumeric(phoneid) == false)){
validate_msg += '<p> Phone field is either empty or non numeric. </p>';
}
if (validate_msg != ''){
$('#response').addClass('error').html('<strong>Please correct the errors below </strong>' + validate_msg);
} else {
var formData = $('form #reserveForm').serialize();
submitForm(formData);
}
});
}
);
You cant use like this $("#success").html(data); because data is in json format. here, the data is an object. You need to parse it and assign to tags.
I see you configured the form to submit to the same document that you are in already. This is fine, we do this all the time.
However, you are also stopping the form from submitting and then using AJAX to submit the values. You specify reservation.php as your ajax processor. Is this the same PHP page you are on already? If so, then I know what the problem is: you can't do that.
By design, AJAX must use an external PHP file to process the AJAX. If you try to do this inside the same document, the AJAX will only echo back the full HTML of the document itself.
Short answer: use an external PHP file. This is by design.
See this other answer for more information about exactly this issue.
See these other posts for further info about AJAX and getting info into the PHP processing script, and returning info back from the PHP processing script:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1

ajax call only works first time

I have a method in my controller that lets users check something called "POE Status".
This returns a string that i display in a div tag on my view. I also provide 2 buttons. one to enable POE and the other to disable. Both the enable and disable commands will return the POE status as a result.
So I'm trying to use ajax to update the page with the new status once either one of the two buttons are clicked.
What I'm noticing is that both buttons will work the first time the page is loaded. But after the initial ajax call is made and the view updated, if i try to use the buttons again, nothing happens.
I have the following HTML: (i'm not including all the html, just the parts that I think matter....)
<div class="span6" id="clientajaxcontainer">
<h2>Port POE Status: Port <?php echo $portname;?></h2>
<p><p>
<?php echo $poeStatus;?>
<button class="btn" id="enable">Enable POE</button>
<button class="btn" id="disable">Disable POE</button>
</div>
Then I have the following javascript:
<script>
//Enable POE button
$('#enable').click(function() {
alert('in POEOn');
console.log('On');
//disbled button until ajax request is done.
$(this).attr("disabled","disabled");
$('#disable').attr("disabled","disabled");
var htmlstring;
$.ajax({
url:"<?php echo site_url('controller/poeOn);?>",
type:'POST',
dataType:'text',
success: function(returnDataFromController) {
htmlstring = "<h2>Port POE Status: Port " + $('#port').val() + "</h2><p><p>" + returnDataFromController + "<button class='btn' name='enable' id='enable'>Enable POE</button> <button class='btn' name='disable' id='disable'>Disable POE</button>";
alert(htmlstring);
$('#clientajaxcontainer').html(htmlstring);
console.log(htmlstring);
}
});
//re-enable the buttons.
$(this).removeAttr("disabled");
$('#disable').removeAttr("disabled");
});
//Disable POE button
$('#disable').click(function() {
alert('in POEoff');
console.log('Off');
//disbled button until ajax request is done.
$(this).attr("disabled","disabled");
$('#enable').attr("disabled","disabled");
$.ajax({
url:"<?php echo site_url('controller/poeOff);?>",
type:'POST',
dataType:'text',
success: function(returnDataFromController) {
htmlstring = "<h2>Port POE Status: Port " + $('#port').val() + "</h2><p><p>" + returnDataFromController + "<button class='btn' name='enable' id='enable'>Enable POE</button> <button class='btn' name='disable' id='disable'>Disable POE</button>";
alert(htmlstring);
$('#clientajaxcontainer').html(htmlstring);
console.log(htmlstring);
}
});
//re-enable the buttons.
$(this).removeAttr("disabled");
$('#enable').removeAttr("disabled");
});
</script>
Can you tell me where I'm going wrong?
Thanks.
The problem is that you are not creating a "live" binding for your buttons and once you call $('#clientajaxcontainer').html(htmlstring); you replace the buttons with new elements which do not have a click binding. Try this instead:
$('#enable').live('click', function() {
//...
}
$('#disable').live('click', function() {
//...
}
If you're using jQuery 1.8 you can use the on() method instead of live(). That would look like this:
$(document).on('click', '#enable', function() {
//...
}
$(document).on('click', '#disable', function() {
//...
}
Here's the relevant documentation:
http://api.jquery.com/live/
http://api.jquery.com/on/

How to remember form values across different pages?

I need to send form values from one page to another and from that page to a third page. I would need the form values from the first page in the third page. How can I do it?
I have the code that transfers form values to the next page. How can I send the same form values to the third page?
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script type="text/javascript">
// we will add our javascript code here
$(document).ready(function(){
$("#ajax-contact-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "contact.php",
data: str,
success: function(msg){
$("#note").ajaxComplete(function(event, request, settings){
if(msg == 'OK') // Message Sent? Show the 'Thank You' message and hide the form
{
result = '<div class="notification_ok">Your message has been sent. Thank you!</div>';
window.location.href = "http://www.google.com";
$("#fields").hide();
}
else
{
result = msg;
}
$(this).html(result);
});
}
});
return false;
});
});
</script>
you can use GET
window.location.href = "http://yourdoamin?value= serialize text variable";
Get URL parameters & values with jQuery
Assuming you're using only simple values (not passing arrays), you can do something like this:
echo "<form id='second_page' method='post' action='third_page.php'>";
foreach ($x in $_POST) {
echo '<input type="hidden" name="' . htmlspecialchars($x) . '" value="' . htmlspecialchars($_POST[$x]) . '" />';
}
Use sessions - here is a Tutorial
You can set the values from Form #1 as input tags with hidden type in Form #2. That way, when you submit Form #2, values will be available in Form #3.

is the browser or server ignoring the code?

i made this form:
<form id="form" name="msgform" method="" action="">
<input type="text" size="40" id="msg" name="message"/>
<input type="submit" id="button" name="clicker" value="click" />
</form>
and this jquery script:
$(document).ready(function(){
$("#button").click(function(){
$("#form).submit(function(){
var submision= $("#form).val();
$.post("txt/process.php", submision, function(data){
alert(data);
});
});
});
});
and this is the process.php file:
<?php
echo $_POST['message'] . "";
?>
now when i click the button the form is submited, but it sends it using the GET method because i can see it in the adress bar, but it never gets sent to the php file, and i checked to see if the names are correct and if i specify the POST method it still doesnt go to the php file.
is the server or browser ignoring the code? or am i doing the whole thing wrong?
thanks
Please find the following code, it works and please go through with the documentation, it will tell you that what the mistake was being done.
$(document).ready(function(){
$("#button").click(function(){
$("#form").submit(function(){
/* var submision= $("#form).val();
THIS DOESN'T WORK TO GET ALL OF THE ELEMENTS IN
FORMAT TO PASS TO $.post EVENT,
We can do this as I did in following example
*/
$.post("txt/process.php", { msg: $("#msg").val() }, function(data){
alert(data);
});
/* Also you didn't put return false statement just at the end
of submit event which stops propagating this event further.
so it doesn't get submitted as usually it can be without ajax,
So this stops sending the form elements in url. This was because
by default if you define nothing in method property for form
then it consider it as GET method.
*/
return false;
});
});
});
Let me know please you are facing any issue.
You don't need to register the submit event for the form inside the click handler of the button. As it is a submit button it will automatically try to submit the form for which you register the corresponding handler:
$(function() {
$('#form').submit(function() {
// Get all the values from the inputs
var formValues = $(this).serialize();
$.post('txt/process.php', formValues, function(data) {
alert(data);
});
// Cancel the default submit
return false;
});
});
$("#form).submit(function(){
see if this selector is missing a "
$("#form").submit(function(){

Categories