i have read all the stackoverflow solutions but it didnt work.
i have some divs and when i click on them it should change and load different data from server via ajax.
but whenever i click on it the page scroll to top.
i have tried "return false" and preventDefault .
here is my code:
$('.part').click(function(e) {
var _this = $(this);
if ($(this).attr('data-selected') == "") {
_this.html('');
var id = 76;
$.post('banners/bannerjs.php', {
'id': id
}, function(result) {
$(_this).append(result);
$(_this).attr('data-selected', 'selected');
});
} else if ($(this).attr('data-selected') == "selected") {
alert('salam');
}
return false;
});
and here is my html code:
<div class="part type<?php echo $w['TypeID']?>" style="" data-price="<?php echo $w['Price']?>" data-id="<?php echo $w['id']?>"
data-selected="<?php echo $selected?>" data-banner-selected="<?php echo $w['Display_Banner_Selected']?>"
data-banner="<?php echo $w['Display_Banner']?>">
<script type="text/javascript">
//jQuery.ajaxSetup({async:false});
if($('[data-id="<?php echo $w['id']?>"]').attr('data-selected') == "selected"){
var id = <?php echo $w['Display_Banner_Selected']?>;
}else{
var id = <?php echo $w['Display_Banner']?>;
}
$.post('banners/bannerjs.php', {'id': id}, function(result) {
$('[data-id="<?php echo $w['id']?>"]').append(result);
});
$('.<?php echo $banner['name'].$banner['id']?>').append('<div class="partPrice"><?php echo $w["Price"]?></div>');
</script>
<br>
</div>
Try returning false after your post:
$('.part').click(function(e) {
var _this = $(this);
if ($(this).attr('data-selected') == "") {
_this.html('');
var id = 76;
$.post('banners/bannerjs.php', {
'id': id
}, function(result) {
$(_this).append(result);
$(_this).attr('data-selected', 'selected');
return false; //added this
});
} else if ($(this).attr('data-selected') == "selected") {
alert('salam');
return false; //added this
}
return false;
});
Updated code:
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
<script>
$(function(){
$(".part").click(function(e) {
e.preventDefault(); //this disables the default behavior of the element
var _this = $(this);
if ($(this).attr('data-selected') == "") {
_this.html('');
var id = 76;
$.post('testy.php', {
'id': id
}, function(result) {
$(_this).append(result);
$(_this).attr('data-selected', 'selected');
});
} else if ($(this).attr('data-selected') == "selected") {
alert('salam');
}
return false;
});
})
</script>
<a class="part" data-selected="">Foo</a>
Related
If I add caption to image it's working, if I add one more caption without refreshing the page the 1st value is posting to the second one...
$(document).ready(function () {
$(".cap_btn").click(function(){
var li = $(this).closest("li");
var cap = $('input[name="cap"]').val();
$.ajax({
type: "POST",
url: "addcap.php",
data: { id: li.data("imageId"), "cap": cap},
success: function(data){
alert("Caption Added");
},
error: function(){
alert("failure");
}
});
});
});
php code:
if(isset($_POST['id'])){
$ids = $_POST['id'];
$cap = $_POST['cap'];
try
{
$query = "UPDATE image SET caption='$cap' WHERE id='$ids'";
$sql=$con->prepare($query);
$sql->execute();
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
}
You can do it like this
$(document).ready(function () {
$(".cap_btn").click(
function()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
alert("Caption Added");
}
else
{
alert("failure");
}
};
xmlhttp.open("POST", "addcap.php", true);
var formdata = new FormData();
var li = $(this).closest("li");
var cap = $('input[name="cap"]').val();
formdata.append("id",li.data("imageId"));
formdata.append("cap",li.data("cap"));
xmlhttp.send(formdata);
});
});
Hope it helps :)
When I use ajax method to the data from server, I get the whole php page, not the echo info.Why?
JS:
var myApp = angular.module("MyApp",[]);
myApp.config(function($httpProvider){
$httpProvider.defaults.transformRequest = function(obj){
var arrStr = [];
for(var p in obj){
arrStr.push(encodeURIComponent(p)+"="+encodeURIComponent(obj[p]));
}
return arrStr.join("&");
};
$httpProvider.defaults.headers.post = {
"Content-Type": "application/x-www-form-urlencoded"
};
});
myApp.controller("content",["$scope","$http",function($scope,$http){
var postData = {name:"Liu"};
$scope.onClick = function(){
$http.post("http://oda53d5ps.bkt.clouddn.com/post.php",postData)
.success(function(data,status,headers,config){
$scope.result = data;
console.log(data);
});
};
}]);
In my PHP files, it is " $str = $_POST["name"]; if($str == "Liu") { echo "Success!"; } else { echo "Failed!"; }"
I'm hoping someone can help me...
Basically, neither if (data.status=='error') { or } else if (data.status=='success') { appear to be getting called yet the data is being inserted into the database fine.
add_alarm_code.php;
<?php
require_once('../inc/config.php');
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
// define and escape each POST as a variable
foreach ($_POST as $key => $value) {
if (!empty($value)) {
${$key} = mysqli_real_escape_string($con, $value);
}
}
// insert data into database
$sql="INSERT INTO alarm_code (
alarm_code_property,
alarm_code_code,
alarm_code_notes,
alarm_code_date_added
)
VALUES (
'$alarm_code_property',
'$alarm_code_code',
'$alarm_code_notes',
'" . date('Y-m-d') . "'
)";
if (!mysqli_query($con,$sql)) {
echo '{ "status": "error", "message": "Error Inserting Alarm Code Data into Database: ' . mysqli_error($con) . '" }';
} else {
echo '{ "status": "success", "message": "The alarm code has successfully been added to the system. The page will now refresh." }';
}
mysqli_close($con);
?>
jQuery on view_property.php;
// add alarm code submit form
$('#add_alarm_code').ajaxForm({
dataType: 'json',
success: processJson,
error: function (xmlRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
function processJson(data) {
if (data.status=='error') {
alert('Error 1');
$('#ajax_form_status_alarm_code').removeClass('green_background')
$('#ajax_form_status_alarm_code').addClass('red_background')
$('#ajax_form_status_alarm_code').html(data.message);
alert('Error 2');
} else if (data.status=='success') {
$('#add_alarm_code').clearForm();
$('#ajax_form_status_alarm_code').removeClass('red_background')
$('#ajax_form_status_alarm_code').addClass('green_background')
$('#ajax_form_status_alarm_code').html(data.message);
setTimeout(function() {
var currentURL = window.location.href;
var currentHashValue = window.location.hash;
if (currentHashValue!='') {
location.reload(true);
} else {
window.location.href += "#keys";
location.reload(true);
}
}, 3000);
}
}
form on view_property.php (the form is in a hidden div as it loads in a fancybox/lightbox)
echo '<div style="display:none">';
echo '<form id="add_alarm_code" action="' . SITE_AJAX . 'add_alarm_code.php" method="post">';
echo '<input type="hidden" id="alarm_code_property" name="alarm_code_property" value="' . $property_id . '">';
echo '<fieldset><legend>Add an Alarm Code</legend>
<table class="nobord">';
echo '<tr><td><label for="alarm_code_code">Alarm Code:</label></td>
<td><input type="text" id="alarm_code_code" name="alarm_code_code" maxlength="10" required></td></tr>';
echo '<tr><td><label for="alarm_code_notes">Notes:</label></td>
<td><textarea id="alarm_code_notes" name="alarm_code_notes" rows="6" cols="35"></textarea></td></tr>';
echo '<tr><td colspan="2"><input type="submit" value="Save"></td></tr>';
echo '</table>';
echo '<div id="ajax_form_status_alarm_code" class="ajax_form_status"></div>';
echo '</fieldset></form>';
echo '</div>';
entire jQuery on view_property.php (in case it helps find a bug!);
<script>
$(document).ready(function() {
// tab functionality on load
$(function(e) {
// define variables
var currentAttrValue = window.location.hash;
if (currentAttrValue!='') {
// show/hide tabs
jQuery('.tabs ' + currentAttrValue).fadeIn(400).siblings().hide();
// change/remove current tab to active
jQuery(currentAttrValue).parent('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
}
});
// tab functionality on click
jQuery('.tabs .tab-links a').on('click', function(e) {
var currentAttrValue = jQuery(this).attr('href');
// show/hide tabs
jQuery('.tabs ' + currentAttrValue).fadeIn(400).siblings().hide();
// change/remove current tab to active
jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
});
// fancybox
$(".fancybox").fancybox({
closeBtn : true,
modal : false
});
// apply validation
$( "#add_certificate" ).validate({
errorClass: "error-class",
});
$( "#add_keys" ).validate({
errorClass: "error-class",
});
$( "#add_alarm_code" ).validate({
errorClass: "error-class",
});
// add certificate submit form
$('#add_certificate').ajaxForm({
dataType: 'json',
success: processJson,
});
function processJson(data) {
if (data.status=='error') {
$('#ajax_form_status_certificate').removeClass('green_background')
$('#ajax_form_status_certificate').addClass('red_background')
$('#ajax_form_status_certificate').html(data.message);
} else if (data.status=='success') {
$('#add_certificate').clearForm();
$('#ajax_form_status_certificate').removeClass('red_background')
$('#ajax_form_status_certificate').addClass('green_background')
$('#ajax_form_status_certificate').html(data.message);
setTimeout(function(){
var currentURL = window.location.href;
var currentHashValue = window.location.hash;
if (currentHashValue!='') {
location.reload(true);
} else {
window.location.href += "#certificates";
location.reload(true);
}
}, 3000);
}
}
$( "#add_1_year" ).click(function() {
if ($('#certificate_start_date').val()!='') {
var expiry_date = moment($('#certificate_start_date').val()).add(1, 'year').format("YYYY-MM-DD");
$('#certificate_expiry_date').val(expiry_date);
} else {
alert('Please enter the certificate start date.');
}
});
// add alarm code submit form
$('#add_alarm_code').ajaxForm({
dataType: 'json',
success: processJson,
error: function (xmlRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
function processJson(data) {
if (data.status=='error') {
alert('Error 1');
$('#ajax_form_status_alarm_code').removeClass('green_background')
$('#ajax_form_status_alarm_code').addClass('red_background')
$('#ajax_form_status_alarm_code').html(data.message);
alert('Error 2');
} else if (data.status=='success') {
$('#add_alarm_code').clearForm();
$('#ajax_form_status_alarm_code').removeClass('red_background')
$('#ajax_form_status_alarm_code').addClass('green_background')
$('#ajax_form_status_alarm_code').html(data.message);
setTimeout(function() {
var currentURL = window.location.href;
var currentHashValue = window.location.hash;
if (currentHashValue!='') {
location.reload(true);
} else {
window.location.href += "#keys";
location.reload(true);
}
}, 3000);
}
}
// add keys submit form
$('#add_keys').ajaxForm({
dataType: 'json',
success: processJson,
});
function processJson(data) {
if (data.status=='error') {
$('#ajax_form_status_keys').removeClass('green_background')
$('#ajax_form_status_keys').addClass('red_background')
$('#ajax_form_status_keys').html(data.message);
} else if (data.status=='success') {
$('#add_keys').clearForm();
$('#ajax_form_status_keys').removeClass('red_background')
$('#ajax_form_status_keys').addClass('green_background')
$('#ajax_form_status_keys').html(data.message);
setTimeout(function(){
var currentURL = window.location.href;
var currentHashValue = window.location.hash;
if (currentHashValue!='') {
location.reload(true);
} else {
window.location.href += "#keys";
location.reload(true);
}
}, 3000);
}
}
});
</script>
I can't get the content from a div (width a specific ID) from single.php into index.php with ajax.
Now I have this code and returns nothing - "0".
function loadcontent(type,id,slug, action) {
jQuery.ajax({
type:'POST',
url:srvars.ajaxurl,
data: {
action:'sr_get_content',
id:id,
type:type
},
success: function(response) {
if ($(window).width() > 768) {
$('#content .content-inner').hide();
$('#content .content-inner').html(response);
initialise('#content');
}
var checkwidth = $('.maincontent').width();
$('#loading').delay(1000).fadeOut(fadeInOutSpeed, function(){
if ($(window).width() > 768) {
if (checkwidth > 0) {
reorganizeIsotope('.masonry');
$('#content .content-inner').fadeIn(fadeInOutSpeed, function() { resize_jplayer(); reorganizeIsotope('.masonry'); });
} else {
$('.mainside').animate({'width':srvars.asidewidth+'%'}, animationSpeed, $easingType);
$('.mainside-bg').animate({'width':srvars.asidewidth+'%'}, animationSpeed, $easingType);
$('.maincontent').animate({'width':srvars.contentwidth+'%'}, animationSpeed, $easingType, function() {
reorganizeIsotope('.masonry');
$('#content .content-inner').fadeIn(fadeInOutSpeed, function() { resize_jplayer(); reorganizeIsotope('.masonry'); });
});
}
} else {
$('#content .content-inner').hide();
$('#content .content-inner').html(response);
initialise('#content');
if ($(window).width() <= 480) { var topscroll = jQuery('header').height(); } else { var topscroll = 0; }
$('html, body').animate({scrollTop: topscroll+'px'}, animationSpeed, $easingType);
reorganizeIsotope('.masonry');
$('#content .content-inner').slideDown(fadeInOutSpeed, $easingType, function() {
resize_jplayer();
reorganizeIsotope('.masonry');
});
}
});
}
});
}
$("body").on("click", 'a.loadcontent', function() {
var href = $(this).attr('href');
var type = $(this).data('type');
var id = $(this).data('id');
var slug = $(this).data('slug');
if(window.location.hash.substr(1) == slug) {
$('html, body').animate({scrollTop: 0}, animationSpeed, $easingType);
} else {
window.location.hash = slug; // set the hash
//history.pushState({page:href}, href, href);
loadcontent(type,id,slug,false);
}
return(false);
});
and from functions.php
add_action('wp_ajax_nopriv_sr_get_content', 'loadAjaxPosts');
add_action('wp_ajax_sr_get_content', 'loadAjaxPosts');
function loadAjaxPosts() {
switch($_REQUEST['type']) {
case 'portfolio':
$output = sf_portfolio_items($_REQUEST['cat'], $_REQUEST['count'], $_REQUEST['page'], true);
break;
case 'blog':
$output = sf_blog_items($_REQUEST['cat'], $_REQUEST['count'], $_REQUEST['page'], true);
break;
default:
$output = 'Incorrect type specified, please contact support.';
break;
}
$output=json_encode($output);
if(is_array($output)) {
print_r($output);
} else {
echo $output;
}
die;
}
How to transfer the content? Thanks
Your loadContent() function's success handler does absolutely NOTHING. Hence whatever your php script sends back is simply thrown away.
You'd need something like:
success: function(response) {
$('#whatever').html(response);
}
Also note that your isarray($output) will NEVER work. json_encode() returns a STRING... never an array.
I can't get the content from a div (width a specific ID) from single.php into index.php with ajax.
Now I have this code and returns "0".
$("body").on("click", 'a.loadcontent', function() {
var href = $(this).attr('href');
var type = $(this).data('type');
var id = $(this).data('id');
var slug = $(this).data('slug');
});
function loadcontent(type,id,slug, action) {
jQuery.ajax({
type:'POST',
url:srvars.ajaxurl,
data: {
action:'sr_get_content',
id:id,
type:type
},
success: function(response) {}
});
}
and from functions.php
add_action('wp_ajax_nopriv_sr_get_content', 'loadAjaxPosts');
add_action('wp_ajax_sr_get_content', 'loadAjaxPosts');
function loadAjaxPosts() {
switch($_REQUEST['type']) {
case 'portfolio':
$output = sf_portfolio_items($_REQUEST['cat'], $_REQUEST['count'], $_REQUEST['page'], true);
break;
case 'blog':
$output = sf_blog_items($_REQUEST['cat'], $_REQUEST['count'], $_REQUEST['page'], true);
break;
default:
$output = 'Incorrect type specified, please contact support.';
break;
}
$output=json_encode($output);
if(is_array($output)) {
print_r($output);
} else {
echo $output;
}
die;
}
How to transfer the content?
Thanks
I have that part too..
$("body").on("click", 'a.loadcontent', function() {
var href = $(this).attr('href');
var type = $(this).data('type');
var id = $(this).data('id');
var slug = $(this).data('slug');
if(window.location.hash.substr(1) == slug) {
$('html, body').animate({scrollTop: 0}, animationSpeed, $easingType);
} else {
window.location.hash = slug; // set the hash
//history.pushState({page:href}, href, href);
loadcontent(type,id,slug,false);
}
return(false);
});