Scenario I have a page where users can activate or deactivate the service. I have got a button where it says the current state of the service. I achieve this by getting service state via php and echoing active
or inactive
at the place of the button text.
Problem I want a AJAX to listen for click on the button. When a user clicks on the active
button the AJAX should call a url which triggers change of the users' service state change and returns the current state of the user. I want to change the text in the button to active
if the reply was 200
and inactive
if the reply from the php was 101
.
I want to compare the result in a if-elseif-else style statement like
if(reply=='200')
code-to-change-the-text-to-active;
elseif(reply=='101')
code-to-change-the-text-to-in;
else
alert(some-error);
I made several searches and only found how to change the text with the text from the reply. But, I want a way to fetch the reply as variable and use it to switch my text.
You need to send your reply from PHP to JavaScript as JSON (using json_encode($reply)), then, your AJAX success callback function will receive the state value in a format it can use.
Use the following code format with your actual data:
HTML
<input type="button" value="active" id="active">
JS
$('#active').click(function () {
var status = $(this).attr('value'); // get the value of your button state
var r = confirm("Are You Sure Change Status?");
if (r==true){
$.ajax({
type: "POST",
url: "YOUR URL",
data:"{userstatus:status}",
beforeSend : function () {
},
success:function(result){
//Do whatever you want with result//
}
});
}else{
return false;
}
});
Note: when you click on the active button its call ajax function and put your actual url file name in url param. then run the sql query there and you will get response in success as result.
shortcut/ fast.
JS
function updateStatus(){
$.get('yourPHPCode/getStatus', function(data) ){
$('#status').val(data);
}
}
PHP
function getStatus(){ ... echo $status; }