Monday, 15 September 2014

jquery - ajax php GET/POST without refresh -



jquery - ajax php GET/POST without refresh -

i need execute next code, without refreshing page... code includes ajax going wrong getting execute without refreshing page....? .vote class attatched anchor in index.php file, , need still work when anchor clicked if possible. re-coding perform on button click not ideal.

$(".vote").click(function() { var id = $(this).attr("id"); var name = $(this).attr("name"); var edata = $(this).attr("data-options"); var datastring = 'id='+ id + '&' + edata ; var parent = $(this); if(name=='up') { $(this).fadein(200).html(''); $.ajax({ type: "post", url: "up.php", data: datastring, cache: false, success: function(html){ parent.html(html); } }); } else { $(this).fadein(200).html(''); $.ajax({ type: "post", url: "down.php", data: datastring, cache: false, success: function(html){ parent.html(html); } }); } });

here html index.php

<div id="main"> <div id="left"> <span class='up'><a href="" class="vote" name="up" data-options="key1=<?php echo $mes_id1;?>&key2=<?php echo $mes_id2;?>"><img src="up.png" alt="down" /></a></span><br /> <?php echo $totalvotes1; ?><br /> </div> <div id="message"> <?php echo $message1; ?> </div> <div class="clearfix"></div> </div> <div id="main"> <div id="right"> <br /> <?php echo $totalvotes2; ?><br /> <span class='down'><a href="" class="vote" name="down" data-options="key1=<?php echo $mes_id1;?>&key2=<?php echo $mes_id2;?>"><img src="down.png" alt="down" /></a></span> </div> <div id="message"> <?php echo $message2; ?> </div> <div class="clearfix"></div> </div>

you need either enclose code $(document).ready(function() {});, or stick code @ end of <body> tag. personally, instead of making browser parse synchronous javascript before dom has loaded (in <head> section), stick near end. bootstrap recommends.

without dom loaded, there no elements created jquery register events with, , code literally sits there doing nil after beingness parsed.

aside that, .click() function executed on click. doesn't matter element it's bound to. if it's clickable, it's executable.

also reply question properly: <a href=""> refresh page. want use <a href="#">. this, however, create jump top of page. define <label> , utilize #labelname instead avoid this. or don't utilize href @ all. it's not needed.

also, little trick echoing variables html utilize <?= $var ?>

php jquery ajax post get

No comments:

Post a Comment