SomeRandomDeveloper
SomeRandomDeveloper

Reputation: 489

PHP function not being called, am i missing something obvious?

i think i need a second pair of eyes.

I have some ajax calling a php file, and it's returning json. This all works fine. I'm then alerting the data elements i return for testing purposes. In doing this i narrowed down my function is not being called.

<?php

// database functions
$response = array();
$count = 1;

// connect to db
function connect() {   
$response['alert'] = 'connect ran'; // does not get alerted
}

// loop through query string
foreach ($_POST as $key => $value) {

switch ($key) {
    case 'connect':
        $response['alert'] = 'case ran';
        if ($value == 'true') {
        $response['alert'] = 'if ran'; // this is what gets alerted, should be overwriten by 'connect ran'
            connect(); // function call does not work?
        } else {
            $response['alert'] = 'false';
            $mysqli->close();
        }
        break;

        case 'otherstuff':
        break;
}
++$count;
}

$response['count'] = $count;

echo json_encode($response);

?>

Any ideas? Thanks.

Upvotes: 2

Views: 136

Answers (2)

mychalvlcek
mychalvlcek

Reputation: 4046

your $response variable is out of scope.. use global keyword inside your function to registering your outer variable(s)

function connect() {
    global $response;    
    $response['alert'] = 'connect ran';
}

or SDC's edit:

function connect($response) { 
    $response['alert'] = 'connect ran';
}

connect($response);

Upvotes: 6

wertigom
wertigom

Reputation: 313

actually you defined the result variable but in another type and you also have another result variable at the top so you put data in $result[] but you try to use $result so your code may not give you the expected result.

Upvotes: 0

Related Questions