Load Json data with AJAX and PHP - javascript

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

Related

AJAX response returns html content

I have an AJAX call in my codeigniter project. Here is my code:
in view :
$('#forgotPassword').click(function() {
var base_url = '<?php echo base_url()?>';
$('#forgotPasswordEmailError').text('');
var email = $('#forgotPasswordEmail').val();
console.log(email);
if(email == ''){
$('#forgotPasswordEmailError').text('Email is required');
}else{
$.ajax({
url : base_url + 'Home/forgotPassword',
type : 'POST',
data : {email : email},
success: function(data) {
console.log(data);
//location.reload();
}
});
}
});
and controller :
public function forgotPassword() {
$email = $this->input->post('email');
echo $email;
}
but the response contains only the html content from my view. I couldn't identify what is happening.
change your jquery code to
$('#forgotPassword').click(function() {
var base_url = '<?php echo base_url()?>';
$('#forgotPasswordEmailError').text('');
var email = $('#forgotPasswordEmail').val();
console.log(email);
if(email == ''){
$('#forgotPasswordEmailError').text('Email is required');
}else{
$.ajax({
url : base_url + 'Home/forgotPassword',
type : 'POST',
data : {email : email},
dataType:'json',
success: function(data) {
console.log(data);
//location.reload();
}
});
}
});
change your controller code like
public function forgotPassword() {
$email = $this->input->post('email');
$response = ["email" => $email];
echo json_encode($response);
}
Instead of
echo $email;
use:
$response = ["email" => $email];
return json_encode($response);
And parse JSON, on client side, using JSON.parse.
hi maybe i can help someone, i had the same problem, in my case the error was here "url : base_url + 'Home/forgotPassword'"
in this example i have to pass all way like this url : /anotherdirectory/Home/forgotPassword.php',
take a look in your "url"
$.ajax({
url : "change here fo works"',
type : 'POST',
data : {email : email},
dataType:'json',
success: function(data) {
console.log(data);
//location.reload();
}

Can't figure why Ajax return error even when I return json

So I've seen the question asked multiple time and a lot of answers about it but none resolve my own problem and I realy don't understand where this could come from.
How come I'm returning a json content with my controller but still access the error part of my Ajax request?
This is my Ajax :
$.ajax({
url: '../ajax/addArticle',
type: 'POST',
data : {
title : $('#title').val(),
content : CKEDITOR.instances.editor.getData(),
},
dataType: 'json',
success: function (data){
console.log(data);
if(data == "Posted"){
alert('Article posté');
window.location = "/blog";
}
},
error: function(e) {
console.log(e);
}
});
And my controller return this :
$data = ['data' => 'Posted'];
header('Content-Type: application/json');
$data = json_encode($data);
return $data;
However this is the output :
You should do this on the server:
echo json_encode($data);
// $data = json_encode($data);
// return $data;
The server doesn't echo anything at the moment, so that's why the request fails, since you have a dataType: 'json' ajax that doesn't get a JSON response from the server.
Ajax returns are responses from the server interpreted as text (or HTML) output
Your code should be :
$data = ['data' => 'Posted'];
header('Content-Type: application/json');
$data = json_encode($data);
echo $data;

Switching from GET to POST

I have the following Ajax request:
// JavaScript
function myFunc(pid) {
$.ajax({
type : "GET",
url : "testback.php",
contentType : "application/json; charset=utf-8",
dataType : "json",
data : {
q : "testrequest",
pid : pid
},
success : function(data) {
console.log(data)
},
error : function(jqXHR, status, error) {
console.log(status, error);
}
});
}
// PHP
require_once ("dbconnect.php");
if (isset ( $_GET ['q'] )) {
if ($_GET ['q'] == "testrequest") {
$pid = $_GET ['pid'];
$query = "SELECT * FROM `tab1` WHERE `pid` = " . $pid;
$json = array ();
if ($result = $link->query ( $query )) {
while ( $row = $result->fetch_assoc () ) {
array_push ( $json, $row );
}
}
header ( "Content-type: application/json; charset=utf-8" );
die ( json_encode ( $json ) );
exit ();
}
die ();
}
It sends a request to my MySQL database and returns the expected output.
However, I now want to switch to POST, rather than GET.
When I just swap GET with POST:
// JavaScript
function myFunc(pid) {
$.ajax({
type : "POST", // POST
url : "testback.php",
contentType : "application/json; charset=utf-8",
dataType : "json",
data : {
q : "testrequest",
pid : pid
},
success : function(data) {
console.log(data)
},
error : function(jqXHR, status, error) {
console.log(status, error);
}
});
}
// PHP
require_once ("dbconnect.php");
if (isset ( $_POST ['q'] )) { // POST
if ($_POST ['q'] == "testrequest") { // POST
$pid = $_POST ['pid']; // POST
$query = "SELECT * FROM `tab1` WHERE `pid` = " . $pid;
$json = array ();
if ($result = $link->query ( $query )) {
while ( $row = $result->fetch_assoc () ) {
array_push ( $json, $row );
}
}
header ( "Content-type: application/json; charset=utf-8" );
die ( json_encode ( $json ) );
exit ();
}
die ();
}
I get the following error in the console:
parsererror SyntaxError: Unexpected end of JSON input
The request payload is still q=testrequest&pid=1.
What else do I need to change, in order to switch from GET to POST?
In your Ajax function you need to omit the content type as it is already defined in the Ajax Call. Delete the line "contentType : "application/json; charset=utf-8" shown below:
$.ajax({
type : "GET", // Or POST
url : "testback.php",
contentType : "application/json; charset=utf-8", // REMOVE THIS LINE!!
dataType : "json",
data : {
q : "testrequest",
pid : pid
},
success : function(data) {
console.log(data)
},
error : function(jqXHR, status, error) {
console.log(status, error);
}
});
It should work just fine after that!
Cheers!
The $.ajax works but i advise to use $.get or $.post instead.
Be carrefull about your url when you use $.get, browsers have caracter limits (around 2000 caracters).
if (urlGet.length < 2000) {
// GET less than 2000 caractères use $.GET
$.get(urlGet, function () {
}).done(function (data) {
//OK do stuff with data returned
}).fail(function () {
//err
});
} else {
//Use $.POST params : { name: "John", age: "25" }
$.post(urlPost, { name: "John", age: "25" }, function () {
}).done(function () {
//ok
}).fail(function () {
//fail
});
}
You can create a function with this code and then have a simple call of your WebServices.
Here is the jQuery doucmentation :
$.GET https://api.jquery.com/jquery.get/
$.POST https://api.jquery.com/jquery.post/
Hope this help ;)

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

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