Reputation: 24061
I call a php function from ajax (addContent):
protected $output = array('success'=>0, 'message'=>'There was an error, please try again.');
public function addContent()
{
$imgName = $this->doSomething();
$this->doSomethingElse();
//save imageName to DB
$this->output['success'] = 1;
return $output;
}
private function doSomething()
{
if($imageOk){
return $imageName;
}
else
{
$this->output['message'] = 'bad response';
//how to return output?
}
}
I have made the methods simple for illustrative purposes.
If the method 'doSomething()' has an output of bad response, how can I send this back from the addContent method to ajax? If the output is bad, I want to exit the script and not continue executing doSomethingElse().
Upvotes: 1
Views: 102
Reputation: 1652
See of it solving (with throwing exception):
protected $output = array('success'=>0, 'message'=>'There was an error, please try again.'); public function addContent() { try{ $imgName = $this->doSomething(); $this->doSomethingElse(); //save imageName to DB $this->output['success'] = 1; return $this->output; } catch(Exception $e){ $this->output['success'] = 0; $this->output['message'] = $e->getMessage(); return $this->output; } } private function doSomething() { if($imageOk){ return $imageName; } else { throw new Exception('bad response'); } }
Upvotes: 1
Reputation: 2538
You could use exception handling.
protected $output = array('success'=>0, 'message'=>'There was an error, please try again.');
public function addContent()
{
try {
$imgName = $this->doSomething();
} catch (Exception $e) {
$this->output['message'] = $e->getMessage();
return $this->output;
}
$this->doSomethingElse();
//save imageName to DB
$this->output['success'] = 1;
return $output;
}
private function doSomething()
{
if($imageOk) {
return $imageName;
}
else {
throw new Exception('bad response');
}
}
Upvotes: 0
Reputation: 15150
Just make doSomething
return false if it fails validation, and then check for that condition:
public function addContent()
{
$imgName = $this->doSomething();
if ($imgName === false) {
return "your error message";
}
$this->doSomethingElse();
//save imageName to DB
$this->output['success'] = 1;
return $output;
}
private function doSomething()
{
if($imageOk){
return $imageName;
}
else
{
$this->output['message'] = 'bad response';
return false;
}
}
You could use either exit
or die
as per the comments, but those both kill the script immediately, so unless you were echoing or assigning your error message to a template before calling those functions, your error message wouldn't be returned.
Upvotes: 3