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!
Related
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);
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) {
}
});
i have an array , which has to be passed from backend to frontend using ajax, i am new to ajax i know the syntax but got stuck , below is my code
backend(PHP)
$s_q = "SELECT `ans` FROM `bec_log_response` WHERE session_id=1 AND paper_id=2";
$s_res = mysql_query($s_q, $db2);
while($row= mysql_fetch_array($s_res))
{
echo $row['ans'];
}
$result = array('ans' => $row['ans'] );
Javascript code
function get_solution()
{
$.ajax({
url: 'waiting.php',
dataType: 'json',
type: 'GET',
timeout: 30 * 1000,
data: {sol:row},
success: function(json){
$('#saved').html(json.ans);
},
error: function(){}
});
}
i am getting an error in this code data: {sol:row}.
The response data from php is not in json format..
$result = array('ans' => $row['ans'] );
echo json_encode($result);
add this in your php code
Create a JSON on the PHP Side and catch it with $.getJSON jquery
Server Side:
$row_1 = array();
$s_q = "SELECT `ans` FROM `bec_log_response` WHERE session_id=1 AND paper_id=2";
$result = mysql_query($s_q) or die (mysql_error());
while($r = mysql_fetch_assoc($result)) {
$row_1[] = $r;
}
$post_data = json_encode(array('ans' => $row_1));
echo $post_data;
Client Side:
$.getJSON("result.php", function(json) {
console.log(json)
$.each( json, function( key, data ) {
//loop through the json if necessary
});
});
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();
}
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);
}
}