I am making a web form and I am validating the inputs via ajax. For every keypress on an input tag, the value is sent to a php file where its checked for numeric value etc. This was easy, I just have it echo back a error message response which is displayed.
On this same keypress, I also want it to check if ALL the input values are != "" so that the person can't leave an entry blank. I am trying to have it control whether or not the submit button works. This is where I get stuck.
Is there a way to send two things back in an ajax request? I tried using the php session object but it wouldn't work the way I wanted (since ajax isn't updating the entire page.)
Yes you can. Two options:
1 - quick and dirty - you could send a string back with the two items you need. You would need to concatenate the two items you need to send back into one string. Your onSuccess function would then split the string into the two items you want.
2 - elegant solution - you can create a JSON object in the server and send it back. A JSON string is something like foo = { "var1" : "response1" , "var2" : "response2" }. In your client-side script you would reference var1.response1 and var2.response2. See below one example using Mootools (a well-known javascript library) and PHP:
javascript code (client):
var params = "id=123&page=1&product=12"; //anything you need to pass to the server
var myRequest = new request.JSON({url:"url of your server script", onSuccess: function(result) {alert(result.response1); alert(result.response2);}).post(params);
PHP code (server):
$a["response1"] = response1; //first thing you need to pass back
$a["response2"] = response2; //second thing you need to pass back
echo json_encode($a); // this will convert $a array to a json string
I hope this helps. Good luck!
You should use json for this one.
$errors = array('Error1', 'Error2');
echo json_encode($errors);
You could attach an onsubmit handler to the form that returns a boolean for success/failure.
<script>
function myValidation(){
/*
Your AJAX validation call here.
*/
if(valid){
return true;
}else{
return false;
}
}
</script>
<form onsubmit="return myValidation();">
<input type="submit" name="submit" value="Submit" />
</form>
If the validation returns false, the form will not submit. A return of true allows the form to process as necessary.
Why aren't you doing this with straight jQuery? It seems ridiculous to make an ajax call to validate a form through PHP while the user is filling it out. Validate the data after submission with PHP, not during.
That is unless you need to match the input to something in the database, but it doesn't sound like that's the case here.
Related
I've got a html form and trying to send it with jQuery to a php script. In this script i am looking for the params.
$(document).ready(function(){
$("#myselect").change(function(e){
e.preventDefault();
$.post("mypath/toscript/",$("#form").serialize(), function(data){
alert(data);
});
});
});
I need all uri parts. So im fetching it with $_SERVER['REQUEST_URI'].
I am requesting something like this:
mypath/toscript/?p1=A&p2=B&p3=C
When i type this URI in the browser it works like it should.
But with the jQuery above i am getting with $_SERVER['REQUEST_URI'] only mypath/toscript/ without params.
Using $_POST shows me the prams p1=A&p2=B&p3=C
So why? Where is the difference when doing a post with $.post() to typing it directly
POST doesn't use the request URL to send the query string like GET does. POST instead sends the query string in the HTTP message body. When you type the query string into the browser, you are using method GET.
Here is an article from W3Schools about it.
That doesn't mean you should switch to using $.get necessarily though. There are drawbacks to using GET over POST, such as having a length limit or being less secure. Read the article to learn more.
To fix your code, you will have to choose which HTTP method suites your needs, and then align the jQuery and PHP code so that they both use the same method.
In your case try this will solve your problem ..
$.get("mypath/toscript/",$("#form").serialize(), function(data){
GET - Requests data from a specified resource..
POST - Submits data to be processed to a specified resource..
from w3school
You should use GET where you're doing a request which has no side effects, e.g. just fetching some info. This request can:
Be repeated without any problem - if the browser detects an error it
can silently retry Have its result cached by the browser Be cached by
a proxy
You have to provide serialize in formatted array way something like this
var data = $('#form').serializeArray();
$.post("mypath/toscript/",data , function(data){
alert(data);
});
Use parse_str to parse your serialized POST data into an array.
// $_POST['form'] : "num=12&obj=3&obs=text"
$form = array();
parse_str($_POST['form'], $form);
// you get :
$int_num = (int) $form['num']; // 12
$int_obj = (int) $form['obj']; // 3
$str_obs = $form['obs']; // "text"
A serialized form data is commonly used to update a database, so it's recommended to use POST vars.
I'm using the following form as part of an Advanced Search page on my WordPress install.
<form action="/advanced-search/" method="get">
The form is working correctly, but producing URLs like:
/advanced-search/page/3/?act=s&f=cichlidae&g&s&c&r&tmin&tmax&hmin&hmax&pHmin&pHmax&cmin&cmax&sF&sM&aL&aD&aH
Is there any way to stop the form from sending those empty variables? In the above example only f was searched for (value cichlidae). As such I'd prefer it to produce a URL like this:
/advanced-search/?act=s&f=cichlidae (plus the /page/3/ if necessary).
I can't use $_POST because I can't get the WordPress paged variable to work with $_POST values.
Thanks in advance,
Why don't you use jQuery's serialize method to collect all the form values in a string?
$('form').submit(function() {
var string = $(this).serialize();
window.location.href = '/advanced-search/'+string;
});
It loops through all of your form elements, collects their values and converts it into a readable string format for use in URLs.
Not built-in to a form, no - if the field exists, it'll be sent.
You could use Javascript to submit the form instead, and thus omit empty fields.
No, there is no way (without JavaScript that is). If there was, this would be browser-specific, since it's the browser that decides what to do with the form data.
Also, this:
foo.php?a=
...and this:
foo.php
...is semantically different. In the former, a is passed with an empty string ("") while the in latter, a is not passed at all (null).
Also, Wordpress is correct here, since the form is a search form, thus it is retrieving data and should use GET; and not creating data as POST should do.
A way to change this (without JavaScript) is to use a gateway script that removes empty parameters from the URL and redirect.
Per example:
$newGET = array();
foreach ($_GET as $key => $value) {
if ($value !== '') $newGET[$key] = $value;
}
header('Location: some/url?'.http_build_query($newGET));
exit;
Im not sure if this is possible, but at the moment I have a form on my page where users can insert their interests, beneath that form are 3 PHP variables (Which dont currently show at first as there is no value assigned to them).
When a user enters an interest and clicks submit, my AJAX takes over, populates the table and then reloads the page so the Variable now shows as it has a value.
Is it possible to not have to refresh the page, so I can say "if success $var = 'value';"?
I hope this doesnt sound too confusing, thanks
Since you're already using AJAX, why don't you just do the logic using Javascript? If you're using jQuery, have a success callback function execute the code you want.
The problem with sending data from AJAX to PHP is that PHP is a server side language, while AJAX is a client side one. By the time your browser sees the page, the PHP has been entirely executed and returned to you as HTML / CSS / Javascript etc.
No, you can't. By the time the HTML has rendered/displayed in the browser, PHP will most likely have long since finished generating the HTML in the first place. You could round-trip the values through an AJAX handler and then populate the places in your page where the values are displayed, but when why bother round-tripping? Just have the AJAX call fill in the values right then and there.
It is absolutely possible, and quite easy to do. Just make another php script and call it from your form page's javascript (I'm going to assume you're using jQuery):
$('#mysubmit').click(function() {
$.getJSON(
'form_ajax.php', // This is the php file that will be called
{ formVar1: $('#form-var-1').val() }, // Add all your form data here
function(data) {
// This is the function that is called after the php script is
// done executing. The 'data' variable will contain the $data
// array you see in the following php file.
}
);
});
I prefer to use JSON, but other approaches are just as good. Check out the documentation for getJSON() and ajax(). Your php file would look something like this:
<?php
$data = array();
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$data['formVar1'] = $_POST['formVar1'];
}
echo json_encode($data);
?>
Of course, yours would probably do a lot more with the form data. Also, theres plenty of other approaches so go explore for the one the best suits your needs.
I currently have a large form that gets sent to our payment authorizer (done so by action="paymentautherizerURL" ), however I am not getting all of the information I require back from them when I go to store the transaction in my DB.
I either need to intercept the form data before it submits so that I can store it in the session (we are using PHP / jQuery), or I have also tried sending it to an intermediary scriptlet that grabs the information I need, and then using jQuery's $.post() to re-build and send off the data to the authorizer.
the second approach does not seem to work, however, at least to the best of my efforts. I'm not sure that a $.post properly emulates the form's send action, or at least I have not done it right.
<?php
session_start();
$post = $_POST;
//gets all of the information that beanstream does not return to approved.php, but is still required to make
//a legitimate database entry. gets from the POST and stores in the session array for approved.PHP to access
$_SESSION['approvedArray']['billAddress'] = $_POST['ordAddress1'];
$_SESSION['approvedArray']['billProvince'] = $_POST['ordProvince'];
$_SESSION['approvedArray']['billCountry'] = $_POST['ordCountry'];
$_SESSION['approvedArray']['billPostalCode'] = $_POST['ordPostalCode'];
$_SESSION['approvedArray']['billCity'] = $_POST['ordCity'];
$_SESSION['approvedArray']['shipAddress'] = $_POST['shipAddress1'];
$_SESSION['approvedArray']['shipPostal'] = $_POST['shipPostalCode'];
$_SESSION['approvedArray']['shipCity'] = $_POST['shipCity'];
$_SESSION['approvedArray']['shipProvince'] = $_POST['shipProvince'];
$_SESSION['approvedArray']['shipCountry'] = $_POST['shipCountry'];
session_write_close();
//the javascript below will send what is required to beanstream as though it were sent from the form
<script type='text/javascript'>
$.post(, {
<?php
//rebuild the POST such that "name: value, " except the last name/value will not be followed by a comma
$keys = array_keys($_POST);
for($i = 0; $i < count($_POST); $i++) {
$currentKey = $keys[$i];
$currentPost = $_POST[i];
echo $currentKey . ": " . $currentPost;
if ($i < (count($_POST) - 1)) {
echo ", ";
}
}
?>
});
</script>
?>
normally, the transaction authorizer will re-direct the user to one of 3 pages (approved, declined, error), and our website does the job from there. however, it's currently stuck at this page, which makes me think it's not sending off properly.
i'm open to all forms of criticism, approaches and ideas. thanks very much in advance, and if any other information is needed, please let me know!
How about changing the form tag to include an onSubmit attribute:
<form action="notmal_action.whatever" onSubmit="return save_data_function()">
Where the save_data_function reads the values from the form and sends it to a script on your server to save in a database (or where ever). I use hidden iframes to make this request hidden from the user...
<script>
function save_data_function() {
$('#iframe_id').attr('src', 'data_saving_script.extension?data_1=' + $('form_data_1').val().serialize() + '&data_2=' + $('form_data_2').val().serialize());
}
</script>
You can set a timeout if the data isn't being passed quick enough to the "data_saving_script.extension" file.
Since your existing example already has a dependency on javascript, you could move to saving the data with AJAX and then using a traditional submit to do the "real" POST to the payment gateway.
Assuming that your form has id="foo", you could do something like this:
<script>
$('form#foo').submit(function(event, doRealSubmit) {
// this executes on the second pass
if (doRealSubmit) {
// returning true gets browser to do a real submit
return true;
}
// this executes on the first pass
$.ajax({
url: '/url/to/post/to/your/server',
type: 'POST',
// this serializes the form data in "application/x-www-form-urlencoded"
data: $(this).serialize(),
success: function(data) {
// trigger 'submit' event again, but pass the doRealSubmit flag
$('form#foo').trigger('submit', [true]);
}
});
// returning false prevents browser from processing the real submit
return false;
});
</script>
instead of action="paymentautherizerURL" you should send it to your own page:
<form action='process.php' method='post'>
now in your process.php you can work with the data (validation, filtering ..)
and when you are done you can send the data to the right place using cURL
With curl you can send post data and wait for the response to decide which page to show.
No need to put the data in sessions, on submit of form called a validate function in which done all the validation and then post the data to ur process.php using ajex , then it will retain on that page...
Don't store the data in the session - it's the wrong place to keep transactional data.
Post the stuff to a script you host, write only the stuff you need to keep to your database, generate an order reference for it,
then....
if you are using a payment processor (e.g. Paypal)
redirect to a second script passing the order reference in the URL. On the second script put in a form with hidden fields cotaining only the details required by your payment processor and some javascript to submiot the form automatically and a message to the user like 'Connecting to Paypal...'
If you are using merchant services to authorize the payment
before you generate output from the landing script, send the details to your authorizer using (e.g.) curl and parse the response, record the response against the order in the database and output a suitable message to the customer via the web page
I'm using jQuery to post a form to a php file, simple script to verify user details.
var emailval = $("#email").val();
var invoiceIdval = $("#invoiceId").val();
$.post("includes/verify.php",
{invoiceId:invoiceIdval , email:emailval },
function(data) {
//stuff here.
});
PHP Code:
<?php
print_r($_POST);
?>
I look at the response in firebug, it is an empty array. The array should have at least some value.
I can not work out why the $_POST isn't working in the php file. Firebug shows the post to contain the contents posted, email and invoice id, just nothing is actually received in the php file.
The form:
<form method="post" action="<?=$_SERVER['PHP_SELF']; ?>" enctype="application/x-www-form-urlencoded">
Anyone know what its doing?
thanks
found this - http://www.bradino.com/php/empty-post-array/
that a sensible route to go?
$.post() passes data to the underlying $.ajax() call, which sets application/x-www-form-urlencoded by default, so i don't think it's that.
can you try this:
var post = $('#myForm').serialize();
$.post("includes/verify.php", post, function(data) {
alert(data);
});
the serialize() call will grab all the current data in form.myForm.
I got bitten by the same issue, and I find the solution Owen gives not appropriate. You're serializing the object yourself, while jQuery should do that for you. You might as well do a $.get() in that case.
I found out that in my case it was actually a server redirect from /mydir to /mydir/ (with slash) that invalidated the POST array. The request got sent to an index.php within /mydir
This was on a local machine, so I couldn't check the HTTP traffic. I would have found out earlier if I would have done that.
application/x-www-form-urlencoded
There's your answer. It's getting posted, you're just looking for the variables in $_POST array. What you really want is $_REQUEST. Contrary to the name, $_POST contains input variables submitted in the body of the request, regardless of submission method. $_GET contains variables parsed from the query string of the URL. If you just want submitted variables, use the $_REQUEST global.
If you expect to be receiving file uploads, than you want to create a new array including the contents of $_FILES as well:
$arguments = $_REQUEST + $_FILES;
I tried the given function from Owen but got a blank alert as well. Strange but i noticed it would output a query string and return a blank alert. Then i'd submit again and it would alert with correct post values.
Also had the field names set in the html using the id attribute (which was how it was done in a jquery tutorial I was following). This didn't allow my form fields to serialize. When I switched the id's to name, it solved my problem.
I ended up going with $.ajax after all that since it did what I was looking for.
I had a case where I was using jQuery to disable all the inputs (even the hidden ones I wanted) just before using jQuery to submit the form. I changed my jQuery to only disable the "button" type inputs and now the hidden vars are posted when the form is submitted! It seems that if you set a hidden input to disabled its values aren't posted with the form!
Changed:
$('input').attr('disabled',true);
to:
$('input[type=button]').attr('disabled',true);