Now I am upgrading my website user experience, so I’m trying modify my form from form action
to ajax
.
Coding now work fine, server side can update the database, but I don’t know how to return the custom message to my user.
My html coding.
<form method="post" id="jnfarm_pop">
blablabla...
<button type="submit" class="layui-btn layui-btn-fluid" name="submitbutn" onclick="login();">submit</button>
</form>
My php file plugin.php
<?php
//coding.....
$final = 'custom wording';
return json_encode(['final' => $final]);
?>
My jQuery
<script>
function login() {
jQuery.get('plugin.php?id=cc&do=dd', jQuery('#jnfarm_pop').serialize(), (result) => {
alert($final); //it doesn't work
}).fail(result => {
alert('fail');
});
event.preventDefault();
}
</script>
Now the alert
doesn’t work, I am also try like
jQuery.get('plugin.php?id=cc&do=dd', jQuery('#jnfarm_pop').serialize(), (result) => {
result = JSON.parse(result); alert(result.final); //not working also
}
and
jQuery.get('plugin.php?id=cc&do=dd', jQuery('#jnfarm_pop').serialize(), (result = JSON.parse(result)) => {
alert(result.final); //this show alert unidentified
}
Can someone correct my coding?
2
Answers
Change
to
return
is really only useful when you’re inside a PHP function. If you want to output something back to the caller of the script then you need to useecho
, as always.To make your example work do the following:
change your PHP code from
to:
and your jQuery code from this:
to this:
PHP can return something to an ajax call by either printing or echoing. And ajax can’t use variables you defined in PHP. The echo’ed value in your PHP script will be the result value in your ajax call.