jQuery process form

2019-05-26 07:52发布

This one is a really simple question (I hope), but as just leaning/getting to grips with jQuery I apologize 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>

And 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 variable - 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

2条回答
孤傲高冷的网名
2楼-- · 2019-05-26 08:10

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');
查看更多
我只想做你的唯一
3楼-- · 2019-05-26 08:10

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.

查看更多
登录 后发表回答