Not able to retrieve json data in Ajax call from php - php

I'm able to convert my data into JSON format in php and while sending that data to Ajax call, I'm not able to get the details. In fact first the length of Json data shows 87, where it is actually 2.
My php code is
// credentials of MySql database.
$username = "root";
$password = "admin";
$hostname = "localhost";
$data = array();
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("Angular",$dbhandle)
or die("Could not select Angular");
//execute the SQL query and return records
$result = mysql_query("SELECT id,name,password FROM User");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
$id = $row{'id'};
$name = $row{'name'};
$password = $row{'password'};
$data[] = array('id' => $id, 'name' => $name, 'password' => $password);
}
echo json_encode($data);
Output it shows is
[
{
"id": "1",
"name": "Rafael",
"password": "rafael"
},
{
"id": "2",
"name": "Nadal",
"password": "nadal"
}
]
My Ajax call is
$.ajax({
type: "GET",
url: "ListUsers.php",
success: function (dataCheck) {
console.log(dataCheck.length);
for(index in dataCheck) {
/*
console.log("Id:"+dataCheck[index].id);
console.log("Name:"+dataCheck[index].name);
console.log("Password:"+dataCheck[index].password);*/
}
},
error: function () {
alert("Error");
}
});
Please let me know if there is any thing wrong in my code

set the dataType to 'JSON' and you are all set:
$.ajax({
type: "GET",
url: "ListUsers.php",
success: function (dataCheck) {
/* ... */
},
error: function () {
alert("Error");
},
dataType: 'JSON'
});

The dataCheck inside success() is a string. You must convert it like this:
var data = $.parseJSON(dataCheck);
Now you can use it in you for loop like
data.forEach(function(item){
console.log(item.name)
});

This should be your Ajax call:
$.ajax({
type: "GET",
url: "ListUsers.php",
success: function (dataCheck) {
var data = $.parseJSON(dataCheck);
$(data).each(function(item){
console.log(item.name);
});
},
error: function () {
alert("Error");
}
});

Related

Using JQuery AJAX and php to fetch data to a mysql database

Im trying to insert data into my database with AJAX but dont working.
I can verify that im connected to the database but when i click it doesnt insert the data. thanks
with a click function i take the 2 parameter that i wanna insert in my database.
$( "#q_answer1" ).click(function () {
var q_no = $("#q_no").val();
var main_no = $("#total_no").val();
$.ajax({
url: "server.php",
type: "post",
async: false,
data: {
"done": 1,
"username": q_no,
"comment": main_no
},
success: function(){
$("#q_no").val('');
$("#total_no").val('');
}
});
});
And here is the php file, first connect to the ddbb and insert the 2 values with the mysql_query.
<?php
include("dbh.php");
if (isset($_POST['done'])) {
$q_no = mysql_escape_string($_POST['username']);
$total_no = mysql_escape_string($_POST['comment']);
mysql_query("INSERT INTO variables(id, names) VALUES('{$q_no}', '{$total_no}')");
exit();
}
?>
html is like this:
<div id="total_no">1</div>
<div id="q_answer1" class="btn left_b">yes</div>
I think you should use PDO, to connect to the database instead of the old driver, which PHP no longer supports. with PDO you can use prepared statements to prevent sql injections
PDO tutorial
filter_var() Constants
dbh.php
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = 'db';
try {
$db = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
exit($e->getMessage());
}
?>
serve.php
<?php
include("dbh.php");
if (isset($_POST['done'])) {
$q_no = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$total_no = filter_var($_POST['comment'], FILTER_SANITIZE_STRING);
try {
$stmt = $db->prepare("INSERT INTO variables(id, names) VALUES(?, ?)");
$stmt->execute(array($q_no, $total_no));
echo json_encode(["message" => "success"]); // sends success response to front-end
} catch (\Exception $e) {
echo json_encode(["message" => $e->getMessage() ]); // sends error response to front-end
}
}
?>
in your ajax check if the data was inserted or not.
$("#q_answer1").click(function() {
var q_no = $("#q_no").val();
var main_no = $("#total_no").val();
$.ajax({
url: "file.php",
type: "post",
async: false,
data: {
"done": 1,
"username": q_no,
"comment": main_no
},
success: function(data) {
const respose = JSON.parse(data);
if (respose.message === 'success') { // data was inserted
$("#q_no").val('');
$("#total_no").val('');
}else {
alert(respose.message); // some error has occured
}
}
});
});
You have to take value of div as mentioned below,
var q_no = $("#q_no").text();
var main_no = $("#total_no").text();
Pass data in key-value Pair, After pass first key-value data concate other data with & sign key.
$( "#q_answer1" ).click(function () {
var q_no = $("#q_no").val();
var main_no = $("#total_no").val();
$.ajax({
url: "server.php",
type: "post",
async: false,
data: 'done=' + 1 + '&username=' + q_no + '&comment=' + main_no,
success: function(){
$("#q_no").val('');
$("#total_no").val('');
}
});
});
You can't use val() on div. Try using text() and then check if your server.php is getting these value.
Thanks
You have typo error in jquery
$qAnswer1.click(function () {
Should be
$('#q_answer1').click(function () {
You can try following to test
$( "#q_answer1" ).click(function() {
alert( "Handler for .click() called." );
});
Include the jquery at the top of your page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Full working code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="total_no">1</div>
<div id="q_answer1" class="btn left_b">yes</div>
<script type="text/javascript">
$( "#q_answer1" ).click(function () {
var q_no = $("#q_no").val();
var main_no = $("#total_no").val();
$.ajax({
url: "ajax.php",
type: "post",
async: false,
data: {
"done": 1,
"username": q_no,
"comment": main_no
},
success: function(){
$("#q_no").val('');
$("#total_no").val('');
}
});
});
</script>
in your PHP file try to print $_POST to see its working.

Why can't I access the JSon data?

I'm trying to get the count of a variable using ajax but it keeps printing fail everytime
here is the php file that works perfectly when I test it
<?php
$conn= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
mysqli_select_db($conn,"bdpfe") or die ("no database");
$rech=$_GET['q'];
$sql=mysqli_query($conn,"select count(id_com) as nbr from commentaire where id_pub like '".$rech."' ");
$response = array();
$nbrs = array();
$result=$sql;
while($row=mysqli_fetch_array($result))
{
$nbr=$row['nbr'];
$nbrs[] = array('nbr'=>$nbr);
}
$response['nbrs'] = $nbrs;
echo "mycallbackcom(".json_encode($response).")";
?>
and here is the ajax call using jsonp
(function getnbr() {
$.ajax({
type : 'GET',
url : 'http://127.0.0.1:800/test/count_com.php?callback=?&q='+$('#idpub').val() ,
jsonpCallback: 'mycallbackcom',
dataType: 'jsonp',
contentType: "application/json",
success: function (data) {
alert("succes");
},
error: function () {
alert("fail");
}
});
})(jQuery);
and the callback function is empty for now:
function mycallbackcom()
{}
it keeps printing fail every time.
Try only returning the JSON. You have specified this as your expected return dataType.
echo json_encode($response);
Then handle the response:
(function getnbr() {
$.ajax({
type : 'GET',
url : 'http://127.0.0.1:800/test/count_com.php?callback=?&q='+$('#idpub').val() ,
jsonpCallback: 'mycallbackcom',
dataType: 'jsonp',
contentType: "application/json",
success: function (data) {
mycallbackcom(data)
},
error: function () {
alert("fail");
}
});
});
You need to parse the $_GET variable..
$data = json_decode($_GET['q']);
function mycallback($data) {
//Do something
}
return mycallback($data);

AJAX call returning empty object from json_encode

I'm making an AJAX call to a fairly simple PHP function. The response should be a JSON object to be manipulated, but my response is always an empty object.
Relevant Code:
index.html's AJAX Call:
$( function() {
$('#dates').on('submit', function (e) {
var start_time = new Date().getTime();
e.preventDefault();
var submitData = $('#dates').serialize();
console.log(submitData);
$.ajax({
type:'POST',
url:'inflow.php',
data:$('#dates').serialize(),
dataType: 'json',
beforeSend: function(){
$('#loading').show();
},
success: function(data) {
console.log(data);
$('#loading').hide();
},
error:function(xhr, desc, err){
alert('You tried to send an AJAX request, but something went wrong.\n Please Contact the NASR WebDev Team');
console.log(xhr);
console.log("Details: " + desc +"\nError: "+ err);
}
});
});
});
inflow.php's array creation and echo:
<?php
$msqlStart = $_POST['start_date'];
$msqlEnd = $_POST['end_date'];
$inflowQuery=
"SELECT
COUNT,
QUEUE_ID,
QUEUE_GROUP,
INFLOW_DATE,
LINE_OF_BUSINESS
FROM
ticket_inflow.inflow
WHERE
ROUTE_STATUS = 'Inflow'
AND inflow_date between ? and ?";
$connect = new mysqli($host, $user, $password, $database);
if ($connect->connect_error){
die("Failed to Connect:.".$connect->connect_errno.": ".$connect->connect_error);
}
if(!($statment = $connect->prepare($inflowQuery))){
die('Error in Preparation Error Number:%d Error: %s');
}
if(!$statment->bind_param('ss', $msqlStart, $msqlEnd)){
die ('Error in Binding');
}
if(!$statment->execute()){
die('Error In Execution');
}
$statment->bind_result($inflowCount, $inflowQueue, $inflowQG, $inflowDate, $inflowLOB);
$a_json = array();
$jsonRow = array();
While($statment->fetch()){
$UID = 0;
$jsonRow['UID'] = $UID++;
$jsonRow['count'] = utf8_encode($inflowCount);
$jsonRow['inflow_date'] = utf8_encode($inflowDate);
$jsonRow['queue'] = utf8_encode($inflowQueue);
$jsonRow['queue_group'] = utf8_encode($inflowQG);
$jsonRow['lob'] = utf8_encode($inflowLOB);
array_push($a_json, $jsonRow);
}
$jsonReturn = json_encode($a_json);
echo $jsonReturn;
?>
If I go directly to inflow.php and pass it parameter's identical to what the page passes it, I get what appears to be a nice JSON object, however when I look at the response Chrome Developer's Tools I get:
[]
And nothing more.
You are sending form data, not json;
$.ajax({
type:'POST',
url:'inflow.php',
data:$('#dates').serialize(),
//contentType: "application/json",<-- remove this
dataType: 'json',

How to extract variable with jquery in php from json?

I wish to extract one variable by one variable from my json file. My goal is to use this variable in php, to be able to do mysql query for exemple.
So my json file is here: pages/getRank-classic.php?idstart=0
[
{"rank":1,"id":"111","site_name":"test1","site_vip":"No","boost":"0","site_banner":"test.png","site_banner_wallrank":"","site_pointstotaux":"5044","site_motclef1":"Pvp\/Fac","site_motclef2":"Skyblock","site_motclef3":"Cr\u00e9atif","site_motclef4":"Hunger-Games","site_motclef5":"SKywars\/Mini-Gam","site_presentationvideo":"3TGjebmNOfs"},
{"rank":2,"id":"222","site_name":"test2","site_vip":"No","boost":"0","site_banner":"test.jpg","site_banner_wallrank":"","site_pointstotaux":"4114","site_motclef1":"hunger","site_motclef2":"games","site_motclef3":"pvp","site_motclef4":"survival","site_motclef5":null,"site_presentationvideo":"3TGjebmNOfs"}
]
I am trying to use it in include like:
<script type="text/javascript" >
$.ajax({
type: 'POST',
dataType: 'json',
url: '/pages/getRank-classic.php?idstart=0',
data: data,
cache: false,
success: function(test) {
alert(test.id);
alert(test.rank);
}
});
</script>
So how I can do it please?
Since it is an array of json, you need to specify the index too.
test[0].id
Also you can iterate through the object using this way,
var data = [{
"rank": 1,
"id": "111",
"site_name": "test1",
"site_vip": "No",
"boost": "0",
"site_banner": "test.png",
"site_banner_wallrank": "",
"site_pointstotaux": "5044",
"site_motclef1": "Pvp/Fac",
"site_motclef2": "Skyblock",
"site_motclef3": "Cr\u00e9atif",
"site_motclef4": "Hunger-Games",
"site_motclef5": "SKywars/Mini-Gam",
"site_presentationvideo": "3TGjebmNOfs"
}, {
"rank": 2,
"id": "222",
"site_name": "test2",
"site_vip": "No",
"boost": "0",
"site_banner": "test.jpg",
"site_banner_wallrank": "",
"site_pointstotaux": "4114",
"site_motclef1": "hunger",
"site_motclef2": "games",
"site_motclef3": "pvp",
"site_motclef4": "survival",
"site_motclef5": null,
"site_presentationvideo": "3TGjebmNOfs"
}];
$(data).each(function () {
alert(this.id);
});
You can fetch the json using the ajax, then in the success event, put this code like,
$.ajax({
type: 'POST',
dataType: 'json',
url: '/pages/getRank-classic.php?idstart=0',
data: data,
cache: false,
success: function(test) {
$(test).each(function () {
alert(this.id);
});
}
});
I finally used php like that =>
<?php
$jsonlink = '/pages/getRank-classic.php?idstart=0';
$json = file_get_contents($jsonlink);
$link = mysql_connect('localhost', 'database', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('database', $link);
$result = json_decode($json);
foreach($result as $key => $value) {
if($value) {
mysql_query("UPDATE `database`.`sites` SET `site_rank` = '$value->rank' WHERE `sites`.`site_id` = '$value->id'");
}
mysql_close;
}
?>

AJAX not sending data to PHP

In this script, data gets sent, but it does not send the updated value of the variable. Hard-coded data gets sent as expected. How can I solve this or go around it?
username = ''; // supposedly these variables are global
tree_name = ''; // I also tried plugging in- $('#username').data("username") -directly.. same results.
$(function() {
username = $('#username').data("username"); // updating value
tree_name = $('#tree_name').data("tree_name"); // idem....
});
var options = {
type: "POST",
url: "/decision/p_tree2/",
data: {
username: username, // this should send the data
tree_name: tree_nam // ...
},
success: function(response) {
console.log(response);
}
};
$("form").ajaxForm(options);
PHP:
public function p_tree2 (){
$data = Array();
$data['username'] = $_POST['username'];
$data['tree_name'] = $_POST['tree_name'];
echo print_r($data); // result: both $data['username'] and $data['tree_name'] equal ""
}
Reformat your code like following. Also correct the typo you have in tree_name in data. You used tree_nam.
$(function() {
var username, tree_name,options;
username = $('#username').data("username");
tree_name = $('#tree_name').data("tree_name");
console.log(username); //make sure
console.log(tree_name); // console outputs what you need to pass
options = {
type: "POST",
url: "/decision/p_tree2/",
data: {
username: username, // this should send the data
tree_name: tree_name // ***correct this typo***
},
success: function(response) {
console.log(response);
}
};
$("form").ajaxForm(options);
});

Categories