checkbox on change ajax call - javascript

I have one checkbox. I want when I checked the checkbox so I get the 1 and then update a mysql query through that get value.
I also want if I unchecked the checkbox so I get a value 0 so then I again update the mysql query. Help me. it should be done with ajax call. code will be in PHP.
HTML code
<input type="checkbox" name="action1" id="action1" title="Action 1" value="1" onclick="return Populat_Industry('set_home_vid.php');"/>
ajax call
<script>
function Populat_Industry(url){
var value=$(#action1).val();
$.ajax({
type: "POST",
url: url,
async: true,
data: "value="+value,
success: function(msg){
//alert('Success');
if(msg !='success'){
//alert('Fail');
}
}
});
}
</script>
PHP code
if($_POST['action1']=='1'){
$query= mysql_query("UPDATE homevideos SET is_active = '1
}
else{
mysql_query("UPDATE homevideos SET is_active = '0')
echo 'success';

Ajax call is async. you cannot use return with it this way. Write checkbox change event in jquery and send ajax call.
Do like this:
HTML:
<input type="checkbox" name="action1" id="action1" title="Action 1" value="1"/>
JQUERY:
$("#action1").change(function () {
var value = $(this).val();
$.ajax({
type: "POST",
url: "set_home_vid.php",
async: true,
data: {
action1: value // as you are getting in php $_POST['action1']
},
success: function (msg) {
alert('Success');
if (msg != 'success') {
alert('Fail');
}
}
});
});

HTML :
<input type="checkbox" name="action1" id="action1" title="Action 1" value="1" url="set_home_vid.php" />
JQuery:
<script>
$("#action1").change(function(){
var value = $(this).val();
var url = $(this).attr("url");
$.ajax({
type: "POST",
url: url,
data: "value="+value, //POST variable name value
success: function(msg){
if(msg =='success'){
alert('Success');
}
else{
alert('Fail');
}
}
});
});
</script>
PHP:
if($_POST['value']==1){ //as used variable name "value" in ajax post data
$query= mysql_query("UPDATE homevideos SET is_active = 1"); //query was incomplete and missing ";"
echo 'success';
}
else{
mysql_query("UPDATE homevideos SET is_active = 0); // missing ";"
echo 'success';
}

Maybe you could use the .is jquery method
something like this:
$("#i").bind("change",function(){
if($(this).is(":checked"))
// set value for ajax
else
// set another value for ajax
// ajax code here
});

You forgot to put quotes around your call to get the input value:
var value=$("#action1").val()

Related

How to get POST data using Jquery AJAX

I am trying to POST simple data using AJAX. My HTML code is
<input type="text" value="myvalue" id="sweet" name="sweet">
<button type="submit" id="mybtn-1">
My JQuery code is
$('#mybtn-1').click(function(){
var newSweet = $('#sweet').val();
if($.trim(newSweet) !== '')
{
$.ajax({
url:"../test_chat.php",
method:"POST",
data:{sweet:newSweet},
dataType:"text",
success:function(data){
$('#test_wrap').load("../test_chat.php").fadeIn("slow");
alert('Success');
}
});
}
});
And my test_chat.php code is
<?php
echo $_POST["sweet"];
echo 'hello';
?>
I want to echo the POST data in a div with the name "test_wrap". The problem is after clicking the button, I can only echo "hello" on the page.
I know it's happening because the load function is reloading the PHP file but I am looking for a solution so that I can show the POST data on my page.
You could return the data directly from your test_chat.php file after the post request, no need for double request here, return data like :
<?php
echo $_POST["sweet"];
echo 'hello';
?>
Then append it to the div #test_wrap like :
$('#mybtn-1').click(function(){
var newSweet = $('#sweet').val();
if($.trim(newSweet) !== ''){
$.ajax({
url:"../test_chat.php",
method:"POST",
data:{sweet:newSweet},
dataType:"text",
success:function(data){
$('#test_wrap').html(data).fadeIn("slow");
alert('Success');
}
});
}
});
Hope this helps.
You don't need to echo it with PHP, you can display it directly from the jQuery success callback:
$.ajax({
url: "../test_chat.php",
method: "POST",
data:{
sweet: newSweet
},
success: function(data) {
$('#test_wrap').load("../test_chat.php").fadeIn("slow");
if (data !== null && data !== undefined) {
alert('Success');
// Here "data" is whatever is returned from your POST
$("#some_content").html(data);
}
}
});
do ajax request of this way in js file:
$.ajax({
data: {keys: values}/*keys you need to post (sweet: newsweet)*/
, type: 'post'
, dataType: 'json'
, url: './php/someFile.php'
, error: function (jqXHR, status, err) {
console.log(jqXHR, status, err);
}
, success: function (response) {
/*use response to innerHTML into a div here*/
}
});
use echo json_encode in php:
<?php
echo json_encode($_POST["sweet"] /*or some value from function in php*/);/*of this way, you can return a response
from server to client, echo just print something, but does not return...*/
?>

How to send select value to php using ajax?

i m trying to passe the value of the selected item from a select tag using ajax for that :
here it is the select tag(it is not in a form):
<select class="select" id="select" >
</select>
here it is the code that fill the select from the database using php:
$(document).ready(function(){
<?php foreach ($espace_ids as $row ) {?>
$('#select').append('<option value="<?php echo $row['espace_id']; ?>"><? php echo $row['nom']; ?></option>');
<?php }?> });
for sending data from the actual page to dashbored.php,here it is the code:
$("#select").change(function() {
$.ajax({
type: 'post',
url: "<?php //echo base_url(); ?>index.php?directeur/dashboard ?>",
data: espace_id: $("#select").val(),
success: function( data ) {
alert( data );
}
});
well i retrieve the value sent with :
$espace_id=$_POST['espace_id'];
the probleme that it display : undefined refrence to espace_id in dashboard.php.
well , the pupose is to load the espace info from the database according to the espace selected by the user.each time the user select an option i should load the appropiate info related to the espace selected.
i wish that you gonna help me.
thanks
You can use following example to get espace id in index.php.
$(document).ready(function ()
{
$('#select').on('change', function ()
{
if ($('#select').val() === null) {
alert("Error");
}
else
{
var selectedValue = $('#select').val();
$.ajax
({
url: 'index.php',
type: 'POST',
data: 'espace_id=' + selectedValue,
success: function(response)
{
alert(response);
}
});
}
});
});
on index.php
if(isset($_POST['espace_id']) && !empty($_POST['espace_id']))
{
// do whatever you want to do here!!
}
For those that want to keep it lighter than Jquery you could do something like this:
<select onchange="livesearch(this.value)"><option></option></select>
<script>
function livesearch(id){
xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET","url?id="+id, false); xmlhttp.send(null); document.getElementById("searchresults").value=xmlhttp.responseText; }
</script>

Check/uncheck checkbox depend on data come from database

I am trying to check or uncheck a checkbox depending on the data from mysql database. I use nusoap webservice/webclient to read data and data value can be 1 or 0.
My code is:
<input name="check1" type="checkbox" id="check1" class="sag">
<script>
function control() {
$.ajax({
type: "POST",
url: "check.php",
data: {
checkdata: 1
},
success: function(asd) {
if (asd == '1') {
document.getElementById('check1').setAttribute("checked", true);
alert('data is 1');
} else {
document.getElementById('check1').removeAttribute("checked");
alert('data is 0');
}
}
});
}
</script>
<body onload="control()">
With this code i can get data from database correctly and alert() works fine. But these codes don't add checked attribute to checkbox. How can i change check status of checkbox according to the data come from database on load of the page?
Since you are already using jQuery why don't you use jQuery methods to set the required values.
function control(){
$.ajax({
type: "POST",
url: "check.php",
data: {checkdata: 1},
success: function(asd){
$('#check1').prop("checked", asd == '1');
}
});
}

ajax html $_POST value from php function returns null

I have this html field
<input type='text' name='newusername' value='' class='input-required' id='username'>
and this is my php code in my function.php
add_action('wp_ajax_checkUsernameExistentVal', 'checkUsernameExistentVal');
add_action('wp_ajax_nopriv_checkUsernameExistentVal', 'checkUsernameExistentVal');
function checkUsernameExistentVal(){
$username = $_POST['newusername']; // it alwas null?
// $username = 'existedusuer'; // works fine
$val = checkCOntactUsernameExist($username);
if ($val){
$usernname_val= 'false';
}else{
$usernname_val = 'true';
}
// I concatenate `$username` to check if it has a value but it is always null?
echo json_encode(array("validation" => $usernname_val.'-'.$val.'-'.$username));
wp_die();
}
and this is my scipt.js.
jQuery('#username').blur(function() {
jQuery.ajax(
{
url: ajax_url,
type: "POST",
dataType: "json",
data: {
action: 'checkUsernameExistentVal',
email: jQuery(this).val(),
},
async: false,
success: function (data)
{
alert(data + ' | '+ data.validation);
// data.validation value is always 'true--'??
},
});
});
I have no idea why in my function.php in the function in $_POST['newusername'] is always null.. do you have idea about this? seems my other code is working but this is not...
You pass on on jquery email in a data so that variable you should pass on.
because you pass the value in email.But getting value in $_POST['username']. so In that variable value is null.
$username = $_POST['email'];
You missed the parameter in the function . You need to supply the variable posted to the function.
function checkUsernameExistentVal($usernameParam)

Passing POST variables from jQuery to PHP, want to update div

I am trying to pass the form value "New Value" from jQuery to a PHP script, and then update the "to_change" div from "Old value" to "New value". It seemed like the AJAX call succeeded, but the POST variables are not being sent to the PHP script, and when I use getJSON, I do not succeed. How could I resolve this issue?
Javascript/HTML code:
<html>
<head>
<script src = 'jquery-1.10.2.js'></script>
<script>
$(document).ready(function() {
$("#form_tmin").submit(function(event) {
var values = $(this).serialize();
$.ajax({
type: "POST",
url: "parameters_form2.php",
data: values,
dataType: "json",
success: function(data){
$.getJSON("parameters_form2.php", function(tmin) {
document.getElementById("to_change").innerHTML = tmin[1];
});
}
});
return false;
});
});
</script>
</head>
<body>
<div id="to_change">Old value</div>
<form id="form_tmin" name="form_tmin">
<input type="hidden" id="tmin_value" name="tmin_value" value="New value">
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
PHP code:
<?php
header('Content-Type: application/json');
if ($_POST["tmin_value"]) {
$tmin[1] = $_REQUEST["tmin_value"];
}
else {
$tmin[1] = "FAILURE";
}
echo json_encode($tmin);
?>
You already have json response in data just set this data in where ever you want to display. you don not need $.getJSON again.
try like this:
$(document).ready(function() {
$("#form_tmin").submit(function(event) {
var values = $(this).serialize();
$.ajax({
type: "POST",
url: "parameters_form2.php",
data: values,
dataType: "json",
success: function(data){
document.getElementById("to_change").innerHTML = data[1];
}
});
return false;
});
});
You already have the response of query, no need to use $.getJson again
Instead just use:
success: function(data){
$("to_change").html(data[1]);
}

Categories

Resources