Dealing with returned JSON data - javascript

I'm querying my database using ajax (jquery) but the data I'm getting back is proving difficult to deal with. I did notice that others have posted similar issues and identified the PHP code (specifically how data is being allocated to the array) as being the issue. However I couldn't find a solution. The contents of my returned data (when I transform the returned data into a string) looks like this:
[{"id":"1","userName":"admin","userPassword":"admin","userEmail":"admin#admin.com","userRegistrationIP":"","registrationDateTime":"2015-05-28 21:22:54","userLastLogin":"2015-05-28 21:22:54"}]
I'd really like to be able to pull an individual element from the returned data, such as the userLastLogin field.
My ajax query:
$.ajax({
url: 'authenticate2.php',
type: 'POST',
dataType: 'JSON',
data: {
username: $('#username').val(),
},
success: function (res) {
$('#resultBox').text(res);
}
});
My PHP below:
<?php
$con = mysqli_connect('127.0.0.1','root','','db1');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"db1");
$sql="SELECT * FROM Users WHERE userName = 'admin'";
$result = mysqli_query($con,$sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode($rows);
mysqli_close($con);
?>

This'll help you
JS
success: function (res) {
var res = [{"id":"1","userName":"admin","userPassword":"admin","userEmail":"admin#admin.com","userRegistrationIP":"","registrationDateTime":"2015-05-28 21:22:54","userLastLogin":"2015-05-28 21:22:54"}];
$.each(res,function(key,value){
alert(res[key].id);
alert(res[key].userName);
alert(res[key].userPassword);
alert(res[key].userEmail);
alert(res[key].userRegistrationIP);
alert(res[key].registrationDateTime);
alert(res[key].userLastLogin);
})
}

You can access individual elements from array like this (Client Side)
$.ajax({
....
....
success: function (res) {
alert(res[0].userLastLogin);
// OR
alert(res[0]['userLastLogin']);
}
});

Check out this:
$.ajax({
url: 'authenticate2.php',
type: 'POST',
success: function(res) {
var response = $.parseJSON(res);
console.log(res.userLastLogin);
})
or you can just do this in your ajax success:
$.each(JSON.parse(res), function() {
console.log(this[Object.keys(this)[6]]);
});

Try this
var json = '{"id":"1","userName":"admin","userPassword":"admin","userEmail":"admin#admin.com","userRegistrationIP":"","registrationDateTime":"2015-05-28 21:22:54","userLastLogin":"2015-05-28 21:22:54"}';
for(var i = 0; i < json.length; i++) {
var obj = json[i];
console.log(obj.userLastLogin);
}

If u want to use only userLastLogin data then u can try this ,
while($r = mysqli_fetch_assoc($result)) {
$rows['userLastLogin'] = $r['userLastLogin'];
}

Related

pass array values from javascript to php

<script>
$("#submit").click(function () {
var newhour= [];
for (var i = 0; i < arrayNumbers.length; i++) {
newhour.push(arrayNumbers[i].toString().split(','));
console.log("each: " + newhour[i]); // output: each: 07:00,08:30
each: 18:00,19:00
}
console.log("all: " + newhour); //output: all: 07:00,08:30,18:00,19:00
var jsonString = JSON.stringify(newhour);
$.ajax({
type: "POST",
url: "exp.php",
data:{data: jsonString},
cache: false,
success: function(){
alert("OK");
}
});
});
<script>
I want to pass the newhour array values to php and use them to insert into a table.
so php file, exp.php:
$data = explode(",", $_POST['data']);
foreach($data as $d){
echo $d;
$sql = "insert into exp_table (hour) values ('$d')";
mysql_query($sql);
}
However I can not take the values. What is wrong with the code?
Could you please help me?
Thanks in advance.
according to the answers i tried this on php side, but it returns NULL.
$data = json_decode($_POST['data'],true);
//$data = explode(",", $_POST['data']);
echo "data: " .$data;
var_dump($data); // no output
foreach($data as $d){
echo $d; // no output
}
You do not have to stringify an array in the javascript.
.ajax looks after all that.
pass
data: {newhours: newhour},
then you will get $_POST['newhours'] in the PHP code which will be the array you had in javascript.
In Ajax there is not "type" params, use "method".
Beside that everything should works, you might need to decode the json using json_decode($_POST['data']) on in your php file.
Hopes it helps !
Nic
Pass the array without JSON.stringify in ajax data post. And fetch the data in php file using $_POST['data'].
I just have tried below code and it working great.
<?php
if(isset($_POST['data'])){
print_r($_POST);exit;
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var newhour= [];
arrayNumbers = [['07:00','08:30'],['08:30','18:00','19:00']];
for (var i = 0; i < arrayNumbers.length; i++) {
newhour.push(arrayNumbers[i].toString().split(','));
console.log("each: " + newhour[i]);
// output: each: 07:00,08:30 each: 18:00,19:00
}
console.log("all: " + newhour); //output: all: 07:00,08:30,18:00,19:00
$.ajax({
type: "POST",
url: "abc.php",
data:{data: newhour},
cache: false,
success: function(data){
console.log(data);
}
});
});
</script>

Using two Ajax calls to post then retrieve data

I am currently trying to firstly post the name of the user that I am trying to retrieve from the database to my php code using ajax. Then in the success part of the call I am trying to make a function to retrieve data from a database which matches the name of the user the I previously sent to the page, however no data is coming back to the javascript code.
Here is the function with my ajax calls.
function checkPatientAnswers(event) {
window.open("../src/clinicreview.php", "_self");
var patientname = event.data.patientname;
var dataToSend = 'patientname=' + patientname;
var clinicquestions = getQuestionsForClinic();
var answers = [];
$.ajax({
type: "POST",
url: "../src/getselectedpatient.php",
data: dataToSend,
cache: false,
success: function(result) {
$.ajax({
url: "../src/getselectedpatient.php",
data: "",
dataType: "json",
success: function(row) {
answers = row;
console.log(row);
}
})
}
})
console.log(answers);
for (i in clinicquestions) {
$('#patientanswers').append("<h2>" + clinicquestions[i] + " = " + answers[i]);
}
$('#patientanswers').append("Patient Status = " + answers[answers.length - 1]);
}
And here is my PHP code:
<?php
session_start();
$con = mysql_connect("devweb2015.cis.strath.ac.uk","uname","mypass") or ('Failed to connect' . mysql_error());
$currentdb = mysql_select_db('yyb11163', $con) or die('Failed to connect' . mysql_error());
$patientname = $_POST['patientname'];
$_SESSION['patient'] = $POST['patientname'];
$data = array();
$query = mysql_query("SELECT question1, question2, question3, question4, patient_status FROM patient_info where real_name = '$patientname'");
$data = mysql_fetch_row($query);
echo json_encode($data);
mysql_close($con);
?>
jQuery
var dataToSend = {'patientname':patientname};
$.ajax({
type : "POST",
url : "../src/getselectedpatient.php",
data : dataToSend,
dataType : "json",
cache : false,
success: function(result) {
console.log(result);
}
})
PHP
<?php
session_start();
$_SESSION['patient'] = $POST['patientname'];
$con = mysql_connect("devweb2015.cis.strath.ac.uk","uname","mypass") or ('Failed to connect' . mysql_error());
$currentdb = mysql_select_db('yyb11163', $con) or die('Failed to connect' . mysql_error());
$query = mysql_query("SELECT question1, question2, question3, question4, patient_status FROM patient_info where real_name = '".$_POST['patientname']."'");
$data = mysql_fetch_row($query);
mysql_close($con);
echo json_encode($data);
?>
For the record, I do not condone the use of your mysql_* shenanigans. It has been completely REMOVED in PHP 7 and don't try telling me that you will ride PHP 5 till death do you part.
Secondly, you are 8000% open to SQL injection.
I understand that you are most likely just a student at a school in the UK but if your teacher/professor is OK with your code then you are not getting your money's worth.
You probably forgot to set data on the second call:
$.ajax({
url : "../src/getselectedpatient.php",
data : result,
or result.idor whatever.

Display json data from post jquery

Hello im using a login script with ajax and i want to callback and display my data
email and usernam to stock it in local storage.
i can get the data in json but i want to display this data in console.log
this is my codes
send_ajax.js
$(document).ready(function(e) {
$("#contactSubmitButton").click(function(){
var email = $("#contactEmailField").val();
var password = $("#contactNameField").val();
$.ajax({
type: "POST",
url: "http://hubafrica.co/webservices/get_user.php",
data: "email="+email+"&password="+password,
dataType: "json",
cache: false,
beforeSend: function(){ $("#contactSubmitButton").val('Chargement...');},
success: function(data) {
alert(data);
if(data)
{
iterateJson(data);
var url="http://hubafrica.co/webservices/get_user.php";
$.get(url,function(data){
// loop through the members here
$.each(json.data,function(i,dat){
console.log(dat.email);
window.localStorage.setItem("id", dat.id);
});
});
//window.location.href = "user_dashboard.html";
}else{
$("#formSuccessMessageWrap").fadeIn('slow');
$("#contactSubmitButton").val('se connecter');
}
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
});
});
script.php
<?php
header("Content-Type:application/json");
header('Access-Control-Allow-Origin: *');
include("../config/config.php");
$account=array();
if (isset($_POST["email"])){
$email = htmlspecialchars($_POST["email"]);
$pass = htmlspecialchars($_POST["password"]);
$sql = mysql_query('SELECT * FROM `b2b_user` where email="'.$email.'" and password="'.$pass.'"');
$num = mysql_num_rows($sql);
if($num > 0){
$row = mysql_fetch_assoc($sql);
$account['id'] = $row['id'];
$account['email'] = $row['email'];
echo '{"members":'.json_encode($account).'}';
}
}
?>
be for send response from backend you need to formate your data in json. Once you get in response you need to parseJSON()and the you can menuplate.
change here:use data.members to access data:
in your php construct like this:do not append string.
$account1= array('members'=>$account);
echo json_encode($account1);
script:
$.each(data.members,function(i,dat){
console.log(dat.email);
window.localStorage.setItem("id", dat.id);
});
You can either use
alert(JSON.stringify(data));
or
Console.log(JSON.stringify(data));
Following line of code turns an object/array in to a JSON text and stores that JSON text in a string.
JSON.stringify('/array variable here/')
Hope it helps.

Return data back to ajax call in jquery

I have a php code (no functions, just direct code) which queries a data base stores values
in an array and returns the array
<?php
//Query the database and fetch some results
$array["min_date"] = $arr['min(date)'];
$array["max_date"] = $arr['max(date)'];
$array['query'] = $query;
echo $arr['min(date)'].'</br>';
echo $arr['max(date)'];
return $array;
?>
this is my jquery ajax call
function date(){
$temp = $('select[name=people_name]').val();
$name = $temp;
$table = 'myTablename';
$url = "/myurl/php/get_date.php?name="+$name+"&table="+$table;
$.ajax({
type: "POST",
url: $url,
success: function(data) {
document.getElementById("from_date").value = data['min_date'];
document.getElementById("to_date").value = data['max_date'];
}
});
}
when I echo the php variables I do get the data which I want. but logging the jquery variables the give me result as undefined.
maybe the php return data is not fetches by ajax success(data)? or do I need to have a function in my php code? how do I fetch returned array in my jquery?
Thanks!
Try encoding the array in php side with json_encode().
In your PHP
//Query the database and fetch some results
$array["min_date"] = $arr['min(date)'];
$array["max_date"] = $arr['max(date)'];
$array['query'] = $query;
echo json_encode($array); //add this
In ajax call
function date(){
$temp = $('select[name=people_name]').val();
$name = $temp;
$table = 'myTablename';
$url = "/myurl/php/get_date.php?name="+$name+"&table="+$table;
$.ajax({
type: "POST",
dataType:'json', //add dataType
url: $url,
success: function(data) {
document.getElementById("from_date").value = data.min_date;
document.getElementById("to_date").value = data.max_date;
}
});
}

jQuery.ajax Why not access the item from php json_encode?

I do not understand because when the data were entered into the login are correct and I make this comparison response.success == "success" nothing happens, I check with firebug and the result is this:
Response
[{"ncontrol":"09680040","nombre":"Edgardo","apellidop":"Ramirez","apellidom":"Leon","tUser":"Admin","status":"success"}]
jQuery.ajax script to send data
// jQuery.ajax script to send json data to php script
var action = $("#formLogin").attr('action');
var login_data = {
ncontrol: $("#ncontrolLogin").val(),
password: $("#passwdLogin").val(),
is_ajax: 1
};
$.ajax({
type: "POST",
url: action,
data: login_data,
dataType: "json",
success: function(response)
{
**if(response.status == "success")** {
$("#status_msg").html("(+) Correct Login");
}
else {
$("#status_msg").html("(X) Error Login!");
}
}
});
return false;
And is PHP Script for processing variables from jQuery.ajax
$ncontrolForm = $_REQUEST['ncontrol'];
$passForm = $_REQUEST['password'];
$jsonResult = array();
$query = "SELECT * FROM users WHERE ncontrol = '$ncontrolForm' AND cve_user = SHA('$passForm')";
$result = mysqli_query($con, $query) or die (mysqli_error());
$num_row = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
if( $num_row >= 1 ) {
$_SESSION['n_control'] = $row['ncontrol'];
$_SESSION['t_user'] = $row['tUser'];
$jsonResult[] = array (
'ncontrol' => $row['ncontrol'],
'nombre' => $row['nombre'],
'apellidop' => $row['apellidop'],
'apellidom' => $row['apellidom'],
'tUser' => $row['tUser'],
'status' => 'success',
);
header('Content-Type: application/json');
echo json_encode($jsonResult);
}
You have an array, so do it this way:
if(response[0].status == "success") {
The object is the first item in the array.
EDIT:
Looking more closely at your PHP, it looks like you might be intending to loop through several rows in your query response and add them to your $jsonResult. Am I seeing it right?

Categories

Resources