1

I just want to do the simple thing: on click get a variable value from the php file a display it on my page. E.g.

<div class="click" onclick="getMyValue()">Click me</>

<script>
function getMyValue() {
$.ajax({
        type: "POST",
        url: "basket_count.php",
        dataType: "json",
        success: function(res) {
            console.log(res['item_count']);
            console.log("success");
        },
        error: function() {
            console.log("Error");
        }
    });
}
</script>

basket_count.php

$item_count = 3;
echo json_encode($item_count);

Not working though. I'm getting "Error" in my console.log();

UPD: I've tried to add this to error: error: function(err) { console.log(err);}

Below is the message i'm getting: enter image description here

UPD: Nothing was wrong with the code, the issue was that I was including "header.php" in my php file, so there was some conflict with it. I removed it and it started to work just fine.

18
  • 3
    what error you got? Commented Feb 21, 2018 at 10:10
  • Also post your getMyValue() code Commented Feb 21, 2018 at 10:12
  • Write AJAX code in getMyValue function, I cannot see getMyValue function defined in your code. Commented Feb 21, 2018 at 10:14
  • can you also try : error: function(res) { console.log(res); } Commented Feb 21, 2018 at 10:22
  • In your PHP try $result['item_count'] = 3; echo json_encode($result); and in your ajax console.log(res.item_count); Commented Feb 21, 2018 at 10:24

2 Answers 2

1
<div class="click" onclick="getMyValue()">Click me</>

<script>

$.ajax({
        type: "POST",
        url: "basket_count.php",
        dataType: "json",
        data:{get:"item_count"};
        success: function(res) {
            console.log(res.responseText);
            console.log("success");
        },
        error: function() {
            console.log("Error");
        }
    });
</script>

and in php add this :

if($_POST['get']==item_count){
 echo $item_count;
}
Sign up to request clarification or add additional context in comments.

Comments

0

There are 2 things here if you need to fetch variable value directly from php file then alert(res); you will get 3 in alert.

You have used echo json_encode($item_count); instead make array with key and pass it to json encode. echo json_encode(array("item_count" => $item_count)); you will get 3 with console.log(res['item_count']);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.