ajax data[0] is undefined - php

I use ajax to get the number of rows (COUNT(*)) from a sql query in php.
The JSON return in Firefox-Network tab is:
[{"number":2}],
(the 2 is without quotes).
But in "ajax success" , when i try to get the value (2) from data[0]["number"] or data.length,it returns "undefined".
It works only if i parse JSON as object.
$.ajax({
url: 'queries.php?q=count',
type: 'post',
//data: data,
datatype: 'json',
success: function(data) {
//var dataobject = jQuery.parseJSON(data);
//console.log(dataobject);
//var var2 = dataobject[0].number; ---->THIS WORKS!
//alert(JSON.parse(data).length); ---->THIS WORKS!
//console.log(data.length); ---->Undefined
console.log(typeof data); ---->string
console.log(data[0]["number"]);---->Undefined,i want this to work!!!
}
});
Thw SQL i use in php is :
switch ($_GET["q"]) {
case "count":
$sql = "SELECT count(*) as number from
(SELECT Employees.emp_username, .............
where Employees.emp_username = ? and Year(emp)=2016 and Month(emp)= MONTH(getdate()) ) as rows1 ";
$stmt = sqlsrv_prepare( $conn, $sql , array(&$_SESSION["username"] ));
break;
default: header("Location: index.php"); }
if( !$stmt ) { die( print_r( sqlsrv_errors(), true)); }
sqlsrv_execute($stmt);
$rows = array();
if(sqlsrv_execute($stmt)){
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
$rows[] = $row; }
} else{
die( print_r( sqlsrv_errors(), true));
}
print json_encode($rows);

You have to parse the data first, like you did with jQuery.parseJSON(data) or like in the alert JSON.parse(data).
data is a string object, so when you access the element [0] you are getting the first character of the string. In your example: [. This is the first element of the string [{"number":2}].
My suggestion is to apply [0]['number'] to dataobject, so your code should look like this:
$.ajax({
url: 'queries.php?q=count',
type: 'post',
//data: data,
datatype: 'json',
success: function(data) {
var dataobject = jQuery.parseJSON(data);
console.log(dataobject[0]["number"]);
}

Your variable type is string. You must parse it first.
$.ajax({
url: 'queries.php?q=count',
type: 'post',
//data: data,
datatype: 'json',
success: function(data) {
//var dataobject = jQuery.parseJSON(data);
//console.log(dataobject);
//var var2 = dataobject[0].number; ---->THIS WORKS!
//alert(JSON.parse(data).length); ---->THIS WORKS!
//console.log(data.length); ---->Undefined
console.log(typeof data); ---->string
data = JSON.parse(data);
console.log(data[0]["number"]);---->Undefined,i want this to work!!!
}
});

Related

Ajax success function not working with json answer

If I set dataType to 'json' and inside my PHP file I print whatever I want (event a letter), success function works, but if I don't print anything else besides the JSON I need, stops working. I can't handle my data with something else printed, because it turns the answer into HTML, instead of JSON. I'm able to see in Network -> Answer the JSON file (only when I don't print anything else beside the JSON), but I don't know why I can't even do an alert in success function when that is the case.
This is my ajax, which only works because I'm printing 'true' on the server:
$(document).on("click", "#btnEditarInstructor", function(event) {
event.preventDefault();
let rfc = $(this).attr("value");
$.ajax({
type: "POST",
url: "../utils/ajax/ajax_consulta_instructor.php",
data: {
rfc: rfc,
},
dataType: "json",
succes: function(response) {
if (response == true) {
// alert(response);
}
},
error: function(request, status, error) {
var val = request.responseText;
alert("error" + val);
alert(status);
alert(error);
},
});
})
This is my PHP code:
$rfc = $_POST['rfc'];
$sql = "SELECT * FROM instructores WHERE rfc = '$rfc'";
$sql_run = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($sql_run)) {
echo "true";
$datos['status'] = 'OK';
$datos['nombre'] = $row['nombre'];
$datos['apellidos'] = $row['apellidos'];
$datos['email'] = $row['email'];
$datos['tipo_promotor'] = $row['tipo_promotor'];
echo json_encode($datos);
}
By the way, with that code, I get this error on the alert:
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 5 of the JSON data
I'm using jQuery 3.6.0 (https://code.jquery.com/jquery-3.6.0.js)
If you're returning JSON, you can only echo the JSON once, not each time through the loop.
If there can only be one row, you don't need the while loop. Just fetch the row and create the JSON.
You also can't echo anything else, so the echo "true"; lines are breaking it.
And your code is wide open to SQL-injection. You should use a prepared statement with a parameter, which I've shown how to do.
$rfc = $_POST['rfc'];
$stmt = $con->prepare("SELECT * FROM instructores WHERE rfc = ?");
$stmt->bind_param("s", $rfc);
$stmt->execute();
$sql_run = $stmt->get_result();
$datos = [];
if($row = mysqli_fetch_array($sql_run)){
$datos['status'] = 'OK';
$datos['nombre'] = $row['nombre'];
$datos['apellidos'] = $row['apellidos'];
$datos['email'] = $row['email'];
$datos['tipo_promotor'] = $row['tipo_promotor'];
}
echo json_encode($datos);
$(document).on("click", "#btnEditarInstructor", function (event) {
event.preventDefault();
let rfc = $(this).attr("value");
$.ajax({
type: "POST",
url: "../utils/ajax/ajax_consulta_instructor.php",
data: {
rfc: rfc,
},
dataType: "json",
success: function (response) {
if (response == true) {
// alert(response);
}
},
error: function (request, status, error) {
var val = request.responseText;
alert("error" + val);
alert(status);
alert(error);
},
});

Return php array to ajax not working

I am running a query to database which fetch a row and i want to return it as array which can accessed as array['min'], array['max'] etc. if i echo it with specific index, it shows the value correctly in ajax but i am unable to pass complete row through it to the ajax file.
PHP file:
<?php
// Database logic here
$calid = reset($_POST);
require '../incs/connect.php';
$sql=mysqli_query($con, "SELECT * FROM calcus_sets WHERE sets_id=$calid ");
WHILE($row=mysqli_fetch_array($sql))
{
echo $row['min']; break;
}
mysqli_close($con);
?>
JS file:
function DB_Fetecher(ops){
$.ajax({
type: "POST",
data: {ops},
url: "calcus_es1-fetcher.php",
success: function(res)
{
// alert( res );
alert(res);
}
});
}
This code get right value from mysql but i want to pass full row to ajax and then use each index in ajax itself to put into textboxes.
You can pass array by:
<?php
// Database logic here
$calid = reset($_POST);
require '../incs/connect.php';
$sql=mysqli_query($con, "SELECT * FROM calcus_sets WHERE sets_id=$calid ");
$result = array();
WHILE($row=mysqli_fetch_array($sql))
{
$result[] = array( "min" => $row['min'], "max" => $row['max'] );
}
mysqli_close($con);
echo json_encode( $result );
?>
On your js, make sure to specify dataType:"json",
function DB_Fetecher(ops){
$.ajax({
type: "POST",
data: {ops},
url: "calcus_es1-fetcher.php",
dataType:"json",
success: function(res)
{
// alert( res );
console.log(res);
}
});
}
Note: It is advisable to use console.log(res); instead of alert() on debugging.

meekro db, json and ajax

I am using meekro db to fetch data from database and when I return object as json format then ajax call goes to error
$(".cat").click(function() {
var value = $(this).attr('id');
$.ajax({
url:"/psl/ajax/get_words.php",
method:"post",
dataType: "json",
data:{ id: value },
success:function(response) // success part does not execute
{
var data = JSON.parse(response);
alert( data );
},
error:function (msg) { // error part executes every time
alert('error');
}
});
});
And the code which is being used to fetch data from database get_words.php
<?php
require_once '../inc/initDb.php';
$id = $_POST['id'];
$words = DB::query("select * from words where category_id = '$id'");
if (DB::count() > 0)
{
echo json_encode($words);
}

json object in php not being read

I want to pass username and password to a php script and check in the database. On the client side I use the following script to make a json object and post it to the php file.
var myobj = {};
myobj["usrname"]= $( "#customer option:selected" ).text();
myobj["usrpass"]= $("#psw").val();
var myjson = JSON.stringify(myobj);
$.ajax({
method: "POST",
url: "checkpass.php",
data: myjson
})
.done(function( msg ) {
alert( msg );
});
On the server side, when I see in firebug, the post is passed as
Parametersapplication/x-www-form-urlencodedDo not sort
{"usrname":"XXXXXXX...
JSON
usrname
"XX"
usrpass
"justdoit"
Source
{"usrname":"XXX","usrpass":"justdoit"}
however when i run the php script to check the query the it returns an error
$usrname = $_POST['usrname'];
$usrpass = $_POST['usrpass'];
$sql = "select count(*) from glusers where EmpName='$usrname' and EmpPass='$usrpass'";
$result = $conn->query($sql);
if($result >0){
$output = 'Success';
} else
{
$output = 'fail';
}
I have tried through all the posts but cannot get this to work.
Thanks in advance.
Regards,
Echo and die the statement in order for ajax to have a success event
Js File
var myobj = {};
myobj["usrname"] = 'myUsername';
myobj["usrpass"] = 'myPassword';
$.ajax({
type: "post",
url: "url",
dataType: "json",
data: {post_data: myobj},
contentType: "application/x-www-form-urlencoded",
success: function (responseData) {
console.log(responseData);
},
error: function (errorThrown) {
console.log(errorThrown);
}
});
PHP action File
/** if we print post we will get the following array * */
//print_r($_Post);
//die()
//Array
//(
// [post_data] => Array
// (
// [usrname] => myUsername
// [usrpass] => myPassword
// )
//
//)
if (isset($_Post['post_data'])) {
$myPost = $_Post['post_data'];
$usrname = $myPost['usrname'];
$usrpass = $myPost['usrpass'];
$sql = "select count(*) from glusers where EmpName='$usrname' and EmpPass='$usrpass'";
$result = $conn->query($sql);
$num_row = $result->num_rows;
if ($num_row > 0) {
$output = 'Success';
} else {
$output = 'fail';
}
echo json_encode($output);
die();
}
Try This :
in js file :
$(document).on("ready", function(){
// Create an object using an object literal.
var ourObj = {};
// Create a string member called "data" and give it a string.
// Also create an array of simple object literals for our object.
ourObj.data = "Some Data Points";
ourObj.arPoints = [{'x':1, 'y': 2},{'x': 2.3, 'y': 3.3},{'x': -1, 'y': -4}];
var savedata = JSON.stringify(ourObj)
$.ajax({
type:"POST",
url:"Users.php",
data: {"points" : JSON.stringify(ourObj)},
success: function(data) {
// Do something with data that came back.
alert(data);
}
})
});
In PHP File :
if (isset($_POST["points"])) {
$points = json_decode($_POST["points"]);
echo "Data is: " . $points->data . "<br>";
echo "Point 1: " . $points->arPoints[0]->x . ", " . $points->arPoints[0]->y;
}
Try this:
var myobj = '{
usrname:'+$( "#customer option:selected" ).text()+',
usrpass:'+$("#psw").val()+'
}';
or
var myobj = {};
myobj.usrname= $( "#customer option:selected" ).text();
myobj.usrpass= $("#psw").val();
Use Json2 library as follows,
var myobj = {};
myobj["usrname"]= $( "#customer option:selected" ).text();
myobj["usrpass"]= $("#psw").val();
var myjson = JSON2.stringify(myobj);
$.ajax({
method: "POST",
url: "checkpass.php",
data: myjson
})
.done(function( msg ) {
alert( msg );
});
Well actually you php code is invalid because you pass json day not name value pair so you cant get it from $_POST['username']. You need to get the whole post data and decode it like this.
$data = json_decode(file_get_contents('php://input'), true);
Now $data is dictionary array of username and password. Also sanitize your data before passing to query to avoid sql injection.

retrieve mysql result to jquery

My problem is that I can't retrieve the result of the mysql result via ajax, please help
ajax code:
$.ajax({
type: "POST",
url: "do_find_courses.php",
//data:{question_id:question_id,answer:answer},
data:{user_id:user_id}, dataType:'json',
success:function(msg) {
alert ('asdasd')
// $("#quiz_form,#demo1").addClass("hide");
// $('#result').show();
$('p').html(msg);
}
});
PHP code:
$final=array();
$sql_courses=mysql_query("SELECT course_id, course_name FROM course") or die (mysql_error());
$row_courses = mysql_fetch_array($sql_courses);
$result=$row_courses['course_name'];
//array_push($final,$result);
//print_r($result);
echo json_encode($result);
Change PHP Code as below
$final = array();
$sql_courses = mysql_query("SELECT course_id, course_name FROM course") or die(mysql_error());
$row_courses = mysql_fetch_array($sql_courses);
echo json_encode($row_courses);
change php code as below:
$.ajax({
type: "POST",
url: "do_find_courses.php",
//data:{question_id:question_id,answer:answer},
data: {
user_id: user_id
},
dataType: 'json',
success: function (msg) {
$('p').html(msg.course_name);
}
});
Its better to send it with a key value like this:
And its better to use console.log(variable); to check variable's content
ajax code:
$.ajax({
type: "POST",
url: "do_find_courses.php",
//data:{question_id:question_id,answer:answer},
data:{user_id:user_id}, dataType:'json',
success:function(msg) {
alert ('asdasd');
console.log(msg);//You should check output of this in browser console
// $("#quiz_form,#demo1").addClass("hide");
// $('#result').show();
$('p').html(msg.cname);
}
});
PHP code:
$final=array();
$sql_courses=mysql_query("SELECT course_id, course_name FROM course") or die (mysql_error());
$row_courses = mysql_fetch_array($sql_courses);
$result=$row_courses['course_name']; // this will have first_coures_name (an string)
$final['cname']=$result;
//print_r($result);
echo json_encode($final); //the output should be this {'cname':'first_course_name'}

Categories