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.
Related
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.
So, I've been looking for a variety of sources to answer my question the last few day and thus have found nothing that's worked for me. I'll preface this further by saying that in regards to PHP and Javascript I started learning them like a week ago. I also understand that there will likely be better ways to format/write the code I'm about to post so please bear with me! :)
Essentially, I am trying to use a page name play.php in combination with AJAX to echo MYSQL queries back onto the page inside certain page elements.
So the code for main.js which is linked directly to play.php. I've tried about three different way that I've seen in various answers and have not gotten the information I wanted. I either get no response or I get undefined in all of them.
function selectChar(uname, cname)
{
var data = {
username : uname,
charname : cname
};
$.ajax({
data : data,
type : 'Get',
url : 'start.php',
dataType:"json",
success : function (result) {
var data_character = JSON.parse(result);
var cnamediv = document.getElementById('charactername');
cnamediv.innerHTML = "";
cnamediv.innerHTML = data_character[0].name;
}
});
}
The one above I see most often and the one below I just found earlier today. I get undefined when I attempt to call the array.
function selectChar(uname, cname)
{
$.get("start.php?username="+uname+"&charname="+cname).done(function(data_character){
var cnamediv = document.getElementById('charactername');
cnamediv.innerHTML = "";
cnamediv.innerHTML = data_character[0].name;
});
}
and finally the PHP code that queries the database and echos the data back.
<?php
$conn = new mysqli($hostname,$username,$dbpassword, $dbname);
if(!$conn) {
die('Could not connect: ' . mysql_error());
}
$username = $_GET['username'];
$charname = $_GET['charname'];
$sql = "SELECT `id`, `username` FROM `users` WHERE `username` ='$username'";
$result = mysqli_query($conn,$sql);
//Send the array back as a JSON object
echo json_encode($result);
?>
I'm not looking for someone to do work for me but I do require some guidance here. What would be an appropriate way to make this work? Is my code terribly incorrect? Am I missing an aspect of this altogether? Please, I would really seriously appreciate any help someone could give me!
P.S. I did just get done reviewing several other similar questions none of which seemed to help. Either there was never a conclusive outcome as to what worked for them or the solution didn't work when I attempted it.
try this:
php get post and return json_encode
if(!$conn) {
die('Could not connect: ' . mysql_error());
}
$username = $_POST['username'];
$charname = $_POST['charname'];
$sql = "SELECT `id`, `username` FROM `users` WHERE `username` ='$username'";
$result = mysqli_query($conn,$sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
//Send the array back as a JSON object
echo json_encode($rows);
?>
JS ajax response and request
$.ajax({
data : data,
type : 'POST',
url : 'start.php',
dataType:"json",
success : function (result) {
console.log(result);
document.getElementById('charactername').innerHTML = result[0].username;
}
});
Hey Logan the issue may be with how the AJAX request is being sent. Try adding the processData property to your request and setting it to false. It just means the data won't be read as a query string and it is as raw data.
$.ajax({
data : data,
type : 'POST',
url : 'start.php',
dataType:"json",
processData: false,
success : function (result) {
console.log(result);
document.getElementById('charactername').innerHTML = result[0].username;
}
});
I would also try echo json_encode($_POST) to see if the you get the following response back :
{username: "hello", charname: "hl"}
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');
Well i have this php for get the value of mysql.
I get two rows in this query.
include('../funciones/funciones.php');
$link=Conectarse();
$pnc=$_GET['pnc'];
$query="SELECT
accion_inmediata.accion,
accion_inmediata.responsable,
accion_inmediata.peligro,
accion_inmediata.ambiente,
DATE_FORMAT(accion_inmediata.fecha,'%m-%d-%Y') as fechaAccion
FROM
accion_inmediata
WHERE
accion_inmediata.id_pnc = '$pnc'";
$result = mysql_query($query,$link);
$array = mysql_fetch_array($result);
echo json_encode($array);
and this is my Jquery code
function traerAcciones(pnc){
$.ajax({
url: 'php_ajax/select_acciones.php?pnc='+pnc,
data: "",
dataType: 'json',
success: function(data)
{
$.each(data, function() {
alert(this.accion);
});
}
});
}
when i execute this code the alert show me "undefined".
The $.each loop works fine but the value is the problem.
Please help and sorry for my bad English
Try to pass the value and the Index as parameters, this is how it works:
$.each(data, function(index, value) {
alert( value.accion );
});
Might also be a problem with the data object not containing what you think it does, do a
console.log(index, value);
inside your loop and a
console.log(data);
before the loop and you will see what you have and how to handle it.
Hope it helps!
Currently you are returning the array of your first row only. So to retrieve both you might want to do this:
include('../funciones/funciones.php');
$link=Conectarse();
$pnc=$_GET['pnc'];
$query="SELECT accion_inmediata.accion, accion_inmediata.responsable, accion_inmediata.peligro, accion_inmediata.ambiente, DATE_FORMAT(accion_inmediata.fecha,'%m-%d-%Y') as fechaAccion FROM accion_inmediata WHERE accion_inmediata.id_pnc = '$pnc'";
$result = mysql_query($query,$link);
$array = array();
while($row = mysql_fetch_array()):
$array[] = $row;
endwhile;
echo json_encode($array);
Now your jquery should be able to retrieve the data. Also, please avoid using MYSQL_QUERY it's deprecated.
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.