I have the following code for a checkbox
<div class="switch switch-lg switch-primary">
<input type="checkbox" name="switch" data-plugin-ios-switch checked="checked" value="usersname:1" />
</div>
When I change the checkbox, the following event is triggered
<script>
$('input[name="switch"]').on('change', function(){
$.ajax({
type: 'POST',
url: 'page.php',
data: {
example: $('#example').val()
}
}).always(function(data, textStatus, jqXHR) {
if (data.response == 'success') {
// Success
} else {
// Error
}
});
});
</script>
I am wondering how I get the value of "usersname:1" in my page.php? I'm guessing it's around example: $('#example').val()?
Basically the page.php will update a mysql database with the value 1, but specific to only that user, so i need to somehow pull up the username:1 in that script portion or the page.php but don't know how to call it.
Thanks in advance!
4 Answers 4
In order to send data to php your have to modify your code line:
data: {
example: $('#example').val()
}
to:
data: {
example: $('#example').val(),
switch: $(this).val()
}
The code finally becomes:
$('input[name="switch"]').on('change', function(){
console.log($(this).val());
$.ajax({
type: 'POST',
url: 'page.php',
data: {
example: $('#example').val(),
switch: $(this).val()
}
}).always(function(data, textStatus, jqXHR) {
if (data.response == 'success') {
// Success
} else {
// Error
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="switch switch-lg switch-primary">
<input type="checkbox" name="switch" data-plugin-ios-switch checked="checked" value="usersname:1" />
</div>
In PHP you can get value using $_REQUEST['switch']
Comments
Add id attributes in your checkbox. You can't define id attributes in checkbox .
<div class="switch switch-lg switch-primary">
<input type="checkbox" id="example" name="switch" data-plugin-ios-switch checked="checked" value="usersname:1" />
</div>
Otherwise You can change example: $('#example').val() to example: $(this).val()
1 Comment
You can get example value in page.php by $_POST['example']
Comments
Ok, this is a tricky one.
With example: $('#example').val() you will pass the VALUE of an input with ÌD example as a post var (so you can catch it with $_POST["example"] in the end script. Thing is, anyone can put anything into that and edit other username.
You should be doing this by calling a $_SESSION variable with the userid or something alike so people don't tamper with the data or make some XSS.
So, if you want to go with that, just put the ID example into your input and it will work (or edit it to match your fields), but i suggest to find another way.