tags:

views:

64

answers:

5

Hey,

I just can't work it out. I need to send a POST request to PHP backend. It should be the following:

Array ( [username] => 'username' [password] => 'password' [action] => 'login' ) 

I have a form as a frontend and i use .serialize() to get the user and password. But how can i add the action key/value?

For now i just add the string manually like "&action=login" but i don't like this solution. An other problem is that i can't use any jQuery plugins, only jQuery itself.

A: 
$login = //your code;
$yourarray =//your code here 
if (array_key_exists($login, $yourarray))
// your code here
streetparade
A: 

You want to POST data from jQuery? Try:

$.post("your/controller/url.php", {username:'myname', password:'mypassword',action:'login'}, function(data){
   //do something when answer from your php backend arrives
},'json');

In your php backend you can access it as usuall $_POST, reply should be in JSON (not mandatory, but I'll recomend it)

habicht
+1  A: 
var usr = $("[name='username']").val();
var pwd = $("[name='password']").val();
var act = $("[name='action']").val();

$.post("script.php", {username:usr, password:pwd, action:act}, function(rst){
  alert(rst); // alerts 'Thank you [username], your data has been received.'
}, "html");

And your code for script.php should be similar to:

if ($_POST) {
  echo "Thank you " . $_POST["username"] .", your data has been received.";
} else {
  echo "Nothing found.";
}
Jonathan Sampson
A: 

I encounter same problem in AJAX Based applications. There is no elegant way to do this. I am using this way:

<form id="foo">
     <input type="hidden" id="action" name="action" value="login" />
     <input type="text" id="username" ....
...
</form>

With this way you don't have to add strings manually.

jsonx
A: 

Are you trying to add more data to the data object you are sending? You can try something like this:

var data = form.serializeArray();
data.push({'action':'login'});

$.post("/url", data, function(){ callback goes here}, 'json');
honeybuzzer