Jump to content

Return vs Echo


Go to solution Solved by ginerjm,

Recommended Posts

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?

Link to comment
https://forums.phpfreaks.com/topic/314957-return-vs-echo/
Share on other sites

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);
}
?>

 

 

Link to comment
https://forums.phpfreaks.com/topic/314957-return-vs-echo/#findComment-1597576
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.