How To Update Mysql With Php And Ajax Without Refreshing The Page
Solution 1:
Ajax in jQuery works like this:
var myData=1;
$.ajax({
type:'POST',//type of ajaxurl:'mypage.php',//where the request is goingdata:myData,//the variable you want to sendbeforeSend:function(xhr){//as a standard, I add this to validate stuffif(someThingWrong===true)xhr.abort//aborts xhttpRequest
},
success:function(result){
//result is your result from the xhttpRequest.
}
});
This will not refresh your page but send a 'POST' to the url specified. On your specified page you want to do whatever it is you want to do and say return a result. In my example I'll do something simple:
if($_POST['myData']===1)returnTrue;
That's the basics of an AJAX request using jQuery.
EDIT!
initiating an AJAX script: I'm only guess as I don't know your elements within your html nor your scripts what so ever! So you'll have to make adjustments!
$('button.dislike').click(function(){
$.ajax({
type:'POST',
url:'disliked.php',
data:{dislike:$(this).attr('id')},
success:function(result){
$(this).prev('span').append(result);
}
});
});
PHP: don't use mysql, it's now been depreciated and is considered bad practise, I also don't know why're using sprintf on the query? :S
$DBH=new mysqli('location','username','password','database');
$get=$DBH->prepare("SELECT dislike FROM random WHERE ids=?");
$get->bind_param('i',$_POST['dislike']);
$get->execute();
$get->bind_result($count);
$get->close();
$update=$DBH->prepare('UPDATE random SET dislike=? WHERE ids=?');
$update->bind_param('ii',++$count,$_POST['dislike']);//if you get an error here, reverse the operator to $count++.$update->execute();
$update->close();
returnString$count++;
This will only work if there in your HTML there is a series of buttons with ID's matching those in your database. So
$get=$DBH->prepare('SELECT ids FROM random');
$get->execute();
$get->bind_result($ids);
while($get->fetch()){
echo"<button class='dislike' id='".$ids."'>Dislike this?</button>";
}
Hope you get the general idea of how I'm managing your dislike button system XD lol
Post a Comment for "How To Update Mysql With Php And Ajax Without Refreshing The Page"