Data is obtained in the error function of the ajax - javascript

I'm trying to fetch the data from the datatable using ajax in cakephp. I'm sending a data named designation and wanna fetch all the records against that. This is how I've tried:
ajax:
$("#Designation").click(function(){
alert($("#Designation").val());
var data = {
"Designation": $("#Designation").val()
}
$.ajax({
type:"POST",
dataType: "JSON",
url: '<?php echo Router::url(array('controller'=>'DynamicForm','action'=>'getbulkoptions')); ?>',
data:data,
success:function(data){
alert("success");
console.log(data);
if(data.fieldid=="0"){
//MyNotif.Show(data.message,"warning");
alert("Field Exists");
}else{
$("#mymodal").modal('hide');
//MyNotif.Show(data.message,"success");
//window.location.reload();
alert("Bulk List");
}
},
error:function(XMLHttpRequest, textStatus, errorThrown){
console.log(XMLHttpRequest.responseText);
}
});
});
This is how I try to communicate with the DB:
DynamicFormController:
<?php
namespace App\Controller;
session_start();
use App\Controller\AppController;
use Cake\ORM\TableRegistry;
class DynamicFormController extends AppController {
public function getbulkoptions(){
$optionvalue = $this->request->data('Designation');
$designation = TableRegistry::get ('Field');
$result = $designation->getbulkoptions($optionvalue);
echo json_encode($result);
}
}
?>
FieldTable:
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Datasource\ConnectionManager;
class FieldTable extends Table {
var $name = 'FieldTable';
public function getbulkoptions($designation){
$conn = ConnectionManager::get('default');
$stmt = $conn->prepare( "CALL proc_getbulkoptionslist (:tid)");
$stmt->bindValue( ':tid', $designation);
$stmt->execute ();
return $stmt->fetchAll ('obj');
}
}
The thing is, I get a proper response. I get the data I want, but that data is being printed in the error function of the ajax. I want it to be in the success function. I don't know what's wrong with the above code. When I tried to print the error, I got this:
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 364 of the JSON data
Stack trace:
n.parseJSON#http://localhost/payrollengine/js/jquery.js:4:16508
Wb#http://localhost/payrollengine/js/jquery.js:4:18828
y#http://localhost/payrollengine/js/jquery.js:4:22274
.send/c#http://localhost/payrollengine/js/jquery.js:4:26750
I tried this in the error function and tried printing it out, I got this response:
error:function(XMLHttpRequest, textStatus, errorThrown){
console.log(XMLHttpRequest.responseText);
}
response:
[{"fieldvalueid":"1","value":"Manager"},{"fieldvalueid":"2","value":"Project Manager"},{"fieldvalueid":"3","value":"Software Engineer"},{"fieldvalueid":"4","value":"Senior Software Engineer"},{"fieldvalueid":"5","value":"Associate Software Engineer"},{"fieldvalueid":"28","value":"sample"},{"fieldvalueid":"29","value":"azhagu"},{"fieldvalueid":"37","value":"t"}]null
I don't know what's wrong with the code. Can someone help me out with this?

Add the json header to your controller function:
header('Content-Type: application/json');
echo json_encode($result);
try to return a associative array from the db
->fetchAll('assoc');

Related

json_encode prints data in html

I'm trying to pass Database table from PHP (using Object-Oriented approach) to Javascript using Ajax (json_encode) which I've done successfully. The problem, however, is that the values that are inside the $data variable are printed in my body tag with a huge whitespace after it.
Server Side:
<?php
require_once "Database.php";
Class Product extends Database
{
public function getAllProducts(){
$sql = $this->connectDB()->query("SELECT * FROM product");
while($row = $sql->fetch()) {
$data[] = $row;
}
echo json_encode($data);
}
}
$p = new Product();
$p->getAllProducts();
?>
Client side:
$(function() {
getProductData();
});
function getProductData(){
$.ajax({
url: "Product.php",
type: "get",
dataType: "json",
success: successAjax,
error: errorAjax,
complete: function(xhr, status) {
console.log(xhr);
console.log(status);
}
});
}
function successAjax($jsonarray){
console.log($jsonarray);
}
Output (Note that body tags aren't being outputted):
<body>
"[{"id":"1","0":"1","name":"john","1":"john"},
{"id":"2","0":"2","name":"bob","1":"bob"}]"
</body>
Is there any way to prevent echo json_encode from printing data in HTML if all I want to do is pass it from PHP to javascript?
Try to send out the json http header in first place on product.php
header('Content-Type: application/json');

cannot receive json in js ajax request from php file

onclick onto a button the js starts an ajax request to the php file. The php file then gets all entries of one table of a database with php-loop. adding them to an array then the php file parse it to a JSON and echos it back to the ajax request. on success the ajax request should output an alert but neither do i get an error nor a alert.
After adding some changes according to the comments. it is now showing the error message 2 error messages randomly:
Fehler: {"readyState":0,"responseText":"","status":0,"statusText":"error"}
Fehler: {"readyState":4,"responseText":"<br />\n<b>Fatal error</b>: Uncaught Error: Cannot use object of type mysqli_result as array in C:\\xampp\\htdocs\\integration\\get.php:32\nStack trace:\n#0 C:\\xampp\\htdocs\\integration\\get.php(13): getLevel1()\n#1 {main}\n thrown in <b>C:\\xampp\\htdocs\\integration\\get.php</b> on line <b>32</b><br />\n","status":200,"statusText":"OK"}
php request (mysqli attributes are left out on purpose):
$func = $_POST['func'];
if ($func == "getLevel1"){
getLevel1();
}
$result = array();
function getLevel1(){
// Create connection
$conn = new mysqli(servername, username, password, dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name FROM capability_level1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$result[] = '<button onclick="capability('. $row["id"] .')">' . $row["name"]. '</button></br>';
}
echo json_encode($result);
} else {
echo json_encode("0 results");
}
$conn->close();
}
js ajax call:
async function getLevel1() {
return $.ajax({
type: "POST",
dataType: "json",
url: "get.php",
data: {
func: "getLevel1"
},
success: function(data) {
alert(JSON.stringify(data));
console.log(data);
},
error: function(data) {
alert("Fehler: "+ JSON.stringify(data));
}
});
}
You need to put the json encoding when you have a complete array to be encoded: after the while:
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$result[] = '<button onclick="capability('. $row["id"] .')">' . $row["name"]. '</button></br>';
}
echo json_encode($result);
} else {
Also note that you probably have to change your data type to Json (and send a json to php) to be able to return it. Actually your Ajax is waiting for text to be returned (based on the data type)
For your further error: it is related to the point that you are fetching the rows from mysql using the wrong function. See this question for more details on how to fix it.

Need to show data in javascript from db

I'm working with a php code where I get variables from an input and using ajax
code:
$.ajax({
type: "GET",
url: "controller/appointment/src_agenda.php",
data: {
function: "professional",
variable: professional,
},
dataType: "html",
fail: function( jqXHR, textStatus, errorThrown ) {
alert(jqXHR);
},
error: function (jqxhr, ajaxOptions, thrownError) {
alert(JSON.stringify(jqxhr));
alert(jqxhr.status);
alert(thrownError);
},
success: function(data){
console.log(data);
}
});
I get an array in the success function:
object(mysqli_result)#3 (5) {
["current_field"]=>
int(0)
["field_count"]=>
int(6)
["lengths"]=>
NULL
["num_rows"]=>
int(76)
["type"]=>
int(0)
}
If I use php foreach it shows all the rows, but I tried javascript data.forEach and it says it doesn't exist. I also tried for(var element of data) but it shows each character as an individual.
How can I show each row from this query result in javascript?
This is the code of the model:
$sql = "SELECT medical_agenda_id, day, `date`, time_start, time_end, hour_status_id FROM medical_agenda WHERE hour_status_id>='0' AND professional_id='".$id."' ;";
var_dump($sql);
$res = $this->db->query($sql);
return $res;
I need to put the result in the success function
return $res; would return plenty of unwanted data. Rather, get the resultset's data into an associative array and echo json_encode() it.
data_type better be JSON instead of html. Because, that will let you get the minimal amount of data in the payload. And you can decide how you present them in the front end.
It should be something like follows.
while($row = mysqli_fetch_assoc($res)){//Using procedural style here
$data[] = $row;
}
echo json_encode($data);
Plus, var_dump($sql) also should be taken out. Otherwise, that will also be included in the HTTP response, which will make the JSON string invalid.
With all the garbage out,
$sql = "SELECT medical_agenda_id, day, `date`, time_start, time_end, hour_status_id FROM medical_agenda WHERE hour_status_id>='0' AND professional_id='".$id."' ;";
//var_dump($sql); Take this out!
$res = $this->db->query($sql);
//return $res; Take this out! You will return the data by echoing it to the Web Server
while($row = mysqli_fetch_assoc($res)){//Using procedural style here
$data[] = $row;
}
echo json_encode($data); //This is the output tho the client's request.
should do the trick.
This is the MINIMAL that you could do to get your code working. There are many many optimizations that you need to do, before you put it in production.

Ajax post returns multiple arrays with objects that have multiple values

So I have a php file that gets messages from a database (ajax.php) and a javascript file that makes ajax request to that ajax.php file (main.js).
What I want: When the php is responding multiple times, the js file would make a table row for every one of them.
main.js:
function doAjax(variable) {
$.ajax({
type: "POST",
url: "ajax.php"
data: { content: variable },
dataType: 'JSON',
success: function (response) {
response.forEach(function(data) {
$(".messages-table").append("<tr><th>"+from+"</th><th>"+text+"</th><th>"+date+"</th><th>"+num+"</th></tr>")
})
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
ajax.php:
<?php
...
foreach ($messages as $message) {
$from = $message['contact_value'];
$text = $message['message'];
$date = $message['date'];
$num = $user['phone_number'];
echo json_encode(array("from"=>"$from", "text"=>"$text", "date"=>"$date", "num"=>"$num"));
?>
But when i do that I get this error in developer console:
parsererror SyntaxError: Unexpected token < in JSON at position 0
at parse (<anonymous>)
at Qb (jquery.min.js:4)
at A (jquery.min.js:4)
at XMLHttpRequest.<anonymous> (jquery.min.js:4)
Cheers
Your ajax.php should be like this
<?php
foreach ($messages as $message) {
$from = $message['contact_value'];
$text = $message['message'];
$date = $message['date'];
$num = $user['phone_number'];
echo json_encode(array("from"=>$from, "text"=>$text,"date"=>$date,"num"=>$num));
?>
if you really want the quotes then use ' ' (singlequotes) instead.
And the javascript file.
success: function (response) {
var success = $.parseJSON(response);
$(".messages-table").append("<tr><th>"+success.from+"</th><th>"+success.text+"</th><th>"+success.date+"</th><th>"+success.num+"</th></tr>");
}
i think you don't need to use the forech loop if you call the doAjax function every time.

jQuery AJAX Call to PHP Script with JSON Return

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.

Categories