Load function between AJAX and Wordpress doesn't work - php

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);
});

Related

Ajax post data through name

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 :)

scroll to top even with a ajax call

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>

Jquery: Option selected not work in rendered select list

I had a countries/state chained select box pulled from database (rendered select list), however I want the specific option value remain selected when the page is redirected back by certain action. The user input fields are temporarily stored in SESSION, all fields is able to retained the value, excepted Country and State field.
I couldn't find these pulled option tag (which is rendered) appeared in view-sources, but I can view it in Chrome console and Firebug, thus I believe jquery cannot find the particular option value to perform the action, whereas when I hard-code the options, the below script is working:
Append options
function ajaxCall() {
this.send = function(data, url, method, success, type) {
type = type||'json';
var successRes = function(data) {
success(data);
};
var errorRes = function(e) {
console.log(e);
alert("Error found \nError Code: "+e.status+" \nError Message: "+e.statusText);
};
$.ajax({
url: url,
type: method,
data: data,
success: successRes,
error: errorRes,
dataType: type,
timeout: 60000
});
}
}
function locationInfo() {
//var rootUrl = "http://lab.iamrohit.in/php_ajax_country_state_city_dropdown/api.php";
var rootUrl = jsbaseurl + '/inc/api-get-location.php';
var call = new ajaxCall();
/* disabled get cities
this.getCities = function(id) {
$(".cities option:gt(0)").remove();
var url = rootUrl+'?type=getCities&stateId=' + id;
var method = "post";
var data = {};
$('.cities').find("option:eq(0)").html("Please wait..");
call.send(data, url, method, function(data) {
$('.cities').find("option:eq(0)").html("Select city");
if(data.tp == 1){
$.each(data['result'], function(key, val) {
var option = $('<option />');
option.attr('value', key).text(val);
$('.cities').append(option);
});
$(".cities").prop("disabled",false);
}
else{
alert(data.msg);
}
});
};
*/
this.getStates = function(id) {
$(".states option:gt(0)").remove();
$(".cities option:gt(0)").remove();
var url = rootUrl+'?type=getStates&countryId=' + id;
var method = "post";
var data = {};
$('.states').find("option:eq(0)").html("Please wait..");
call.send(data, url, method, function(data) {
$('.states').find("option:eq(0)").html("Select state");
if(data.tp === 1){
$.each(data['result'], function(key, val) {
var option = $('<option />');
option.attr('value', key).text(val);
$('.states').append(option);
});
$(".states").prop("disabled",false);
}
else{
alert(data.msg);
}
});
};
this.getCountries = function() {
var url = rootUrl+'?type=getCountries';
var method = "post";
var data = {};
$('.countries').find("option:eq(0)").html("Please wait..");
call.send(data, url, method, function(data) {
$('.countries').find("option:eq(0)").html("Select country");
console.log(data);
if(data.tp === 1){
$.each(data['result'], function(key, val) {
var option = $('<option />');
option.attr('value', key).text(val);
$('.countries').append(option);
});
$(".countries").prop("disabled",false);
}
else{
alert(data.msg);
}
});
};
}
$(function() {
var loc = new locationInfo();
loc.getCountries();
$(".countries").on("change", function(ev) {
var countryId = $(this).val();
if(countryId !== ''){
loc.getStates(countryId);
}
else{
$(".states option:gt(0)").remove();
}
});
/* Disabled city
$(".states").on("change", function(ev) {
var stateId = $(this).val();
if(stateId != ''){
loc.getCities(stateId);
}
else{
$(".cities option:gt(0)").remove();
}
});
*/
});
Jquery to retain selected option
<script>
$(document).ready(function(){
localStorage.setItem('selCountry', '<?php echo $cust_country_code ?>');
$('.countries').find('option').each(function(i,e){
if($(e).val() == localStorage.getItem('selCountry')){
$('.countries').prop('selectedIndex',i);
}
});
});
</script>
**the $cust_country_code is return countries id that
HTML - Options is rendered from db + jquery.
<select name="co_country" class="countries">
<option value="">Select Country</option>
<!-- HARDCODED FOR TEST, WORKING!
<option value="111">Brazil</option>
<option value="142">Germany</option>
<option value="123">Austria</option>
<option value="145">Japan</option>
-->
</select>
I was included $(document).ready() in order jquery to run while DOM is loaded, but no luck, any workaround?

sending data via ajax in Cakephp

i am new to cakephp and trying to send data from ajax to my controller action..
i have a popup model in which there is a input box ..i want to grab that value and send to controller without page refresh
here is my code ..
<a class="button anthracite-gradient" onclick="openPrompt()">submit </a>
my javascript
function openPrompt()
{
var cancelled = true;
$.modal.prompt('Please enter a value:', function(value)
{
$.ajax({
type:"POST",
url:"/cakephp/controller/action/",
success : function(data) {
alert(value); //value right now is in this variable ... i want to send this variable value to the controller
},
error : function() {
alert("false");
}
});
}, function()
{
});
};
</script>
myController
public function action(){
if( $this->request->is('ajax') ) {
$new = $this->request->data;
echo "ok"
return;
}
}
i want to first get the value here and then send the response to may ajax request
Its simple post the value to the controller and do what you want , in ajax request bind the value in data:{value_to_send:value} and get in controller
function openPrompt()
{
var cancelled = true;
$.modal.prompt('Please enter a value:', function(value)
{
$.ajax({
type:"POST",
data:{value_to_send:value},
url:"/cakephp/controller/action/",
success : function(data) {
alert(data);// will alert "ok"
},
error : function() {
alert("false");
}
});
}, function()
{
});
};
</script>
public function action(){
if( $this->request->is('ajax') ) {
// echo $_POST['value_to_send'];
echo $value = $this->request->data('value_to_send');
//or debug($this->request->data);
echo "ok"
die();
}
}
For more see accessing-post-data
I will give you some example. In my case, list out book list as a smart search while typing on text box.
$( ".selectBook" ).each(function(){
$(this).keyup(function( event ) {
var tri = $(this).val();
var oPrnt = $(this).parents('.smartsearch');
var str = '';
if(tri.length > 2){
$.ajax({
type: "POST",
url: "/utility/getbooks/",
data: JSON.stringify({string: tri, activeonly:false}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data, function(key, val) {
str += '<li id="a'+key+'" term="'+val+'" data-did="'+key+'">'+val+'</li>';
});
oPrnt.find("ul.result").html(str);
},
error: function (errormessage) {
oPrnt.find("ul.result").html('<li><b>No Results</b></li>');
}
});
oPrnt.find("ul.result").slideDown(100);
}
});
});
And in the controller, action (getbooks Action in UtilityController in my case)
public function getbooks($string = '', $activeonly = true){
$this->autoRender = false;
if( $this->request->is('ajax') ) {
$data = $this->request->input('json_decode');
$string = $data->string;
$activeonly = $data->activeonly;
}
$aReturn = array();
// ... fetch books data from DB goes here...
$aResult = $this->Book->fetch('list');
foreach($aResult as $r){
if(isset($r['bookname'])){
$aReturn[$r['id']] = $r['bookname'];
}
}
return json_encode($aReturn);
}

AJAX and Wordpress - how to load content from div ID?

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.

Categories