double json response - javascript

I don't know why this double json response are not successful:
[{"first_content":"content",...}][{"second_content":"content",...}]
So i am getting the message Oops! Try Again.
if(isset($_GET['start'])) {
echo get_posts($db, $_GET['start'], $_GET['desiredPosts']);
echo get_posts1($db, $_GET['start'], $_GET['desiredPosts']);
$_SESSION['posts_start']+= $_GET['desiredPosts'];
die();
}
var start = <?php echo $_SESSION['posts_start']; ?>;
var desiredPosts = <?php echo $number_of_posts; ?>;
var loadMore = $('#load-more');
loadMore.click(function () {
loadMore.addClass('activate').text('Loading...');
$.ajax({
url: 'profile.php',
data: {
'start': start,
'desiredPosts': desiredPosts
},
type: 'get',
dataType: 'json',
cache: false,
success: function (responseJSON, responseJSON1) {
alert(responseJSON);
loadMore.text('Load More');
start += desiredPosts;
postHandler(responseJSON, responseJSON1);
},
error: function () {
loadMore.text('Oops! Try Again.');
},
complete: function () {
loadMore.removeClass('activate');
}
});
});
What is the solution to get a double json response ? With one there is no problem

"Double JSON response" as you call them is basically invalid JSON. You should have something like so:
{"first_content":"content", "second_content":"content",...}
Or as a couple of people mentioned:
[{"first_content":"content",...}, {"second_content":"content",...}]
You probably need to modify some server side code, your get_posts function could return a PHP array instead of a JSON array. Example:
function get_posts(){
$array = array('content' => 'foo', 'title' => 'bar');
return $array;
}
Then in your profile.php:
if(isset($_GET['start'])) {
$posts = get_posts($db, $_GET['start'], $_GET['desiredPosts']);
$posts1 = get_posts1($db, $_GET['start'], $_GET['desiredPosts']);
echo array($posts, $posts1);
$_SESSION['posts_start']+= $_GET['desiredPosts'];
die();
}

Related

AJAX returns error with empty responseText

I'm trying to get some data trough AJAX but am getting an error with an empty responseText.
My code is as follows:
JS:
function getFounder(id) {
var founder = "";
$.ajax({
url: '/data/founder_info.php',
data: {founder: id},
dataType: 'json',
async: false,
type: 'post',
success: function(json) {
//founder = json.username;
console.log(json);
},
error: function(ts) {
console.log("Error: " + ts.responseText);
}
});
return founder;
}
PHP:
<?php
require_once '../core/init.php';
if($_POST['founder']) {
$u = new User();
$user_info = $u->find(escape($_POST['founder']));
$user_info = $u->data();
echo json_encode($user_info);
exit();
}
I cannot find the issue as to why it is throwing the error.
I fixed it using a method to convert everything to UTF-8.
function utf8ize($d) {
if (is_array($d))
foreach ($d as $k => $v)
$d[$k] = utf8ize($v);
else if(is_object($d))
foreach ($d as $k => $v)
$d->$k = utf8ize($v);
else
return utf8_encode($d);
return $d;
}
This was posted as an answer to this question
My problem is now solved!

How to use jQuery to get variable from PHP

I am trying to get data from MySQL using ajax and jQuery. Right now, the only thing being returned is "0". Here is my PHP function:
function dallas_db_facebook_make_post () {
global $wpdb;
$query = "SELECT * FROM wp_dallas_facebook WHERE time > NOW() ORDER BY time LIMIT 1";
$results = $wpdb->get_results($query, ARRAY_A);
foreach($results as $result) {
$fbpost = $result['text'];
}
}
Here is my jQuery function:
function send_fb_post() {
jQuery.ajax({
type: "GET",
url: my_ajax.ajaxurl,
data: {
'action': 'dallas_db_facebook_make_post'
},
beforeSend: function() {
},
success: function(data){
console.log(data);
},
error: function(){
},
});
};
You are not getting anything, because you are not printing/echoing anything.
What happens if you try
foreach($results as $result) {
echo $fbpost = $result['text'];
}
You code is not working because you are not print anything on server side. so you can small change in your code like below.
jsonencode is use to return an array of data.
function dallas_db_facebook_make_post () {
global $wpdb;
$query = "SELECT * FROM wp_dallas_facebook WHERE time > NOW() ORDER BY time LIMIT 1";
$results = $wpdb->get_results($query, ARRAY_A);
$fbpost = array();
foreach($results as $result) {
$fbpost = $result['text'];
}
echo json_encode($fbpost);
exit;
}
in response you json_encodeed data. You can decode and use this data using below function in response callback.
function send_fb_post() {
jQuery.ajax({
type: "GET",
url: my_ajax.ajaxurl,
data: {
'action': 'dallas_db_facebook_make_post'
},
beforeSend: function() {
},
success: function(data){
console.log(jQuery.parseJSON( data ));
},
error: function(){
},
});
};

Get Success Results From AJAX call

I am trying to get the results from an AJAX call, but I keep getting the error results of the function and I have no idea why.
Here is the javascript:
var curfrndurl = "http://www.website.com/app/curfrnd.php?frndid=" + secondLevelLocation + "&userid=" + items;
$("#loadpage1").click(function(event){
event.preventDefault();
$.ajax({
url: curfrndurl,
dataType: 'json',
type: "GET",
success: function (data){
if (data.success) {
alert("Hi");
$("#curstatus").html(data);
$("#curstatus2").hide();
$("#subtform").hide();
}
else
{
alert("Bye");
$("#curstatus2").html(data);
$("#curstatus").hide();
$("#addform").hide();
}
},
error: function() {
alert('Doh!');
}
});
});
The PHP file is:
<?php
$userdbme = $_GET['userid'];
$frndid = $_GET['frndid'];
$query2 = mysql_query("SELECT * FROM follow WHERE yoozer1='$userdbme' AND yoozer2='$frndid' ORDER BY followid DESC LIMIT 0,1");
$numfriends = mysql_num_rows($query2);
if ($numfriends!=0)
{
echo json_encode(array(
'success' => true
//'user_name' => $userdb
));
echo "<h4>Current Friends</h4>";
}
else {
echo json_encode(array('success' => false));
echo "<h4>Not Friends</h4>";
}
?>
Any help would be greatly appreciated! Thanks!
If you want to echo JSON data, then you need to make sure you don't echo anything else before or after the data.
echo json_encode(array(
'success' => true
));
echo "<h4>Current Friends</h4>";
This is not parsable as JSON, because of the "extra" stuff after the JSON data. Try this:
echo json_encode(array(
'success' => true,
'html' => "<h4>Current Friends</h4>"
));
Then you can do: $("#curstatus").html(data.html);

How to return success in a ajax call

I have an ajax call to delete a page from my database, but I'm not quite sure how to return success and use it:
My ajax call looks like this:
$('.delete_button').click(function() {
$.ajax({
url: 'delete_page.php',
dataType: 'json',
async: false,
type: 'post',
data: {
page_id: id
},
succes:function() {
alert('something');
if (s.Err == false) {
window.location.reload(true);
}
}, error:function(e){
}
});
});
And in my delete_page.php I have this:
<?php
require 'core/init.php';
$id = $_POST['page_id'];
$page_id = $id[0];
$delete_page = DB::getInstance()->delete('pages', array('id', '=', $page_id));
if ($delete_page) {
$output['Err'] = false;
} else {
$output['Err'] = true;
}
return json_encode($output);
It does delete the page, but it doesn't run the if statement and it is not alerting anything. How do I fix this?
Dont use return, actually output the data, with the correct header:
//return json_encode($output);
header('Content-Type: application/json');
echo json_encode($output);
In your PHP script, you need to output the data instead of returning it:
header('Content-Type: application/json');
echo json_encode($output);
Then in your javascript file you need to retrieve the data:
success: function (data) { // It's success not succes, and you need the parameter
alert('something');
if (data.Err == false) {
window.location.reload(true);
}
}
If that's the entire delete_page.php, it needs to echo the output, not just return it.
Here's a slightly more elegant way of handling this.
Update your delete_page.php script like this:
<?php
require 'core/init.php';
$id = $_POST['page_id'];
$page_id = $id[0];
// Init
$output = array(
'IsDeleted' = false,
'LastError' = ''
);
// Delete
try {
$output['IsDeleted'] = DB::getInstance()
->delete('pages', array('id', '=', $page_id));
}
catch (Exception $ex) {
$output['LastError'] = $ex->getMessage();
}
// Finished
echo json_encode($output);
?>
Then update your ajax code like this:
$.ajax({
url: 'delete_page.php',
dataType: 'json',
async: false,
type: 'post',
data: {
page_id: id
},
dataType: 'json',
succes: function(result) {
if (result.IsDeleted) {
window.location.reload(true);
} else {
alert('Failed to delete. Last error: ' + result.LastError)
}
},
error:function(e) {
}
});

JSON ajax and jquery, cannot get to work?

I have the following script in my javascript...
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
data: {email: val},
success: function(response) {
alert(response);
}
});
And my php file looks like this...
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
}
else {
echo json_encode(error = true);
}
}
I cannot get either the variable error of true or false out of the ajax call?
Does it matter how I put the data into the ajax call?
At the minute it is as above, where email is the name of the request, and val is a javascript variable of user input in a form.
Try this instead. Your current code should give you a syntax error.
if (!$q -> rowCount()) {
echo json_encode(array('error' => false));
}
else {
echo json_encode(array( 'error' => true ))
}
In your code, the return parameter is json
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
dataType: 'json',
data: {email: val},
success: function(response) {
alert(response);
}
});
PHP FILES
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
return json_encode(error = false);
} else {
echo json_encode(error = true);
return json_encode(error = true);
}
}

Categories

Resources