yank yank - 7 months ago 11
PHP Question

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.

Plz suggest me, without negative vote if u do not understand my question.

Sorry if question is not clear. But I will try to clear question in comments.

Answer

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.

Comments