Wordpress ajax call is returing the html of the page - php

I am getting the data from the sql table and storing the results inside the associative array after that i have encoded into json but the problem is that it is returning the html of the page along with the results
this is my php code
<?php
add_action('wp_ajax_nopriv_my_loadmore','my_loadmore');
add_action('wp_ajax_my_loadmore','my_loadmore');
function my_loadmore(){
global $wpdb;
$table_name="wpnn_tweets";
$paged=$_POST['page'];
$page=$paged*10;
$results = $wpdb->get_results("SELECT * FROM $table_name LIMIT 1 OFFSET $page");
$arr = array();
foreach($results as $row){
$arr['userScreen']=$row->userScreen;
$arr['userName']=$row->userName;
$arr['tweetCreated']=$row->tweetCreated;
$arr['tweetText']=$row->tweetText;
$arr['tweetRetweetCt']=$row->tweetRetweetCt;
$arr['tweetFavoriteCt']=$row->tweetFavoriteCt;
}
echo json_encode($arr);
wp_die();
}
?>
this is how i am retrieving the json in the front end
$ = jQuery;
function scroller() {
if($(window).scrollTop() + $(window).height() > $(document).height() - 200) {
$(this).off("scroll.ajax");
var page=parseInt($(this).data('page'));
var ajaxurl=$(this).data('url');
$.ajax({
url:ajaxurl,
type:"POST",
data:{
page:page,
action:"my_loadmore"
},
error:function(response){
console.log("error");
},
success:function(data){
for(i = 0; i < data.length; i++) {
console.log(data[i]);
}
}
});
}
}
$(window).on("scroll.ajax", scroller);

var ajaxurl = $(this).data('url');
This returns null unless you explicitly set it in your HTML. The easiest solution is to replace it with something like the following.
var ajaxurl = 'my-cool-endpoint';
This was not the solution to this particular problem, but I feel like it's a good thing to check for others coming to this page with the same problem. Replace wp_die() with die(). See the documentation for more details, but here is the relevant line.
A call to this function complements the die() PHP function. The difference is that HTML will be displayed to the user in the case of a typical web request.

Related

Count number of jQuery $.get success responses

I have a jQuery function that loads a PHP file (which gets a JSON response from an application) every 100ms. What I am trying to do is have two different counters, one which will increment every time a request is sent and another counter which will increment as soon as it gets a JSON response. At the moment I have the following which is not working, they are both just counting the number of requests being sent:-
JQUERY
$(function() {
var MAXNUM = 9;
var count = 0;
var countSuccess = 0;
function newAsyncRequest() {
setTimeout(function() {
newAsyncRequest();
count++;
$(".request").html(count);
$.get('test.php', function(data) {
countSuccess++;
$( ".log" ).html(countSuccess);
});
}, 100);
}
newAsyncRequest();
});
PHP
require_once('scripts/php/controllers/curl.controller.php');
$postcode = 'LE11 5';
$postcode = rawurlencode($postcode);
$uri = 'http://192.168.1.110:8290/?pc='.$postcode; // Home
$response = CurlController::request($uri);
So my question is basically, how can I count the number of successful responses I am getting from .$get command?
Need to print count to .request, you were using countSuccess in both the statements
$(function() {
var MAXNUM = 9;
var count = 0;
var countSuccess = 0;
function newAsyncRequest() {
setTimeout(function() {
newAsyncRequest();
count++;
$(".request").html(count);
//need to print here
$.get('test.php', function(data) {
countSuccess++;
$( ".log" ).html(countSuccess);
});
}, 100);
}
newAsyncRequest();
});
You can use $.ajax's success parameter. The function passed to this parameter will only run if an ajax request is successful.
$.ajax({
url:"",
type: "get",
beforeSend: function(){ requestCounter++ },
success: function(){ successCounter++ }
});
What are you defijning as a success?
The .get 'success' is that the server responded which it hopefully always will do.
If you are definign success as somthign working in the PHP script then in the PHP then in the jquery success function check what was returned in 'data' to see if it was succesful.
I generally return a Json encoded array with an element called 'result' that is either set to ture or false by the PHP and the jquery can simple act on that record.

how to use two $.post methods very well for give data from 2 different database

function ChangeGallery(){
var GalleryName = $('.SubSubGalleryLock').text();
/*Send string to Data1.php and include Tags from Database*/
$.post("Data1.php", { Sections: GalleryName },
function(data){
$(".IncludeData").append(data);
});
/*send string to Data2.php and include Events data from Database*/
$.post("Data2.php",{ GallerySec: GalleryName },
function(response){
/*when i use alert method, this function works very well, why?*/
alert('SomeString');
var data = jQuery.parseJSON(response);
var ImageID = data[0];
var ImageSrc = data[1];
$(ImageID).click(function(){
$(".LargeImage").attr('src', ImageSrc);
});
});
};
in Data1.php
/*give data from database1 and print to HTML File*/
if ($_POST['Sections']) == "String")
{ $results = mysql_query("SELECT * FROM Table1");
while($row = mysql_fetch_array($results))
{ echo $row['Tags']; }
in Data2.php
/*give data from database2 and Use for events*/
if ($_POST['GallerySec']) == "String")
{ $results = mysql_query("SELECT * FROM Table2");
while($row = mysql_fetch_array($results))
{ echo json_encode($row); }
in Client side when i use it then Data1.php works very well but Data2.php only when i write an
alert('Some stringh');
after
var data = jQuery.parseJSON(response);
line, it's work well, why? what's due to this problem?
I'm going to guess that you need the second .post() to be processed AFTER the first .post() and when you put the alert() in, that guarantees that it will go in that order, but without the alert(), it is a race condition and depends upon which .post() returns quicker.
There are a couple ways to fix the sequencing. The most straightforward is to start the second .post() from the success handler of the first so that you know the first has already completed.
You can also use jQuery promises or you could use your own flags to keep track of which has finished and call the last bit of code only when both have finished.
Here's how you would start the second .post() from the success handler of the first to guarantee the order:
function ChangeGallery(){
var GalleryName = $('.SubSubGalleryLock').text();
/*Send string to Data1.php and include Tags from Database*/
$.post("Data1.php", { Sections: GalleryName },
function(data){
$(".IncludeData").append(data);
/*send string to Data2.php and include Events data from Database*/
$.post("Data2.php",{ GallerySec: GalleryName },
function(response){
var data = jQuery.parseJSON(response);
var ImageID = data[0];
var ImageSrc = data[1];
$(ImageID).click(function(){
$(".LargeImage").attr('src', ImageSrc);
});
});
});
};

jQuery Array to PHP

I have a little bit of a problem, I have a JavaScript with jQuery where I work with an Array I got from PHP, in the script I add some data to two new arrays and here comes my problem, how can I work with those two arrays in my PHP file? I need to save the data from the two new arrays in a database. In the PHP I have a form where I enter some data about a User. Does someone knows a easy way to send my data back to the PHP?
Some information about the script: I have a table with the names of schools, and a checkbox with the id of the school as a value. when i check or uncheck one of the checkboxes the script checks if it is a school already saved in the database for this specific user or if it's a new user.
<script>
var schools = [];
var oldschools = [];
var uncheckedschools = [];
oldschools = <?php echo json_encode($oldschoolids); ?>;
$(".checkbox").change(function() {
if(this.checked) {
var additem = $(this).val();
for (var i=0; i<oldschools.length; i++) {
if (additem == oldschools[i]) {
uncheckedschools = jQuery.grep(uncheckedschools, function(value) {
return value != additem;
});
}
}
schools.push(additem);
} else {
var removeitem = $(this).val();
for (var i=0; i<oldschools.length; i++) {
if (removeitem == oldschools[i]) {
uncheckedschools.push(removeitem);
}
}
schools = jQuery.grep(schools, function(value) {
return value != removeitem;
});
}
});
</script>
I hope someone can help me with this problem!
You'll need to use AJAX to send your updates back to your server. Using jQuery's ajax() method, it would looks something like this:
$.ajax({
url: 'path/to/serverside/file.php',
dataType: 'json',
data: {schools: schools},
success: function(dataFromServer) {
//after the save is successful, you can do something here
},
error: function(dataFromServer) {
//if there was an error handle it here
}
});
EDIT: As mentioned by a few commentors, you'll need to use json_decode on the server-side to decode the JSON Object you're sending back: http://php.net/manual/en/function.json-decode.php

PHP: Unable to get the json output into my javascript page as a variable value [duplicate]

This question already has answers here:
php : how to pass database value into a javascript/jquery function
(3 answers)
Closed 9 years ago.
i have to get output in this format
var sampleTags = ['c++', 'scala'];
My javascript function is:
<script>
$(document).ready(function(){
$(function(){
var sampleTags;
$.ajax({
url:"<?php echo base_url('ajax_get_tags/gettags'); ?>"
}).done(function(data) {
if (data) {
sampleTags = data;
}
});
......................
.......................
$(function(){
var sampleTags = <?php echo json_encode($query) ?>;
My php controller is
function gettags(){
$json_array=$this->tagsmodel->get_all_tags();
echo json_encode($json_array);
}
My model is
//-------------------------------Function get all tags--------------------------------
function get_all_tags() {
$this->load->database();
$this->db->limit('10');
$this->db->select('tags_name');
$res = $this->db->get('tags');
$ret = array();
foreach ($res->result_array() as $row) {
$ret[] = $row['tags_name'];
}
return $ret;
}
How can get the json output from ajax request to be display its value for a javascript variable?
Please help me to solve this issue..
You're using an older version of jQuery, so .done won't work. It looks like you want to add a key to your request object called complete, with the anonymous function as its value:
$.ajax({
url: "<?php echo base_url('ajax_get_tags/gettags'); ?>",
complete: function(data) {
if (data) {
sampleTags = data;
}
}
});
I found this out by googling your error message. One of the results was this question: Object #<XMLHttpRequest> has no method 'done'. You could have just googled the error message and figured this out yourself.
I would like to give a few suggestions
Check for the return value form the server side by printing it with die or exit.
check the http response in firebug net tab.
3.

Ajax JSON Not Returning

I have the following code in my main page, trying to pull AJAX JSON.
It simply has to show 10 extra products on each page scroll. and at the moment it only shows the loader Circle div which should remove after loading - but nothing is loading.
var handler = null;
var page = 1;
var isLoading = false;
var apiURL = 'ajax/api.php'
function onScroll(event) {
// Only check when we're not still waiting for data.
if(!isLoading) {
// Check if we're within 100 pixels of the bottom edge of the broser window.
var closeToBottom = ($(window).scrollTop() + $(window).height() >
$(document).height() - 100);
if(closeToBottom) {
loadData();
}
}
};
function loadData() {
isLoading = true;
$('#loaderCircle').show();
$.ajax({
url: apiURL,
dataType: 'jsonp',
data: {page: page}, // Page parameter to make sure we load new data
success: onLoadData
});
};
// Receives data from the API, creates HTML for images
function onLoadData(data) {
isLoading = false;
$('#loaderCircle').hide();
// Increment page index for future calls.
page++;
// Create HTML for the images.
var html = '';
var i=0, length=data.length, image;
for(; i<length; i++) {
image = data[i];
html += '<li>';
// Image tag
html += '<img src="products/200/'+p_id+'.jpg" ">';
// Image title.
html += '<p>'+p_name+'</p>';
html += '</li>';
}
// Add image HTML to the page.
$('#tiles').append(html);
};
And my PHP JSON call
<?php require_once('../inc/config.php');
$page = $_REQUEST['page'];
$items = '10';
$start = (($page * $items) - $items);
$end = ($page * $items);
$result = mysql_query("SELECT p_id, p_name FROM products ORDER BY p_id ASC LIMIT $start, $end");
$products = array();
while($product = mysql_fetch_array($result, MYSQL_ASSOC)) {
$products[] = ($product);
}
$output = json_encode($products);
echo $output;
?>
The JSON that the php displays is as follows (example data):
[{"p_id":"1","p_name":"ASOS Pleated Swing Mac"},{"p_id":"2","p_name":"ASOS Midi Belted Coat"},{"p_id":"3","p_name":"ASOS Zig Zag Coat"},{"p_id":"4","p_name":"Collarless Quilted Leather Biker with Ribbed Sleeve"},{"p_id":"6","p_name":"TFNC Dress with Wrap Front in Flocked Heart"},{"p_id":"7","p_name":"Striped Skater Dress"},
{"p_id":"8","p_name":"Metallic Wrap Dress"},{"p_id":"9","p_name":"Strapless Dress With Neon Belt"},{"p_id":"10","p_name":"Darling Floral Border Print Dress"},{"p_id":"11","p_name":"Dip Hem Chiffon Dress With Printed Top"}]
So overall it doesnt load the data into the html. Can someone please explain what I might have to do or what I might be doing wrong. (this is using the wookmark plugin - but shouldnt affect anything)
The problem is that you've set the jQuery AJAX dataType to jsonp, but your api.php is outputting JSON, not JSONP.
To solve this, either change the dataType to json:
$.ajax({
url: apiURL,
dataType: 'json',
data: {page: page}, // Page parameter to make sure we load new data
success: onLoadData
});
Or change your api.php file to output JSONP data:
$json = json_encode($products);
$output = isset($_GET['callback']) ? "{$_GET['callback']}($json)" : $json;

Categories