Adamhumbug Posted June 23, 2022 Share Posted June 23, 2022 I have a php function that is called via ajax: function getItemAttributesById($itemId){ require 'includes/dbconn.php'; $sql = "SELECT id, name, type, price_uk, price_us, price_ca, price_au, price_eu, billing_freq from item where id = :itemId"; $stmt = $pdo->prepare($sql); $bindData = [ 'itemId' => $itemId ]; $stmt->execute($bindData); $item = $stmt->fetch(PDO::FETCH_ASSOC); echo json_encode($item); } when i echo the $item at the end of the function and console.log the response in ajax, i can see the array. When i use the return keyword instead of echo i just see the word "Array". From my understanding of what they do, i wouldnt have thought there would have been a difference in what got back to the ajax function. Am i using it wrong? Quote Link to comment https://forums.phpfreaks.com/topic/314957-return-vs-echo/ Share on other sites More sharing options...
Solution ginerjm Posted June 23, 2022 Solution Share Posted June 23, 2022 An echo is an 'output' statement which is why you actually see something. A return is not. It is simply a method to pass a value back to another that is waiting to receive it. Quote Link to comment https://forums.phpfreaks.com/topic/314957-return-vs-echo/#findComment-1597575 Share on other sites More sharing options...
Barand Posted June 23, 2022 Share Posted June 23, 2022 Return values from functions. And stop conneting inside your functions! Connect once at top of script and pass the connection to your functions. I'd structure it something like this... <?php require 'includes/dbconn.php'; ## HANDLE AJAX CALL if ( isset($_GET['itemId']) ) { // if it's an ajax request exit(getItemAttributesById($pdo, $_GET['itemId'])); } function getItemAttributesById($pdo, $itemId){ $sql = "SELECT id, name, type, price_uk, price_us, price_ca, price_au, price_eu, billing_freq from item where id = :itemId"; $stmt = $pdo->prepare($sql); $bindData = [ 'itemId' => $itemId ]; $stmt->execute($bindData); $item = $stmt->fetch(PDO::FETCH_ASSOC); return json_encode($item); } ?> Quote Link to comment https://forums.phpfreaks.com/topic/314957-return-vs-echo/#findComment-1597576 Share on other sites More sharing options...
Adamhumbug Posted June 23, 2022 Author Share Posted June 23, 2022 Thanks both for the explanations. **removing endless includes for db from code now** Quote Link to comment https://forums.phpfreaks.com/topic/314957-return-vs-echo/#findComment-1597577 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.