Say I have a function as following. alert_danger
returns the error message in red box. check_empty
checks if a value posted from form is empty or not.
function alert_danger($msg){
$alert = "<div class='alert alert-danger' id='responseBox'>".$msg."</div>";
return $alert;
}
function checkEmpty($postValue, $msg){
if($postValue == null){
echo alert_danger($msg);
exit();
}
}
Now when I want to return the function value using jSON it’s not returning the same. The following error is occuring:
// It returns this
$msg = alert_danger("Ah! Hello Adventurer, and welcome to the town of Honeywood!");
echo json_encode(array('status' => $msg));
// But it does not returns this
$msg = checkEmpty($state, "Ah! Hello Adventurer, and welcome to the town of Honeywood!");
echo json_encode(array('status' => $msg));
What seems to be the problem here?
Here is my jQuery if needed!
$(".action").click(function() {
var form = $(this).closest("form");
var type = form.find(".type").val();
var dataString = form.serialize();
var btnValue = $(".action").html();
var btnElement = $(".action");
var url = form.attr("action");
$.ajax({
type: "POST",
dataType : "json",
url: url,
data: dataString,
cache: true,
beforeSend: function(){
$('.message').hide();
$(".overlay").show();
$(".wickedpicker").hide();
btnElement.html('Please wait...');
},
success: function(json){
$('.message').html(json.status).fadeIn();
// $('#content').html(json.result).fadeIn();
$(".overlay").hide();
$("html, body").animate({ scrollTop: $(".message").offset().top }, "slow");
btnElement.html(btnValue);
if(type == 'admin'){
if($('.message').find('#responseBox').hasClass('alert-success')){
setTimeout(function(){
$(".overlay").hide();
window.location.replace("dashboard.php");
}, 1000);
}
}
}
});
return false;
});
2
Answers
Consider the following.
PHP
JavaScript
https://softwareengineering.stackexchange.com/questions/126671/is-it-considered-bad-practice-to-have-php-in-your-javascript
You have to be careful to not confuse
echo
andreturn
, they do very different things.https://www.php.net/manual/en/function.echo.php
https://www.php.net/manual/en/function.return.php
Since you’re passing back JSON data to the AJAX Call, I would advise wrapping your HTML inside the callback versus sending it back inside the JSON.
I think you should take a look at your success function. I think it normally runs before the page loads. So, its possible none of the html your referencing in there exists yet. So move it out to a function like this: