jquery $.post empty array - php

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);

Related

jQuery $.post() a form with .serialize() / Where are my params in PHP?

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.

Is there any way to stop a GET method form from sending empty variables?

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;

php - multiple validations

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.

Jquery Validate: How do I call the PHP file

I am very new to this javascipt, jquery world and I am having great difficulty getting to grips with it.
I have got the following in my HTML
$(document).ready(function(){
$("#frmEnquiry").validate();
});
</script>
It works although I do not understand, what is going on behind that statement, especially as it validates on each field entry (which is wonderful).
I have action="" in my form definition and a submit button and I have created a process.php file which further validates and sends an email, but I have no idea how I call that php file or where I put the call or what the syntax is for doing it. I am assuming it is based on a return from validate().
Also what is the correct procedure for returning from the PHP file with either success or failure messages.
If anyone can help at a simple syntax level, I would be most grateful as I have looked at so many possible solutions, my head is just totally confused.
I apologise for probably asking a very common question, but when you are just starting, it is difficult finding an example which you fully understand.
Well, there are two general approaches:
Oldschool form processing: you set <form action='process.php'> so your request is submitted to that page. Browser reloads and displays the content that you have rendered in process.php
Ajax-submit: this way you leave action blank, block submitting with something like <form onSubmit = 'return false'> and then send content using one of jQuery's AJAX-methods: get, post or ajax. It looks something like that:
$(document).ready(function(){
if($('form').validate()){
$('form').submit(function{
//Personally I prefer ajax as get and post are just shorthands for this method
$.ajax({
url:'process.php',
dataType:'json',
data:{name:nameVal, value:valueVal}
success: function(){
/*server returned some data, process it as you wish*/
}
});
});
}
});
Don't forget the principles:
PHP is executed server-side
javascript is executed client-side
Thus, PHP will only be executed if you are calling the server, meaningly, if you call an URL (http://mydomain.com/MyPHPpage.php) or if you are calling your server through an AJAX request (which is seemingly the same, except there is no reload client-side).
On the contrary, javascript is called only client-side. So the code used to validate() your form is called only on the client-side (except if you have a specific function behind this that would call the server). Hence, the javascript will use the parameters you gave him to validate the form without calling the server. This is a very good way not to overload your server with un-wanted request (empty fields, wrong e-mail addresses...).
Anyway, you can still have some other checks on your server side (checking in your database if the user exists...) and return another message to the user.
To answer your question, i'll ask some other ones: what are you trying to validate? do you want to check client-side or server-side? which data and for which purpose?
You need an AJAX call to your PHP script. If your form data is valid you would do such a call. You can asign a success callback to the ajax request where you can process the return data from PHP and either update data, display a error message or something else. From PHP you can return an object or an array where you detail if errors occured and of what type. More about AJAX -> http://api.jquery.com/jQuery.ajax/
In your case it is reasonable to perform form validation via javascript by checking the value of each field.
There is no need to send data to the server and receive information about their correctness. This method complicates the validation and is not improve protection against bad data.

what's the best way to post 30 variables from client side to server?

hey,
i have about 30 variables which are created and modified by user (none of which comes from input, so submitting a form is not really an option), once modification finished a JS function process the variables and spouse to post them to the controller which will then send the to the model.
now, as appears in the title, my question is what is the best way for me to send them?
thnx for time and attention,
Ido
I wouldn't use GET for this unless it's something like a complex search form.
You can POST values in JavaScript either by using some form of AJAX or by generating a hidden form and submitting it.
Modern browsers and newer versions of PHP both support JSON, and there are supporting libraries you can use if the browsers you need to support or the PHP version you're stuck with are old. I'd recommend this as a way of getting data back and forth.
Client side JS:
var myobject = {
userparam: "value",
anotherThing: "another value",
something: "etc"
}
var serialized = JSON.stringify(myobject);
// use any AJAX technicque to POST 'serialized' back to the server
Then on the server-side:
<?php
$myobject = json_decode( $_POST['serialized'], true );
$myobject['userparam'] == "value"; // true
Hope this helps!
I would use a POST using an ajax-submitted form. You can simply create a form with hidden inputs and then use your favorite ajax library to submit the form to the server as a POST request.
If the variables are tightly related you can shove them into an array and POST them (use Javascript to construct the array of course). Another alternative would be to name each one of them and POST them separately?
POST array look like this: arr[]=Hello&arr[]=World
in PHP you can access it like
<?php
arr = $_POST['arr'] // ["Hello", "World"]
?>
Hope that helped!
Weigh it up between POST and GET. GET is better if you want to navigate back to the a page with a given set of 'variables'. POST is better if you're submitting a lot of content. However, a POST request is less 'efficient' as a GET request - bear that in mind and only use POST if you really need to.

Categories