So I have this php class where i have a function that get users from a PSQL database but the AJAX keep loging empty array in the console:
public function getUsers(){
$query = pg_query(self::$DBH, "select id, name, email, admin from users order by name;");
$result = array();
$i = 0;
while ($row = pg_fetch_row($query)) {
$result[$i] = $row;
$i++;
}
return $result;
}
I use a phphandler file to call the function from ajax
:
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/bdd.php';
require_once 'modele_backend.php';
$module = new Modele_Backend();
echo json_encode($module -> getUsers());
?>
and finaly there is the AJAX call
$(document).ready(function(){
$("#user_email").on("input", function(){
// Print entered value in a div box
$.ajax({
url: 'modules/mod_backend/backendHandler.php',
type: 'post',
dataType: 'json',
success: function(response) { console.log(response); }
});
});
});
The problem is that js keep showing empty array in the console.
The json_encode works fine as json_last_error = 0.
I Tried replacing the return of my getUsers() function by
echo json_encode($result);
to test if the function manage to encode my array and it did show up like a JSON on the page so this is not a encoding of my array problem. Still when AJAX get the result of the json_encode function it display an empty array.
Thanks for any help !
Necro.
Solution 1
You have to set content type of header in your php file before echo
header('Content-type: application/json');
Solution 2
change dataType in your ajax code to html
or remove it to return default dataType (default: Intelligent Guess (xml, json, script, or html))
and then convert returned string to json using javascript JSON.parse() method .
It turned ou the problem was not json_encode at all, it was a problem with my static DB class wich I was includong twice with the AJAX call.
Thanks anyway for the support
Related
I really thought I would figure this one out but I am stuck.
I only want to get one single result from this PHP file, so I believe it is unescessary to use an array then?
However, I've tried console.log(result) multiple times but I am only recieving "null".
What am I doing wrong?
AJAX:
$.ajax({
url: "includes/getwinner.php",
success: (function (result) {
console.log(result);
})
})
PHP
include("../steamauth/db.php");
$result=mysqli_query($db, "select low_winner from pots");
$row=mysqli_fetch_assoc($result);
echo $row['low_winner'];
Try this:
if ($result = mysqli_query($db, "select low_winner from pots")) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
echo $row["Name"];
}
/* free result set */
mysqli_free_result($result);
}
Use the mysqli_free_result function correctly, docs here.
I am trying to send some data from JS to PHP and make a DB request, which goes back into my JS.
Problem is, I only get "null" as result.
I checked and double checked my Query which is perfectly fine.
Here the JS:
var selectedEngin = getSelectedText(enginID);
selectedEngin = selectedEngin.slice(0, -1);
var roleNameList = new Array();
$.ajax({
url: '/getRoleNames.php',
type: "POST",
dataType:'json',
data: { engin : selectedEngin },
success: function(data){
console.info(data);
}
});
And the PHP:
include_once ("config.php");
$userAnswer = $_POST['engin'];
$row = array();
$query="select ROLE_NAME from type_vehicule_role WHERE TV_CODE
='".$userAnswer."' ORDER BY ROLE_ID" ;
$result=mysqli_query($dbc,$query);
$row=mysqli_fetch_array($result);
echo json_encode($row);
If I give back "test" instead of $row, it works perfectly as well.
Hope you can help me! Thank you!
Have a nice day!
$dbc has to contain the info with the parameters to connect to the DB. In your case the $result is null as your connection cause an error.
Try using this to get all of the data properly encoded prior to feeding it to the json_encode() call.
include_once ("config.php");
$userAnswer = $_POST['engin'];
$row = array();
$query="select ROLE_NAME from type_vehicule_role WHERE TV_CODE
='".$userAnswer."' ORDER BY ROLE_ID" ;
$result=mysqli_query($dbc,$query);
$row=mysqli_fetch_array($result);
// Walk the array and encode everything in UTF8
$utf8Row = array_map(utf8_encode, $row);
// JSONify the encoded array
echo json_encode($utf8Row);
Thanks to BA_Webimax I found the problem and got an answer:
The problem was the charset. I solved it using mysqli_set_charset($dbc,"utf8"); in the PHP.
Thank you for your help guys!
Have a nice day!
Here is my code to call AJAX and get the response from another PHP file:
$.post('<?php echo get_site_url(); ?>/ajax-script/',{pickup:pickup,dropoff:dropoff,km:km},
function(data){
$('#fare').html(data);
$('#loading_spinner').hide();
});
ajaxscript.php file
$jsonData = '{"fare":30580,"actual_distance":1519,"city":"Islamabad","status":true}';
$json = json_decode($jsonData,true);
echo $json['fare'];
This code gives me the fare at the time of $('#fare').html(data);
But I need to extract the city from JSON, too, and for this I added an extra line in ajaxscript.php:
echo $json['city'];
After doing this, it gives me 30580Islamabad
How can I store these two values separately in JavaScript? I need them for future work.
You are doing everything backwards
Your PHP should be
$jsonData = '{"fare":30580,"actual_distance":1519,"city":"Islamabad","status":true}';
//$json = json_decode($jsonData,true);
echo $jsonData;
As you already have a JSONString to send to your javascript.
Then your javascript will recieve a javascript object in the data parameter of
$.post( '<?php echo get_site_url(); ?>/ajax-script/',
{pickup:pickup,dropoff:dropoff,km:km},
function( data ) {
$('#fare').html(data.fare);
$('#city').html(data.city);
$('#loading_spinner').hide();
}, "json");
Note the "JSON" at the end of the javascript to tell it to expect a JSON Object, it will then convert the JSONString to a javascript Object automatically for you so the data parameter will be an onbect
Add Special characters at the end of each value and in jquery, using jquery split, cut the variable and display
like below;
$jsonData = '{"fare":30580^^,"actual_distance":1519^^,"city":"Islamabad^^","status":true}';
$json = json_decode($jsonData,true);
echo $json['fare'];
in jquery
function(data){
var tdata = data.split("^^");
$('#fare').html(tdata[0]);
$('#loading_spinner').hide();
});
I finally could receive a response from my AJAX PHP call.
But now in return I get my full HTML site instead of a JSON object or string.
What is wrong here?
var request = $.ajax({
url: "mysite.php",
type: "POST",
data: {select:requestStr},
dataType: "html"
});
request.done(function( data ) {
console.log(JSON.stringify(data));
});
I send a simple string to my php class. This is what I get from the response-text in my developer tool from the browser:
data=Test
On PHP site I just return that respone:
<?php
$myData = array();
$myData['data'] = "test";
if (isset($_POST)) {
$myData['data'] = $_POST;
}
echo json_encode($myData);
exit();
?>
And this is the console.log from the response:
"<!DOCTYPE html>\r\n<html>\r\n<head> ... </html>\"Test\""
EDIT
I only need the end of the response and that is "Test" but not the whole HTML file.
UPDATE
I extracted my PHP class and wrote a Little Version like the PHP code above.
But now my response is an empty object {"data":[]}
Hey put type="Json" instead of the "text"
Put a exit(); after echo json_encode($myData);
I've been smashing my head against a brick wall with this one, i've tried loads of the solutions on stackoverflow but can't find one that works!
Basically when I POST my AJAX the PHP returns JSON but the AJAX shows Undefined instead of the value:
JS:
/* attach a submit handler to the form */
$("#group").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/*clear result div*/
$("#result").html('');
/* get some values from elements on the page: */
var val = $(this).serialize();
/* Send the data using post and put the results in a div */
$.ajax({
url: "inc/group.ajax.php",
type: "post",
data: val,
datatype: 'json',
success: function(data){
$('#result').html(data.status +':' + data.message);
$("#result").addClass('msg_notice');
$("#result").fadeIn(1500);
},
error:function(){
$("#result").html('There was an error updating the settings');
$("#result").addClass('msg_error');
$("#result").fadeIn(1500);
}
});
});
PHP:
$db = new DbConnector();
$db->connect();
$sql='SELECT grp.group_id, group_name, group_enabled, COUNT('.USER_TBL.'.id) AS users, grp.created, grp.updated '
.'FROM '.GROUP_TBL.' grp '
.'LEFT JOIN members USING(group_id) '
.'WHERE grp.group_id ='.$group_id.' GROUP BY grp.group_id';
$result = $db->query($sql);
$row = mysql_fetch_array($result);
$users = $row['users'];
if(!$users == '0'){
$return["json"] = json_encode($return);
echo json_encode(array('status' => 'error','message'=> 'There are users in this group'));
}else{
$sql2= 'DELETE FROM '.GROUP_TBL.' WHERE group_id='.$group_id.'';
$result = $db->query($sql2);
if(!$result){
echo json_encode(array('status' => 'error','message'=> 'The group has not been removed'));
}else{
echo json_encode(array('status' => 'success','message'=> 'The group has been removed'));
}
}
JSON Result from firebug:
{"status":"success","message":"success message"}
AJAX Displays the JSON result as Undefined and I dont have a clue why. I have tried displaying adding dataType='json' and datatype='json'. I have also tried changing it to data.status and data['status']: still no joy though.
Any help would be really appreciated.
Make it dataType instead of datatype.
And add below code in php as your ajax request is expecting json and will not accept anything, but json.
header('Content-Type: application/json');
Correct Content type for JSON and JSONP
The response visible in firebug is text data. Check Content-Type of the response header to verify, if the response is json. It should be application/json for dataType:'json' and text/html for dataType:'html'.
I recommend you use:
var returnedData = JSON.parse(data);
to convert the JSON string (if it is just text) to a JavaScript object.
Use parseJSON jquery method to covert string into object
var objData = jQuery.parseJSON(data);
Now you can write code
$('#result').html(objData .status +':' + objData .message);
try to send content type header from server use this just before echoing
header('Content-Type: application/json');
Your datatype is wrong, change datatype for dataType.