Reputation: 525
Ok, I'm not a AJAX specialist so please hear me out...
I'm trying to echo some data to a div using a form submit, AJAX and PHP. I hope this is possible. I've looked around stackoverflow and google for an answer but could not find one for my purpose.
This is my HTML:
<article id="search-results">
<div class="container">
<div class="row">
<div class="col-sm-3">
<?php echo do_shortcode('[searchandfilter id="15"]');?>
</div>
<div class="col-sm-7">
<?php echo do_shortcode('[searchandfilter id="15" show="results"]'); ?>
<?php get_template_part('pagination'); ?>
</div>
<div class="col-sm-2">
<div id="txtHint">
<h4>Saved Items</h4>
<!-- ECHO OUTPUT -->
</div>
</div>
</div>
</div>
</article>
In the div txtHint
is where I want to have the output echoed. This is my form code:
<form id="ajaxform" class="content-items">
<div class="row">
<div class="col-sm-3">
<div class="thumbnail-content-items">
<?php if ( has_post_thumbnail()) : // Check if thumbnail exists ?>
<?php the_post_thumbnail(array(120,120)); // Declare pixel size you need inside the array ?>
<?php endif; ?>
</div>
</div>
<div class="col-sm-9">
<h2><?php the_title(); ?></h2>
<?php html5wp_excerpt('html5wp_index'); ?>
<div class="text-right">
<button type="submit" class="btn btn-primary text-right" data-toggle="modal" data-target=".post-<?php the_ID(); ?>" data-attribute="<?php the_title(); ?>" data-whatever="<?php the_title(); ?>">Save this item <span class="glyphicon glyphicon-heart" aria-hidden="true"></span></button>
</div>
</div>
</div>
And here is my AJAX script:
$("#ajaxform").submit(function(){
$.ajax({
type: "POST",
url: "example.com/reload.php",
data: "id=" + a_href,
success: function(data, textStatus) {
$(".txtHint").html(data);
},
error: function() {
alert('Not OKay');
}
});
return false;
});
This is in my php file:
<?php echo hello; ?>
There is something happening, the page is refreshed but this could also be the submit action from the form. Could any one help me get this to work?
Cheers
Upvotes: 1
Views: 985
Reputation: 10548
Change
$(".txtHint").html(data);
To
$("#txtHint").html(data);
As, txtHint
is ID not Class.
See, may be hello
get printed. But, due to page-reload, <div id='txtHint'>
is not able to show ajax response
. So, you have to use event.preventDefault();
for stopping page refresh.
Use the given code as it is. I removed data
as you also don't know why it is used as you copied it from somewhere.
$("#ajaxform").submit(function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: "example.com/reload.php",
success: function(data) {
$("#txtHint").html(data);
},
error: function() {
alert('Not OKay');
}
});
return false;
});
And here, put hello
in quotes.
reload.php
<?php echo "hello"; ?>
Upvotes: 2
Reputation: 2195
Use instead of
$("#ajaxform").submit(function(){
"id=" + a_href,
Into
$("#ajaxform").submit(function(e){
e.preventDefault();
{id : a_href},
Upvotes: 1