开发者

How do I post information to a server when a link is clicked?

Alright so I want my users to be able to click a link that will allow them to add a movie to their favourite.

So in example I have http://xxx.com/favorite.php?userid=1&movieid=1020

For the moment al开发者_JS百科l works well, it adds the values into database, but since it's movies, I do not wish the page to reload, hence the use of Ajax which I am new to.

I worked a little bit around with the different ways of doing it, but never succeeded.

I got alot of help earlier on with my PHP issue, and that would be awesome if it could be the same now!

Basicly just click the favorite image (which is a link) and when the action of posting to database is done, well show another image.

Well I tried many ways, including the JSON ones, but I know GET method can be vulnerable, but it uses session + more security so I'm pretty sure it safe for the moment, I can always work on that later.

Although I'd like to know a nice way with a good example, because I still didn't figured it out.

Thanks to answers tho! Appreciated.

Edit:

Or if not, what would be the best way to POST the info it that's easier? Best way I found is get, since I'm not that advanced in AJAX / etc

Also in my favorite.php file, the information are being submitted to the server, that is the whole point.


You need to get JQuery and install it in your web app (see their getting started docs). In your HTML you'll have:

<div id="fav_12_345"><a href="javascript:void(null)" id="addfav">Favorite</a>

And in your javascript:

$("a#addfav").onclick(function(ev) {
    data_id = $(ev).parent.id();
    $.post('someurl', { data_id: data_id }, function(res) {
        // this bit gets run once the call has been processed on the server
        if (res) {
            // update the new image
            $("img#blah").attr("src", 'someurl');
        }
       }, 'json');
 });

And in your PHP

$data_id = your_sanitise_user_input($_REQUEST['data_id']);
$data = explode('_', $data_id);
$sql = "UPDATE table set fav_id=$data[1] where id=$data[0]";
$res = your_sql_lib_thing($sql);
print "{res: '$res'}";

All this code is approximate and syntactically flawed probably but gives you the general idea.


If you're wanting to get data you can use jQuery's .getJSON method http://api.jquery.com/jQuery.getJSON/, or if you're wanting to post data you can use its .post() method http://api.jquery.com/jQuery.post/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜