Get Success Results From AJAX call - javascript

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

Related

Ajax response isn't showed on page

My ajax is
$.ajax({
type: 'POST',
url: ajax.ajax,
contentType: false,
processData: false,
dataType: 'JSON',
status: 200,
data: formdata,
success: function(msg){
$('#success_message').fadeIn().html(data);
setTimeout(function() {
$('#success_message').fadeOut("slow");
}, 2000 );
}
});
This is the PHP part
function form(){
global $wpdb;
$table = cars;
foreach ($_FILES as $file) {
if($file['error'] == UPLOAD_ERR_NO_FILE) {
continue;
}
$valid_ext = array( 'img' , 'png');
$extension_upload = strtolower( substr( strrchr($file['name'], '.') ,1) );
if ( in_array($extension_upload,$valid_ext) ) {
$name_upload = uniqid() . $file['name'];
$url_insert = trailingslashit( plugin_dir_path( dirname( __FILE__ ) ) ) . 'uploads';
wp_mkdir_p($url_insert);
$name_insert = trailingslashit($url_insert) . $name_upload;
$action = move_uploaded_file($file['tmp_name'],$name_insert);
$data = array( 'customer_resume' => $name_upload );
$format = array( '%s' );
$success=$wpdb->insert( $table, $data, $format );
$msg_true = 'Upload ok ';
} else {
$msg_error = 'Upload error';
}
}
$result = !isset($msg_error);
$msg = array();
if($result) {
$msg['error'] = 'true';
$msg['true'] = $msg_true;
} else {
$msg['error'] = 'false';
$msg['false'] = $msg_error;
}
header('Content-Type: application/json');
echo json_encode($msg);
}
And the HTML where I try to show the success or error message
<div id="error_message"></div>
<div id="success_message"></div>
When I click on Submit button I everything works fine and saved in database but there is no indication wheather is success or no. I've tried to add this msg's but still nothing shows on page.
PHP side:
You need to print same variable for success and failure:
if($result) {
$msg['error'] = 'true';
$msg['msg'] = $msg_true;
} else {
$msg['error'] = 'false';
$msg['msg'] = $msg_error;
}
JavaScript Side:
The AJAX response will come as
data.error -> true or false.
data.msg -> Success or Error message depending upon program logic.
...
success: function(data){
$('#success_message').fadeIn().html(data.msg);
...
What is hiding behind "ajax.ajax" ?
Also if you want to show your data you need to use "msg"
success: function(msg){
$('#success_message').fadeIn().html(msg);
setTimeout(function() {
$('#success_message').fadeOut("slow");
}, 2000 );
}

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!

Load Json data with AJAX and PHP

I'm triing to load a json data with ajax, but it doesn't work. Everytime ajax call the error function and doesn't call the success function.
my AJAX call :
$(document).on("click", "#myMovies .btn-update", function() {
var id = $(this).parent().data("id");
$.ajax({
url : 'index.php',
type : 'POST',
dataType: 'json',
data : 'id=' + id + '&action=update',
success : function(data){
$('#updateMovie')
.find('[name="title"]').val(data.title).end()
.find('[name="list"]').val(data.list).end();
},
error : function(jqXHR, textStatus, errorThrown){
console.log("error");
alert(textStatus);
alert(errorThrown);
}
});
});
The interessing part of index.php :
else if($_POST['action'] == "update") {
/*getSpecificMovie($_POST['id']);
$movies = getSpecificMovie();
$results = Utils::secureMoviesJSON($movies);
echo $results;*/
header("Content-Type: application/json", true);
$array = array(
'title' => 'test',
'list' => 'test');
echo json_encode( $array, JSON_FORCE_OBJECT );
}
Anyone know where is my mistake ?
Thank you for your answer.
I think the problem is at the 'JSON_FORCE_OBJECT' option. The data type the request expected is a json string. When adding JSON_FORCE_OBJECT to the json_encode function, the json string is not valid for the request.
else if($_POST['action'] == "update") {
/*getSpecificMovie($_POST['id']);
$movies = getSpecificMovie();
$results = Utils::secureMoviesJSON($movies);
echo $results;*/
header("Content-Type: application/json", true);
$array = array(
'title' => 'test',
'list' => 'test');
echo json_encode( $array);
die();
}
Also add a parser for the json to your javascript (parseJSON):
success : function(data){
data = $.parseJSON(data);
$('#updateMovie')
.find('[name="title"]').val(data.title).end()
.find('[name="list"]').val(data.list).end();
},

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

double json response

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

Categories

Resources