I'm implementing a web and I need to use AJAX+JQuery to complete some fields without recharging the page. I test it and it works correctly but when I tried to use a real JSON (created by MySQL) I'm not be able to parse it.
The format of JSON is this:
[
{
"ID":"5847"
},
{
"Usuari":"admin"
},
{
"Nom":"admin"
},
{
"Cognom1":null
},
{
"Cognom2":null
},
{
"Tipus":"admin"
},
{
"Progres":"0"
}
]
And the AJAX code is this:
$(document).ready(function(){
$("#botoBuscar").click(function(){
$.ajax({url: "http://192.168.1.39/web/api/buscarUser.php?user="+ $("#userInput").val(), success: function(data){
var obj = $.parseJSON(data);
$("#id").val(obj[0]['ID']);
$("#user").val(obj[0]['Usuari']);
$("#nom").val(obj[0]['Nom']);
$("#cognom1").val(obj[0]['Cognom1']);
$("#cognom2").val(obj[0]['Cognom2']);
$("#tipus").val(obj[0]['Tipus']);
$("#progres").val(obj[0]['Progres']);
}});
});
});
If I print only the var "data", it prints correctly the full JSON, but if I try to use data['ID'] or data[0]['ID'], etc.. it doesn't print anything. What I'm doing wrong? Thanks!
If you need, the code to generate JSON is this (PHP):
$sql = "SELECT id, user, nom, cognom1, cognom2, tipus, progres FROM users WHERE user='".$_GET['user']."'";
$result = $db->query($sql);
$row = $result->fetch_array(MYSQLI_ASSOC);
$id = $row['id'];
$user = $row['user'];
$nom = $row['nom'];
$c1 = $row['cognom1'];
$c2 = $row['cognom2'];
$tipus = $row['tipus'];
$progres = $row['progres'];
//build the JSON array for return
$json = array(array('ID' => $id),
array('Usuari' => $user),
array('Nom' => $nom),
array('Cognom1' => $c1),
array('Cognom2' => $c2),
array('Tipus' => $tipus),
array('Progres' => $progres));
echo json_encode($json);
mysqli_close($db);
Thanks!
I found the solution to get the values correctly. The code is the following one:
$(document).ready(function(){
$("#botoBuscar").click(function(){
$.ajax({url: "http://XX.com/api/buscarUser.php?user="+ $("#userInput").val(), success: function(data){
var obj = $.parseJSON(data);
$("#id").val(obj[0]['ID']);
$("#user").val(obj[1]['Usuari']);
$("#nom").val(obj[2]['Nom']);
$("#cognom1").val(obj[3]['Cognom1']);
$("#cognom2").val(obj[4]['Cognom2']);
$("#tipus").val(obj[5]['Tipus']);
$("#progres").val(obj[6]['Progres']);
}});
});
});
Related
I'm trying to send a username from the view to the controller through Ajax like this :
$('#exampleFormControlSelect1').change(function(){
var username =$('#exampleFormControlSelect1').val();
$.ajax({
type: 'POST',
dataType: "json",
url: "Panier/loadPanier",
data: {username: username},
success: function(result){
$("#tbodyid").empty();
var data1 = JSON.parse(result);
console.log(data1) ;
},
});
});
and I try to use the sent value to do some work:
public function loadPanier()
{
$res = [];
$username = $this->input->post('username');
$panier_data = $this->model_panier->getPanierData($username);
foreach ($panier_data as $k => $v) {
$idPiece = $v['idPiece'];
$qte = $v['quantity'];
$piece_data = (array)$this->model_catalogue->getDetail($idPiece);
$price = (int)$piece_data['Unit Price'];
$montant = $qte * $price;
array_push($res, array(
'idPiece' => $idPiece,
'Description' => $piece_data['Description'],
'qte' => $qte,
'prix HT' => round($piece_data['Unit Price'], 3),
'montant' => $montant
));
}
return $res;
}
In my URL I'm getting this error :
Invalid argument supplied for foreach()
but here's what I'm noticing by doing var_dump($username):
C:\wamp64\www\PortalDealer\application\controllers\Panier.php:66:null
So my data is not passing!
Can you help me with this?
EDIT
showcase the result of this part of the code :
var_dump($_REQUEST);
$res = [];
$username = $this->input->post('username');
var_dump($username);
$panier_data = $this->model_panier->getPanierData($username);
var_dump($panier_data);
The below code should send your data to Panier/loadPanier/.
$('#exampleFormControlSelect1').change(function(){
var val1 =$('#exampleFormControlSelect1').val();
$.ajax({
method: "POST",
url: "Panier/loadPanier/",
data: { username: val1}
}).done(function( result ) {
$("#tbodyid").empty();
var data1 = JSON.parse(result);
console.log(data1) ;
});
});
You were seeing null every time you did var_dump() because you were trying to load the page independently. The page will only give you the POST value if you are going to the page thru the form, in this case, the form is javascript. When you load a page with POST method in javascript, the response is sent to the same page with ajax so you can work with your code without having to refresh the page.
Also: You cannot return data to javascript. You have to print it out to client side so that your javascript's JSON parser can read it. Therefore, instead of return $res; :
echo json_encode($res);
I have tried different ways to make this work but it is still not working. data[0].urgency is undefined. I tried to stringify data but a bunch of \n in between the result (see below).
Thank you in advance.
My ajax code:
function ajaxCall() {
$.ajax({
type: "POST",
url: "../nav/post_receiver.php",
success: function(data) {
console.log(data.length);
console.log(data[0].urgency);
}
});
}
My PHP code:
<?php
session_start();
ob_start();
require_once('../../mysqlConnector/mysql_connect.php');
$results = array();
$query="SELECT COUNT(initID) AS count, urgency, crime, initID, TIMESTAMPDIFF( minute,dateanalyzed,NOW()) AS minuteDiff FROM initialanalysis WHERE commanderR='0' AND stationID='{$_SESSION['stationID']}';";
$result=mysqli_query($dbc,$query);
while ($row = $result->fetch_assoc()){
$count = $row['count'];
$urgency = $row['urgency'];
$crime = $row['crime'];
$initID = $row['initID'];
$minuteDiff = $row['minuteDiff'];
$results[] = array("count" => $count, "urgency" => $urgency, "crime" => $crime, "initID" => $initID, "minuteDiff" => $minuteDiff);
}
echo json_encode($results);
?>
Result of PHP:
[{"count":"9","urgency":"Low","crime":"Firearm","initID":"6","minuteDiff":"4743"}]
I think the result is in wrong format? I'm not sure.
This is the result of console.log(data), there is a comment tag of html and I don't know why:
<!-- -->
[{"count":"9","urgency":"Low","crime":"Firearm","initID":"6","minuteDiff":"4761"}]
Use a JSON parser for validate the json response like JSON.parse
function ValidateJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
Update your ajax call like this
function ajaxCall() {
$.ajax({
type: "POST",
url: "../nav/post_receiver.php",
success: function(data) {
data= jQuery.parseJSON(data);
console.log(data.length);
console.log(data[0].urgency);
}
});
}
I am trying to create a validation to check if my data already exist or not using Ajax. It's works, but now I want to add JSON inside my Ajax php file and retrieve the array inside of the JSON, unfortunately it doesn't work as expected.
Take a look at my JQuery below :
$("#button").click(function(e) {
e.preventDefault();
var tempcode = $('#someobject').val();
$.ajax({
method:"POST",
dataType: "text",
url:'example.php',
data:{
Code: tempcode
},
success:function(data){
var my = JSON.parse(data);
alert(my.Title);
}
});
});
And below is example.php :
$AJAXCode = $_POST['Code'];
$myObj = array();
$strSQL = mysql_query("select * from sometable where Code ='$AJAXCode'");
$check = mysql_num_rows($strSQL);
if ($AJAXCode == NULL) {
$myObj->Title= "Choose Something";
$myObj->Total = $check;
$myJSON = json_encode($myObj);
echo $myJSON;
} else {
if ($check != 0) {
$myObj->Title= "Already Exist !";
$myObj->Total = $check;
$myJSON = json_encode($myObj);
echo $myJSON;
} else {
$myObj->Title= "You are good !!!";;
$myObj->Total = $check;
$myJSON = json_encode($myObj);
echo $myJSON;
}
}
As you can see at my JQuery scripts, I am trying to call "Title" inside my JSON array, but it doesn't work. Am I missing something ?
This is the result in Console.log, no error show up just this:
Firstly, you initialize your object the wrong way. Use instead of $myObj = array(); one of the following:
$myObj = (object) array();
or
$myObj = new StdClass();
For more information and more ways to create your object, look up this link.
Next, change the dataType attribute to:
dataType: "json"
in order to tell your script that your PHP response is encoded as JSON. You can use now your response the regular way, with JSON.parse(), try:
console.log(JSON.parse(data));
Replace Below Code :
$("#button").click(function(e) {
e.preventDefault();
var tempcode = $('#someobject').val();
$.ajax({
method:"POST",
dataType: "json",
url:'example.php',
data:{
Code: tempkode
},
success:function(data){
console.log(data.Title); // Example
}
});
});
Change variable tempkode to tempcode in data
I'm facing a strange problem for the last 10 hours and its really very annoying. The problem is with jquery printing json data from php. The php script is running fine, but when the ajax call returns in complete: event i'm not getting any valid otput.
here is the jquery code::
list_choice = "A";
content_choice = "Artists"; //globals to store default value
$(document).ready(function() {
$('.list-nav > a').click(function() {
var ltext = $(this).text();
list_choice = ltext;
console.log(ltext+" <------> ");
$.ajax({
url: 'retrieveFileFront.php',
data: {type: content_choice, navtext: list_choice},
type: 'POST',
dataType: 'json',
complete: function(data) {
console.log(data['message']['Album_Name']);
}
});
return false;
});
});
i had to use complete: event as success: didn't worked at all. Atleast i'm getting some sort of output from the complete: event, although its giving undefined or [object][Object] which is totally ridiculous.
here is the retrieveFileFront.php:
<?php
require './retrieveFiles.php';
$type = $_POST['type'];
$nav_text = $_POST['navtext'];
$ret_files = new retrieveFiles($type, $nav_text);
$data = $ret_files->retFiles();
if ($data['success'] == FALSE) {
$data = array('success' => FALSE, 'message' => 'Sorry an Error has occured');
echo json_encode($data);
} else {
echo json_encode($data);
}
?>
and here is the /retrieveFiles.php
<?php
class retrieveFiles {
public $content_type;
public $list_nav;
public $connection;
public $result;
public $result_obj;
public $tags_array;
public $query;
public $row;
public function __construct($type, $nav_text) {
$this->content_type = $type;
$this->list_nav = $nav_text;
}
public function retFiles() {
#$this->connection = new mysqli('localhost', 'usr', 'pass', 'data');
if(!$this->connection) {
die("Sorry Database connection could not be made please try again later. Sorry for the inconvenience..");
}
if ($this->content_type == "Artists") {
$this->query = "SELECT album_name, album_art FROM album_dummy NATURAL JOIN album_images_dummy WHERE artist_name LIKE '$this->list_nav%'";
try {
$this->result = $this->connection->query($this->query);
$this->row = $this->result->fetch_row();
if (isset($this->row[0]) && isset($this->row[1])) {
$this->tags_array = array("success" => true, "message" => array("Album_Name" => $this->row[0], "Album_Art" => $this->row[1]));
return $this->tags_array;
}
} catch (Exception $e) {
echo 'Sorry an Error has occurred'.$e;
return false;
}
}
}
}
?>
I'm getting a 200 response in console in firebug, which indicates that its running okay.
<!DOCTYPE HTML>
{"success":true,"message":{"Album_Name":"Streetcleaner","Album_Art":"\/var\/www\/html\/MusicLibrary\/Musics\/1989 - Streetcleaner\/folder.jpg"}}
Now this is making me even more confused as i can see that the json is formatted properly. Please provide any sort of suggestion on how to solve this problem.
Thanks in advance..
JSON encoded data is usually not sent like
data['message']['Album_Name']);
But rather like:
data.message.Album_Name;
You're calling your results the wrong way. These are not associative arrays anymore but are now objects, as the name JSON (JavaScript Object Notation) suggests.
You need to parse the json response using
data = $.parseJSON(data)
Use success event instead of complete in ajax and we can able to parse JSON encoded data in javascript/jQuery by using JSON.parse
well after a long period of trauma, i finally found a solution, turns out that i needed to parse the response text and then access the objects, individually.
Here is the working code
list_choice = "A";
content_choice = "Artists"; //globals to store default value
$(document).ready(function() {
$('.list-nav > a').click(function() {
var ltext = $(this).text();
list_choice = ltext;
console.log(ltext+" <------> ");
$('#loading').css('visibility', 'visible');
$.ajax({
url: 'retrieveFileFront.php',
data: {type: content_choice, navtext: list_choice},
type: 'POST'
dataType: 'json',
complete: function(data) {
var res = data.responseText;
res = res.replace(/<!DOCTYPE HTML>/g, "");
res = res.trim();
console.log(res);
var arr = JSON.parse("[" + res +"]"); //needed to parse JSON object into arrays
console.log(arr[0].message.Album_Name);
console.log(arr[0].message.Album_Art);
$('#loading').css('visibility','hidden');
}
});
return false;
});
This works fine and gives the desired response. Anyways thanks for the help, guys.
I created a php script that generates the json response
this is the example of the output:
[[],{"idgps_unit":"2","lat":"40","lon":"40","name":"ML350","notes":"Andrew","dt":"2012-10-29 19:43:09","serial":"3602152","speed":"44","odometer":"208.49"},{"idgps_unit":"1","lat":"42","lon":"39","name":"unit1","notes":"fake unit 1","dt":"2012-10-18 18:16:37","serial":"12345","speed":"0","odometer":"0.16"}]
This is how I form the response in PHP:
$data[] = array();
foreach ($list->arrayList as $key => $value) {
$unit = new Unit();
$unit = $value;
//create array for json output
$data[] = array('idgps_unit' => $unit->idgps_unit, 'lat' => $unit->lat,
'lon' => $unit->lon, 'name' => $unit->name, 'notes' => $unit->notes,
'dt' => $unit->dt, 'serial' => $unit->serial, 'speed' => $unit->speed,
'odometer' => $unit->odometer);
}
echo json_encode($data);
Now, in JS I did this:
function getCheckedUnits() {
jQuery(function($) {
$.ajax( {
url : "json.php?action=get",
type : "GET",
success : function(data) {
var jsonData = JSON.parse(data);
///PARSE VALUES AND SUBMIT TO A FUNCTION :: START
var C_longitude = 0;
var C_name = 0;
var C_idgps_unit = 0;
var C_serial = 0;
var C_speed= 0;
var C_notes= 0;
var C_dt = 0;
var C_time = 0;
var C_odometer = 0;
initialize(C_longitude,C_name,C_idgps_unit, C_serial,C_speed, C_notes, C_dt, C_time, C_odometer);
///PARSE VALUES AND SUBMIT TO A FUNCTION :: END
}
});
});
}
I need to parse the json reponce into values
Assuming that JSON.parse(data) only gets the associative array in the JSON response, you should be able to get the values in the JSON data like so:
var i = 1;
var C_longitude = jsonData[i]["lon"];
var C_name = jsonData[i]["name"];
Assuming that the first empty array is not removed by JSON.parse(), i = 1 would get the first batch of data and i = 2 would get the second.
The parsed JSON behaves the same way as if it was defined in JavaScript
If you put dataType: "json" in the ajax settings it will return you a json object than you don't need to parse it again. So this would look like:
function getCheckedUnits() {
jQuery(function($) {
$.ajax( {
url : "json.php?action=get",
type : "GET",
dataType: "json"
success : function(data) {
}
});
});
}
However you could also use your own option but than just use the parseJSON function so var jsonData = jQuery.parseJSON(data);