I'm facing a strange problem for the last 10 hours and its really very annoying. The problem is with jquery printing json data from php. The php script is running fine, but when the ajax call returns in complete: event i'm not getting any valid otput.
here is the jquery code::
list_choice = "A";
content_choice = "Artists"; //globals to store default value
$(document).ready(function() {
$('.list-nav > a').click(function() {
var ltext = $(this).text();
list_choice = ltext;
console.log(ltext+" <------> ");
$.ajax({
url: 'retrieveFileFront.php',
data: {type: content_choice, navtext: list_choice},
type: 'POST',
dataType: 'json',
complete: function(data) {
console.log(data['message']['Album_Name']);
}
});
return false;
});
});
i had to use complete: event as success: didn't worked at all. Atleast i'm getting some sort of output from the complete: event, although its giving undefined or [object][Object] which is totally ridiculous.
here is the retrieveFileFront.php:
<?php
require './retrieveFiles.php';
$type = $_POST['type'];
$nav_text = $_POST['navtext'];
$ret_files = new retrieveFiles($type, $nav_text);
$data = $ret_files->retFiles();
if ($data['success'] == FALSE) {
$data = array('success' => FALSE, 'message' => 'Sorry an Error has occured');
echo json_encode($data);
} else {
echo json_encode($data);
}
?>
and here is the /retrieveFiles.php
<?php
class retrieveFiles {
public $content_type;
public $list_nav;
public $connection;
public $result;
public $result_obj;
public $tags_array;
public $query;
public $row;
public function __construct($type, $nav_text) {
$this->content_type = $type;
$this->list_nav = $nav_text;
}
public function retFiles() {
#$this->connection = new mysqli('localhost', 'usr', 'pass', 'data');
if(!$this->connection) {
die("Sorry Database connection could not be made please try again later. Sorry for the inconvenience..");
}
if ($this->content_type == "Artists") {
$this->query = "SELECT album_name, album_art FROM album_dummy NATURAL JOIN album_images_dummy WHERE artist_name LIKE '$this->list_nav%'";
try {
$this->result = $this->connection->query($this->query);
$this->row = $this->result->fetch_row();
if (isset($this->row[0]) && isset($this->row[1])) {
$this->tags_array = array("success" => true, "message" => array("Album_Name" => $this->row[0], "Album_Art" => $this->row[1]));
return $this->tags_array;
}
} catch (Exception $e) {
echo 'Sorry an Error has occurred'.$e;
return false;
}
}
}
}
?>
I'm getting a 200 response in console in firebug, which indicates that its running okay.
<!DOCTYPE HTML>
{"success":true,"message":{"Album_Name":"Streetcleaner","Album_Art":"\/var\/www\/html\/MusicLibrary\/Musics\/1989 - Streetcleaner\/folder.jpg"}}
Now this is making me even more confused as i can see that the json is formatted properly. Please provide any sort of suggestion on how to solve this problem.
Thanks in advance..
JSON encoded data is usually not sent like
data['message']['Album_Name']);
But rather like:
data.message.Album_Name;
You're calling your results the wrong way. These are not associative arrays anymore but are now objects, as the name JSON (JavaScript Object Notation) suggests.
You need to parse the json response using
data = $.parseJSON(data)
Use success event instead of complete in ajax and we can able to parse JSON encoded data in javascript/jQuery by using JSON.parse
well after a long period of trauma, i finally found a solution, turns out that i needed to parse the response text and then access the objects, individually.
Here is the working code
list_choice = "A";
content_choice = "Artists"; //globals to store default value
$(document).ready(function() {
$('.list-nav > a').click(function() {
var ltext = $(this).text();
list_choice = ltext;
console.log(ltext+" <------> ");
$('#loading').css('visibility', 'visible');
$.ajax({
url: 'retrieveFileFront.php',
data: {type: content_choice, navtext: list_choice},
type: 'POST'
dataType: 'json',
complete: function(data) {
var res = data.responseText;
res = res.replace(/<!DOCTYPE HTML>/g, "");
res = res.trim();
console.log(res);
var arr = JSON.parse("[" + res +"]"); //needed to parse JSON object into arrays
console.log(arr[0].message.Album_Name);
console.log(arr[0].message.Album_Art);
$('#loading').css('visibility','hidden');
}
});
return false;
});
This works fine and gives the desired response. Anyways thanks for the help, guys.
Related
I'm making a phone app using PhoneGap with PHP on the server side. the Login function has been working fine, but AJAX returns an error [object Object] while PHP returns the correct value's in JSON.
it's for making a phone app for an existing website and using its database.
the data my PHP prints is correct yet I receive an error response from ajax.
Alert(response)
Gives an [object Object] return value on error
whenever I try
alert(response.val)
I strangely get undefined, but in the network, I can see the printed data is correct in JSON.
{{"user_id":"390","response":"Success"}}
but when I look in the console on my browser I see an unexpected error.
Unexpected parameter ':'
my ajax function is as follows
$(document).ready(function () {
$("#btnLogin").click(function () {
var gebr = $("#login_username").val().trim();
var pass = $("#login_password").val().trim();
var dataString = "username=" + gebr + "&password=" + pass + "&login=";
var msg = "";
$("#message").html("Authenticating...");
if (gebr != "" && pass != "") {
$.ajax({
type: "POST",
data: dataString,
dataType: "json",
//contentType: "application/javascript",
crossDomain: true,
url: "http://url/page/app/index.php?&jsoncallback=?",
headers: "application/json",
success: function (response) {
var user_id = response.user_id;
var success = response.response;
localStorage.setItem("user_id", user_id);
window.location = "home.html";
alert("login successfull");
},
error: function (response) {
$("#message").html("error..");
alert(response);
}
});
} else {
msg = "Please fill all fields!";
$("#message").html(msg);
}
return false;
});
PHP
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
$gebruikersnaam = $_REQUEST['username'];
$wachtwoord = md5($_REQUEST['password']);
$user = [];
//if user and password are filled
if (!empty($gebruikersnaam) && isset($wachtwoord)) {
//checks if user_id has been found
if (!$found_user_id) {
$msg = "user not found!";
print json_encode($msg);
} else {
if (($gebruikersnaam == $user['gebruikersnaam'] && $wachtwoord == $user['wachtwoord']) && ((!empty($user['single_allowed_ip_address_for_login']) && $user['single_allowed_ip_address_for_login'] == $_SERVER['REMOTE_ADDR'])|| empty($user['single_allowed_ip_address_for_login']))) {
//responds with this data
$user_id = $user['user_id'];
$response[] = array(
'user_id' => $user_id,
'response' => 'Success'
);
print json_encode($response);
} else {
$msg = "user is incorrect";
print json_encode($msg);
}
}
}
I have been wanting to get a successful response and saving the user_id in local storage so it can be used on a different page.
Edit:
after using console.log on the response i got an odd object.
abort: function abort()
always: function always()
catch: function catch()
done: function add()
fail: function add()
getAllResponseHeaders: function getAllResponseHeaders()
getResponseHeader: function getResponseHeader()
overrideMimeType: function overrideMimeType()
pipe: function pipe()
progress: function add()
promise: function promise()
readyState: 4
setRequestHeader: function setRequestHeader()
state: function state()
status: 200
statusCode: function statusCode()
statusText: "load"
then: function then()
<prototype>: {…
which is strange because none of these functions are made and the only thing which i can recognize is the statuscode.
You need to correct your JSON. {{"user_id":"390","response":"Success"}} is not valid JSON. It needs to be {"user_id":"390","response":"Success"}.
You're getting a strange object in your console.log because your response in the error: function (response)... is actually the jqXHR jQuery object and will not return your response directly in its arguments. Stick with success: function(response)... and output whatever your server sends back.
I have tried different ways to make this work but it is still not working. data[0].urgency is undefined. I tried to stringify data but a bunch of \n in between the result (see below).
Thank you in advance.
My ajax code:
function ajaxCall() {
$.ajax({
type: "POST",
url: "../nav/post_receiver.php",
success: function(data) {
console.log(data.length);
console.log(data[0].urgency);
}
});
}
My PHP code:
<?php
session_start();
ob_start();
require_once('../../mysqlConnector/mysql_connect.php');
$results = array();
$query="SELECT COUNT(initID) AS count, urgency, crime, initID, TIMESTAMPDIFF( minute,dateanalyzed,NOW()) AS minuteDiff FROM initialanalysis WHERE commanderR='0' AND stationID='{$_SESSION['stationID']}';";
$result=mysqli_query($dbc,$query);
while ($row = $result->fetch_assoc()){
$count = $row['count'];
$urgency = $row['urgency'];
$crime = $row['crime'];
$initID = $row['initID'];
$minuteDiff = $row['minuteDiff'];
$results[] = array("count" => $count, "urgency" => $urgency, "crime" => $crime, "initID" => $initID, "minuteDiff" => $minuteDiff);
}
echo json_encode($results);
?>
Result of PHP:
[{"count":"9","urgency":"Low","crime":"Firearm","initID":"6","minuteDiff":"4743"}]
I think the result is in wrong format? I'm not sure.
This is the result of console.log(data), there is a comment tag of html and I don't know why:
<!-- -->
[{"count":"9","urgency":"Low","crime":"Firearm","initID":"6","minuteDiff":"4761"}]
Use a JSON parser for validate the json response like JSON.parse
function ValidateJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
Update your ajax call like this
function ajaxCall() {
$.ajax({
type: "POST",
url: "../nav/post_receiver.php",
success: function(data) {
data= jQuery.parseJSON(data);
console.log(data.length);
console.log(data[0].urgency);
}
});
}
I'm using CakePHP framework. My problem is that when I print a php function then it gives me an array with a lot of members but when using the same function with Ajax then the response is empty.
Ajax response function:
public function functionOne(){
$this->autoRender = false;
if ($this->request->is('ajax')) {
if(!$this->request->data['amount']) {
$json['errors'][] = 'Fill in all the required fields';
}elseif(!is_numeric($this->request->data['amount'])){
$json['errors'][] = 'Field amound has to be a number';
}
if(!$this->request->data['currency_from']){
$json['errors'][] = 'Fill in all the required fields';
}
if(!$this->request->data['currency_to']){
$json['errors'][] = 'Fill in all the required fields';
}
if(!$this->request->data['rate_date']){
$json['errors'][] = 'Fill in all the required fields';
}
if(isset($json['errors'])){
$json['status'] = 'error';
}else{
$json['status'] = 'success';
$json['curs'] = $this->functionTwo($this->request->data['date1']);
$json['rates'] = $this->functionThree($this->request->data['date'], $this->request->data['from'], $this->request->data['to'], $this->request->data['amount']);
}
print_r(json_encode($json));
}
}
View file ajax request:
$(document).ready(function(){
$('#converter').on('submit', function(e) {
var form = $(this);
e.preventDefault();
$.ajax({
url: '<?php echo $this->Html->url(array(
"controller" => "cur",
"action" => "functionOne"
));
?>',
data: form.serialize(),
type: 'post',
async: true,
success: function (data) {
var json = data;
if (json.status == 'error') {
$('#errors').show();
$('#currencies').hide();
$('#errors').html('');
$.each(json.errors, function (k, v) {
$('#errors').append("<span>" + v + "</span>");
});
}
if (json.status == 'success') {
var json = data;
$('#errors').hide();
$('#currencies').show();
}
}
});
})
});
getCur method returns an array in format "code" => "name". It gets the currencies from reading different sources XML files. When I print the function outside of the response it gives me a correct result but with ajax it just gives me an empty array.
Errors are coming through the response though.
Thanks!
What version of Cake are you using??
Depends on the version of cake.
1.3.x:
$this->RequestHandler->isAjax();
2.x
$this->request->is('ajax');
Also can you check your chrome network tab for any specific issue.
Try to :
echo your json like echo json_encode($json);
In success callback, parse data variable by using :
success : function(data){
var json = $.parseJSON(data);
console.log(json);
}
See the data inside console.
Mistake was that I created the instances inside the method so ajax thought that I did not have any.
Thanks for replying!
I'm new to jQuery, and have not been able to debug this ajax call in Firebug:
This is my ajax call:
var styndx = $('#studylist option:selected').val();
var studyname = $('#edit_field').val();
$.post("saveStudyName.php", {'type': 'update', 'studyname':studyname, 'styndx':styndx},
function(resultmsg) {
$('#edit_field').val('');
$('#savebtn').attr('disabled',true);
refresh_studynames();
});
And this is the function refresh_studynames:
function refresh_studynames()
{
$.ajax({
url: 'getStudyNames.php',
data: "",
dataType: 'json',
error: function() {
alert('Refresh of study names failed.');
},
success: function(data)
{
$data.each(data, function(val, sname) {
$('#studylist').append( $('<option></option>').val(val).html(sname) )
});
}
});
}
Finally, this is the php script getStudyNames.php ($dbname,$dbconnect, $hostname are all populated, and $dbconnect works; the backend database is Postgres, and pg_fetch_all is a Postgres function in PHP that returns result as an array):
$dbconnect = pg_pconnect("host=".$hostname." user=".$dbuser." dbname=".$dbname);
if (!$dbconnect) {
showerror(0,"Failed to connect to database",'saveStudyName',30,"username=".$dbuser.", dbname=".$dbname);
exit;
}
$sql = "SELECT ST.studyindex,ST.studyabrv AS studyname
FROM ibg_studies ST
ORDER BY studyname";
$fetchresult = pg_exec($dbconnect, $sql);
if ($fetchresult) {
$array = pg_fetch_all($fetchresult);
echo json_encode($array);
} else {
$msg = "Failure! SQL="+$sql;
echo $msg;
}
Any help much appreciated....
The line
$('#studylist').append( $('<option></option>').val(val).html(sname) );
looks wrong.
I'm not too sure but you could try :
var $studylist = $('#studylist').empty();
$data.each(data, function(i, record) {
$studylist.append( $('<option/>').html(record.sname) );
});
I am using Codeigniter and trying to use the jQuery autocomplete with it. I am also using #Phil Sturgeon client rest library for Codeigniter because I am getting the autocomplete data from netflix. I am return correct JSON and I can access the first element with
response(data.autocomplete.autocomplete_item[0].title.short);
but when I loop through the results
for (var i in data.autocomplete.autocomplete_item) {
response(data.autocomplete.autocomplete_item[i].title.short)
}
it acts like a string. Lets say the result is "Swingers", it will return:
Object.value = s
Object.value = w
Object.value = i
and so on.
the js:
$("#movies").autocomplete({
source: function(request, response) {
$.ajax({
url: "<?php echo site_url();?>/welcome/search",
dataType: "JSON",
type:"POST",
data: {
q: request.term
},
success: function(data) {
for (var i in data.autocomplete.autocomplete_item) {
response(data.autocomplete.autocomplete_item[i].title.short);
}
}
});
}
}).data("autocomplete")._renderItem = function(ul, item) {
//console.log(item);
$(ul).attr('id', 'search-autocomplete');
return $("<li class=\""+item.type+"\"></li>").data( "item.autocomplete", item ).append(""+item.title+"").appendTo(ul);
};
the controller:
public function search(){
$search = $this->input->post('q');
// Run some setup
$this->rest->initialize(array('server' => 'http://api.netflix.com/'));
// set var equal to results
$netflix_query = $this->rest->get('catalog/titles/autocomplete', array('oauth_consumer_key'=>$this->consumer_key,'term'=> $search,'output'=>'json'));
//$this->rest->debug();
//$json_data = $this->load->view('nice',$data,true);
//return $json_data;
echo json_encode($netflix_query);
}
the json return
{"autocomplete":
{"autocomplete_item":[
{"title":{"short":"The Strawberry Shortcake Movie: Sky's the Limit"}},
{"title":{"short":"Futurama the Movie: Bender's Big Score"}},
{"title":{"short":"Daffy Duck's Movie: Fantastic Island"}}
...
any ideas?
thanks.
there are some console logs with the return
the url
in, as you've noticed, doesn't do what you'd like with arrays. Use $.each
As far as I know, for (property in object) means that you want to access each of its properties rather than accessing them via the index. If you want to access them via the index, you probably want to use the standard for loop.
for (i = 0; i <= 10; i++) {
response(data.autocomplete.autocomplete_item[i].title.short);
}
or if you still want to use your code, try this:
for (i in data.autocomplete.autocomplete_item) {
response(i.title.short);
}
I haven't test them yet but I think you have the idea.
ok I figured out the correct format that I need to send to the autocomplete response method:
the view
$("#movies").autocomplete({
minLength: 2,
source: function(request, response) {
$.post("<?php echo base_url();?>welcome/search", {q: request.term},
function(data){
//console.log(data);
response(data);
}, 'json');
}
});
the controller:
$search = $this->input->post('q');
// Run some setup
$this->rest->initialize(array('server' => 'http://api.netflix.com/'));
// Pull in an array
$netflix_query = $this->rest->get('catalog/titles/autocomplete', array('oauth_consumer_key'=>$this->consumer_key,'term'=> $search,'output'=>'json'),'json');
$json = array();
foreach($netflix_query->autocomplete->autocomplete_item as $item){
$temp = array("label" => $item->title->short);
array_push($json,$temp);
}
echo json_encode($json);
what was needed was to send back to the view an array of objects. Thank you guys for all your answers and help!!