Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return JS value using AJAX

I have a code like this

$(document).ready(function() {
    $('#myHref').change(function(){
        var value = $('#myHref').val();
        $.get('get_projectName.php',{id:value},function(data)
        { 
        .....
        .....
        if(condition here){}
        }); 
    }); 
});

I need to check a condition according to the value returned from get_projectName.php. Let get_projectName.php have $abc = 1; and according to this value I need to use if condition.

like image 541
yank Avatar asked Feb 01 '26 02:02

yank


1 Answers

Your jquery condition will be totally depend on the type of data returned from the php function. Let's check for the example:-

Example 1 :-

If your php code is :-

<?php
if(isset($_GET['id'])){ // check id coming from `ajax` or not
  $data = 1; // as you said
}
echo $data;
?>

Then jquery will be:-

<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script><!-- library needed-->
<script type = "text/javascript">
$(document).ready(function() {
   $('#myHref').change(function(){ // you need to check that it is working or not because i don't know from where it is coming
        var value = $('#myHref').val(); // same as above check yourself.
        $.get('get_sales_price.php','',function(data){ 
            if(data ==1){
                alert('hello');
            }else{
                alert('hi');
            }
        });
    });
});
</script>

Example 2:-

But if your php code is like below:-

<?php
if(isset($_GET['id'])){ // check id coming from `ajax` or not
     $data = Array('a'=>1,'b'=>2);
}
echo json_encode($data);
?>

then jquery will be like below:-

<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type = "text/javascript">
$(document).ready(function() {
    $('#myHref').change(function(){
        var value = $('#myHref').val();
        $.get('get_sales_price.php','',function(data){ 
            var newdata = $.parseJSON(data);//parse JSON
            if(newdata.a ==1 && newdata.b !== 1){
                alert('hello');
            }else{
                alert('hi');
            }
        });
    });
});
</script>

Note:- these are simple examples, but conditions will vary in jquery, based on returned response from php. thanks.

like image 152
Anant Kumar Singh Avatar answered Feb 02 '26 14:02

Anant Kumar Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!