views:

133

answers:

2

This one is a really simple question (I hope), but as just laening/getting to grips with Jquery I apologise in advance.

If I have a form e.g.

<form id="form">
<input type="text" name="abc" />
<input type="text" name="def"/>
<input type="text" name="ghi"/>
<input type="submit" name="try" id="try" />
</form>

Anf then send it via JQuery like this

$.post("process.php", $("#form").serialize());

How do I access the data to process the information on process.php? i.e. via a simple PHP insert query (I can write the PHP!), just how do I access the serialized data. Also is there a way to send all the data (from the 3 fields) as i varaiable - I think this is JSON?, if so, how do I then reprocess that info when I call the database to display it.

I have a good grasp of most things so you don't need to be over simplistic, but just some general pointers would help. Thanks

A: 

Have you thought about simply changing the action and method properties of the form tag, then submitting?

$("#form").attr("action", "process.php").attr("method", "post").submit();

That being said, be careful if you do this. the onSubmit, if there's any, won't be run when calling submit() directly from jQuery. You'll have to find it and run it yourself.

David Morton
Any particular reason why should I do that/this?
RussellP
It's emulating the way a form is meant to be submitted anyways. Changing the action to the page you want to post to, and the method to post will automatically get all your values and post them to the page specified by the action attribute. It clears all your requirements and takes advantage of the browser's ability to perform a postback automatically. No knowledge of json necessary.
David Morton
+1  A: 

In process.php the data will already be available deserialized in the $_POST superglobal.

JSON is another form of serialization best suited to send responses from PHP back to javascript.

So in your case, for example, process.php reads $_POST, processes the result somehow and then you could format the scripts return values in an array, use json_encode() and die($json_encoded_variable_here) to return it to jquery.

In jquery you could add a callback to your function:

$.post("process.php", $("#form").serialize(), function(json){
    // the variable json is the JSON died() by php and can be easily parsed by jquery
}, 'json');
Alex