I'm creating a PHP application where I have to send a JavaScript variable to the same page and then use it in PHP. However when I run my code the output shows and is correct but it goes away and dissappears.
$.ajax({
type: 'POST',
url: 'ajax.php',
data: { id: 1},
success: function(result) {
$('body').html(result);
console.log(result);
},
error: function() {
alert('Some error happened. Please try again!');
}
});
I accessed the posted variable via PHP post variable and the output is correct but I cant get it to stay on the screen. Is the innerHTML of my ajax.php being overwritten?
The console shows correct output also !
You are calling body attributes, try changing this line:
$('body').html(result);
To;
$("#myResult").html(result);
You can now print your response by adding this to your HTML code:
<div id="myResult"></div>
If you want to select via a Class instead:
$(".myResult").html(result);
Here, the ID selector #
is replaced by the Class selector .
so your div
will now become:
<div class="myResult"></div>
Now try this:
$.ajax({
type: 'POST',
url: 'ajax.php',
data: {id: 1},
success: function(result) {
// $('body').html(result);
// $(".myResult").html(result);
$("#myResult").html(result);
console.log(result);
},
error: function() {
alert('Some error found. Please try again!');
}
});
On the HTML side enter this:
<div class="myResult"></div>
If it still doesn't work, then post your PHP code and I'll help you get it fixed.
Are you doing something else with your html <body>
element? If I were you, I'd make a new element in the body and put your results there.
$.ajax({ type: 'POST', url: 'ajax.php', data: { id: 1}, success: function(result) { $('#results').html(result); console.log(result); }, error: function() { alert('Some error found. Please try again!'); } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <html> <head> <title>Title</title> </head> <body> <div id="results"></div> </body> </html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.