AJAX form submission and results - php

Just started using AJAX today via JQuery and I am getting nowhere. As an example I have set up a job for it to do. Submit a form and then display the results. Obviously I haven't got it right.
The HTML.
<form id="PST_DT" name="PST_DT" method="post">
<input name="product_title_1682" id="product_title_1682" type="hidden" value="PADI Open Water">
<input name="product_title_1683" id="product_title_1683" type="hidden" value="PADI Advanced Open Water">
<input type="submit" name="submit" id="submit" value="Continue" onclick="product_analysis_global(); test();"/>
</form>
<span id="results"></span>
There are actually many more fields all loaded in dynamically. I plan to use ajax to submit to PHP for some simple maths and then return the results but we can worry about that later.
The JQuery
function test() {
//Get the data from all the fields
var alpha = $('#product_title_1682').val();
JQuery.ajax({
type: 'POST',
url: 'http://www.divethegap.com/update/functions/totals.php',
data: 'text=' + alpha,
beforeSend: function () {
$('#results').html('processing');
},
error: function () {
$('#results').html('failure');
},
timeout: 3000,
});
};
and the PHP
<?php
$alpha = $_POST['alpha'];
echo 'Marvellous',$alpha;
?>
That's my attempt and nothing happens. Any ideas?
Marvellous.

First of all, you're passing the $_POST variable as 'text' while your script is looking for $_POST['alpha']. If you update your PHP to $_POST['text'], you should see the proper text.
Also, if your form is going to have lots of inputs and you want to be sure to pass all of them to your AJAX Request, I'd recommend using jQuery's serialize() method.
data: $('#PST_DT').serialize(), // this will build query string based off the <form>
// eg: product_title_1682=PADI+Open+Water&product_title_1683=PADI+Advanced+Open+Water
In your PHP script you'd then need to use $_POST['product_title_1682'] and $_POST['product_title_1683'].
UPDATE Add a success callback to your $.ajax call.
function test() {
// serialize form data
var data= $('#PST_DT').serialize();
// ajax request
$.ajax({
type : 'POST',
url : 'http://www.divethegap.com/update/functions/totals.php',
data : data,
beforeSend : function() {
$('#results').html('processing');
},
error : function() {
$('#results').html('failure');
},
// success callback
success : function (response) {
$('#results').html(response);
},
timeout : 3000,
});
};
In your PHP script you can debug the information sent using:
var_dump($_POST);

In your AJAX request, you are sending the parameter foo.php?text=..., but in the PHP file, you're calling $_POST['alpha'], which looks for foo.php?alpha=....
Change $_POST['alpha'] to $_POST['text'] and see if that works.

There is a simpler method:
$("#PST_DT").submit(function(e){
e.preventDefault();
$.ajax({
data: $(this).serialize(),
type: "POST",
url: 'http://www.divethegap.com/update/functions/totals.php',
success: function(){
....do stuff.
}
});
return false;
});
This will allow you to process the variables like normal.

Related

Ajax script writing

I have this code for example
<?php
if(isset($_POST['goose'])){
echo '<div>goose</div>';
}
?>
<form action="goose.php" method="POST">
<input type="submit" name="goose" />
</form>
How can I write something like this but in AJAX? I don't know this language.
I recommend using jQuery.
$.ajax({ // begins our async AJAX request
type: "POST", // defining as POST
url: "goose.php", // page to request data from
data: ["goose":$("input[name=goose]").val()], // define POST values
success: function(output){
alert(output);
},
error: //do something else
});
Because we have set the type to POST our data will need to be in the form of an associative array with "goose" being equivalent to $_POST["goose"].
data: ["goose":$("input[name=goose]").val()],
The success is what will happen if the data is able to be sent correctly with output being what is returned. In our case output = <div>goose</div>.
success: function(output){
alert(output);
}
error can also have a function but here you will want to tell the script what do do if say goose.php is un-reachable.
No need for extra frameworks. Just use fetch api.
<form action="goose.php" method="POST" onsubmit="submit(event, this)">
<input type="submit" name="goose" />
</form>
Javascript:
function submit(event, form) {
event.preventDefault();
fetch(form.action,{
method: 'post',
body: new FormData(form)
}).then((data) => {
console.log(data);
});
}

Trouble POSTing form with AJAX

edit - the info appears to be posting, but on form_data.php it doesn't seem to be retrieving the posted values
Here's the AJAX
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$("#submit_boxes").submit(function() { return false; });
$('input[type=submit]').click(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: $(this).serialize(),
success: function(data) {
$('#view_inputs').html(data); //view_inputs contains a PHP generated table with data that is processed from the post. Is this doable or does it have to be javascript?
});
return false;
});
};
</script>
</head>
Here is the form I'm trying to submit
<form action="#" id = "submit_boxes">
<input type= "submit" name="submit_value"/>
<input type="textbox" name="new_input">
</form>
Here is the form_data page that gets the info posted to
<?php
if($_POST['new_input']){
echo "submitted";
$value = $_POST['new_input'];
$add_to_box = new dynamic_box();
array_push($add_to_box->box_values,$value);
print_r($add_to_box->box_values);
}
?>
Your form is submitting because you have errors which prevents the code that stops the form from submiting from running. Specifically dataType: dataType and this.html(data) . Firstly dataType is undefined, if you don't know what to set the data type to then leave it out. Secondly this refers to the form element which has no html method, you probably meant $(this).html(data) although this is unlikely what you wanted, most likely its $(this).serialize() you want. So your code should look like
$('form#submit_boxes').submit(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: $(this).serialize(),
success: success
})
return false;
});
Additionally if you have to debug ajax in a form submit handler the first thing you do is prevent the form from submitting(returning false can only be done at the end) so you can see what errors occurred.
$('form#submit_boxes').submit(function(event) {
event.preventDefault();
...
});
You can use jQuery's .serialize() method to send form data
Some nice links below for you to understand that
jquery form.serialize and other parameters
http://www.tutorialspoint.com/jquery/ajax-serialize.htm
http://api.jquery.com/serialize/
One way to handle it...
Cancel the usual form submit:
$("#submit_boxes").submit(function() { return false; });
Then assign a click handler to your button:
$('input[type=submit]').click(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: this.html(data),
success: success,
dataType: dataType
})
return false;
});

Using JQuery to Update Form Fields before passing to PayPal

I have spent the day studying up on jquery because I think it will allow me to do this. I have a paypal form and I want the "onClick" button to send this field to my sql table
<input type="hidden" name="amount" id="amount" value="0.05">
Meanwhile my PayPal button is doing this:
<input class="btn btn-primary" onClick="send()" type="submit" value="Subscribe">
How can I pass this value to my process_plan.php? So far I have this but it's hanging and not working.
function send() {
var id = $('#amount').val();
var result;
$.ajax({
type: "POST",
url: "process_plan.php",
data: {
"amount" : amount
},
async: true,
dataType: "html",
success: function(response) {
result = response;
},
error: function(response) {
alert("Oh no! An error occured!");
}
});
return result;
}
I apologize if the code is really wonky - really my first day studying up on Jquery and Ajax.
Don't know if that is the problem, but I think you have a little mistake in your code.
Please try :
...
data: {
amount : "amount"
},
...
In case that amount is a var too, delete the "
Use a tools such as firebug for firefox or fiddler (http://www.fiddler2.com/fiddler2/) to look at the request and response. It will tell you how the communication is going.
That being said it's not hanging. Your send() function is posting a value asynchronously, meaning the function send() will return while the ajax call is being made. You cannot rely on the result to be set by the time the function returns. That is why you have a callback function in the call:
success: function(response) {
result = response;
},
This will run after the call is complete and generally after the originating function has completed. To see it in action change it to:
success: function(response) {
window.alert("Response: " + response);
},
You can then go onto submitting the form, in the success function, by selecting the form and manually call submit:
success: function(response){
$('#form-id').submit();
}
For more information on the quirks of ajax see this msdn: https://developer.mozilla.org/en-US/docs/AJAX
Where is the variable amount defined? I have a feeling you wanted to use id instead:
data: {
"amount" : id
},
I think there is another mistake! You set the variable 'id' to the value of the field, then you send the undefined variable 'amount' in the data of the post. This would fix it:
var amount = $('#amount').val();

HTML : Enable Multiple Submission without refreshing

I want to enhance my tool's page where as soon use click a button. Request goes to server and depending upon return type (fail/pass) i change color of button. No Refresh/page reload
Page has multiple buttons : some what like below.
Name 9-11 - 11-2 2-5
Resource1 - Button - Button - Button
Resource2 - Button - Button - Button
Resource1 - Button - Button - Button
I am a c++ programmer so you might feel i asked a simple question
Here's a sample of jQuery Ajax posting a Form. Personally, I'm unfamiliar with PHP but Ajax is the same no matter what. You just need to post to something that can return Success = true or false. This POST happens asynchronously so you don't get a page refresh unless you do something specific in the success: section.
$("document").ready(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: yourUrlHere,
dataType: "json",
cache: false,
type: 'POST',
data: $(this).serialize(),
success: function (result) {
if(result.Success) {
// do nothing
}
}
});
}
return false;
});
});
Of course you don't have to be doing a POST either, it could be a GET
type: 'GET',
And if you don't need to pass any data just leave data: section out. But if you want to specify the data you can with data: { paramName: yourValue },
The cache: false, line can be left out if you want to cache the page. Seeing as how you aren't going to show any changes you can remove that line. jQuery appends a unique value to the Url so as to keep it from caching. Specifying type: "json", or whatever your specific type is, is always a good idea but not necessary.
Try using the $.post or $.get functions in jquery
$.post("url",$("#myform").serialize());
Adding a callback function as Fabrício Matté suggested
$.post("url",$("#myform").serialize(),function(data){alert(data);$("#myform").hide()//?Do something with the returned data here});
Here you go. You will find an example of a form, a button a the necessary ajax processing php page. Try it out and let us know how it goes:
<form action="" method="post" name="my_form" id="my_form">
<input type="submit" name="my_button" id="my_button" value="Submit">
</form>
<script type="text/javascript">
$("document").ready(function () {
$('#my_form').submit(function () {
$.ajax({
url: "ajaxpage.php",
dataType: "json",
type: "POST",
data: $(this).serialize(),
success: function (result)
{
//THere was an error
if(result.error)
{
//So apply 'red' color to button
$("#my_button").addClass('red');
}
else
{
//there was no error. So apply 'green' color
$("#my_button").addClass('green');
}
}
});
return false;
});
});
</script>
<?php
//ajaxpage.php
//Do your processing here
if ( $processed )
{
$error = false;
}
else
{
$error = true;
}
print json_encode(array('error' => $error));
die();
?>

How to submit a form with AJAX/JSON?

Currently my AJAX is working like this:
index.php
<a href='one.php' class='ajax'>One</a>
<div id="workspace">workspace</div>
one.php
$arr = array ( "workspace" => "One" );
echo json_encode( $arr );
ajax.js
jQuery(document).ready(function(){
jQuery('.ajax').live('click', function(event) {
event.preventDefault();
jQuery.getJSON(this.href, function(snippets) {
for(var id in snippets) {
jQuery('#' + id).html(snippets[id]);
}
});
});
});
Above code is working perfectly. When I click link 'One' then one.php is executed and String "One" is loaded into workspace DIV.
Question:
Now I want to submit a form with AJAX. For example I have a form in index.php like this.
<form id='myForm' action='one.php' method='post'>
<input type='text' name='myText'>
<input type='submit' name='myButton' value='Submit'>
</form>
When I submit the form then one.php should print the textbox value in workspace DIV.
$arr = array ( "workspace" => $_POST['myText'] );
echo json_encode( $arr );
How to code js to submit the form with AJAX/JSON.
Thanks
Here is my complete solution:
jQuery('#myForm').live('submit',function(event) {
$.ajax({
url: 'one.php',
type: 'POST',
dataType: 'json',
data: $('#myForm').serialize(),
success: function( data ) {
for(var id in data) {
jQuery('#' + id).html(data[id]);
}
}
});
return false;
});
Submitting the form is easy:
$j('#myForm').submit();
However that will post back the entire page.
A post via an Ajax call is easy too:
$j.ajax({
type: 'POST',
url: 'one.php',
data: {
myText: $j('#myText').val(),
myButton: $j('#myButton').val()
},
success: function(response, textStatus, XMLHttpRequest) {
$j('div.ajax').html(response);
}
});
If you then want to do something with the result you have two options - you can either explicitly set the success function (which I've done above) or you can use the load helper method:
$j('div.ajax').load('one.php', data);
Unfortunately there's one messy bit that you're stuck with: populating that data object with the form variables to post.
However it should be a fairly simple loop.
Have a look at the $.ajaxSubmit function in the jQuery Form Plugin. Should be as simple as
$('#myForm').ajaxSubmit();
You may also want to bind to the form submit event so that all submissions go via AJAX, as the example on the linked page shows.
You can submit the form with jQuery's $.ajax method like this:
$.ajax({
url: 'one.php',
type: 'POST',
data: $('#myForm').serialize(),
success:function(data){
alert(data);
}
});

Categories