here is my PHP code
$response = array();
$user1 = array();
$user1['name'] = 'Tom';
$user1['age'] = '13';
$user2 = array();
$user2['name'] = 'Jack';
$user2['age'] = '20';
$response[] = $user1;
$response[] = $user2;
echo json_encode($response);
and here is my .html file that use jquery to get data from PHP file like
$.post('file.php', {userid : '1234'}, function(data){
alert(data) //problem here
}, 'json');
the problem is how to get user1's name after I use $.post in that code.
Thank you :)
Because your user arrays are associative, they are being translated into json objects, not arrays.
access them with data[0].name
I think you need JSON.parse
var response = JSON.parse(data)
Now response is your JSON object that has all the data.
Related
I am using axios.get to retrieve the element I want, and it return successfully with json data showen below:
It gooes fine, with [ and { perfectly allocated. Here is my duty, I want to retrieve one column element (this json only has one templete), let's say OrederReferencePreffix, it returns undefined instead of [[\t ... I've try these declaration below:
var attempt_one= json_only[0].InvoiceNumberPreffix; //undefined
var attempt_two= response.data.InvoiceNumberPreffix; //undefined
var attempt_three= response.data[0].InvoiceNumberPreffix; //undefined
var attempt_four= json_only.InvoiceNumberPreffix; //undefined
The php returns the correct one like above, and in js
axios.get('http://localhost/backend/get_templete.php', {
params: {
clciked_cpy: cpy
}
})
.then(function(response) { //attempt above, need to put my ans in here; tried
var json_only = pre_cpy_cut.exec(response.data.toString());
console.log("=]" + json_only);
} #reponse.data
in case you need, php:
$json = array();
while($row = mysqli_fetch_assoc($result)) {
$json[] = $row;
}
mysqli_free_result($result);
echo json_encode( $json, JSON_UNESCAPED_SLASHES ); //return as same as the picture above
#response.data already gives me json and stuff for me already. Why it still not return the column data I want? How to do that.
I think you could gave more informations about your code, but for what I understood you aren't manipulating the JSON correctly. You need to parse the data retrieved by the axios request. Try:
axios.get('http://localhost/backend/get_templete.php', {
params: {
clciked_cpy: cpy
}
})
.then(function(response) {
const parsedResponse = JSON.parse(response.data)
// now you can access correctly the response data.
console.log(parsedResponse.anyVariableYouWant)
})
This is my php codes to received and insert the data into the online database. I am very sure i these fabricated codes will not work but with you education and help i will get. thank you. insertdata.php
<?php
include 'connect.php';
include 'function.php';
//Create Object for DB_Functions clas
$db = new DB_Functions();
//Get JSON posted by Android Application
$json = $_POST["usersJSON"];
//Remove Slashes
if (get_magic_quotes_gpc()){
$json = stripslashes($json);
}
//Decode JSON into an Array
$data = json_decode($json);
//Util arrays to create response JSON
$a=array();
$b=array();
//Loop through an Array and insert data read from JSON into MySQL DB
for($i=0; $i<count($data) ; $i++)
{
//Store User into MySQL DB
$res = $db->storedata($data[$i]->callid,$data[$i]->pid,$data[$i]->pname,$data[$i]->medstay_amt,$data[$i]->med_amt,$data[$i]->imv_amt,$data[$i]->othermc_amt,$data[$i]->emtrans_amt,$data[$i]->outpden_am,$data[$i]->otherps_amt,$data[$i]->herb_amt,$data[$i]->medban_amt,$data[$i]->othermp_amt,$data[$i]->assist_amt,$data[$i]->code,$data[$i]->date);
//Based on inserttion, create JSON response
if($res){
$b["id"] = $data[$i]->pid;
$b["status"] = 'yes';
array_push($a,$b);
}else{
$b["id"] = $data[$i]->pid;
$b["status"] = 'no';
array_push($a,$b);
}
}
//Post JSON response back to Android Application
echo json_encode($a);
?>
You can do something like this:
$(document).on("click", ".BTN_Submit_Task", function () {
var AllTasks = ls.GetAllArr(LocalstorageName);
var id = $(this).attr("rec_id");
var result = $.grep(AllTasks, function(e){ return e.rec_id === id; });
$.ajax({
url: "url/of/php/file.php",
type: 'post',
dataType: 'json',
data: {usersJSON: [result]},
done: function(response) {
console.log(response);
}
});
});
And BTW you probably want to make AllTasks variable global and assign it once, then you can call it from both functions.
I'm having a little trouble figuring out how to fix this error I'm getting. My code is as follows.
It all starts with a AJAX request whenever the user moves their mouse on the webpage.
$('body').mouseover(function() {
$.ajax({
url: '/core/home.php',
data: {action: 'refresh'},
type: 'post',
Next, the PHP file (home.php) executes a couple methods to get all the needed data and sends it back to AJAX Request.
require_once 'init.php';
if(isset($_POST['action']) && !empty($_POST['action'])) {
// Home Class
$h = new Home();
// Method to count all "vacs"
$h->getVacs('id');
$vacs = $h->count();
// Method to count all "users"
$h->getUsers('id');
$users = $h->count();
// Create array to store all data
$arr = array();
$arr[] = $vacs;
$arr[] = $users;
// Use JSON to send the array back
json_encode($arr);
return $arr;
}
Once the AJAX Request receives a success, the following executes
success: function(output) {
obj = JSON.parse(output);
// Separate the parts of the JSON string
vacs = obj[0];
users = obj[1];
// Show the result at the correct position on the webpage
$('#vac_num').html(vacs);
if(vacs == 1) $('#vac_txt').html('is'); else $('#vac_txt').html('zijn');
$('#users_num').html(users);
if(users == 1) $('#users_txt').html('is'); else $('#users_txt').html('zijn');
}
});
});
Unfortunately this code results into an error: Unexpected end of JSON input.
Any help is much appreciated.
Rather than returning variable you need to echo it
require_once 'init.php';
if(isset($_POST['action']) && !empty($_POST['action'])) {
// Home Class
$h = new Home();
// Method to count all "vacs"
$h->getVacs('id');
$vacs = $h->count();
// Method to count all "users"
$h->getUsers('id');
$users = $h->count();
// Create array to store all data
$arr = array();
$arr[] = $vacs;
$arr[] = $users;
// Use JSON to send the array back
echo json_encode($arr);
}
I hava data structure like this which is then returned to another file with AJAX:
$data = array();
$data['message'] = "You are searching: $domain!";
$data['domain:name'] = "domain.tld";
$data['domain:registrar'] = "Registrar Ltd.";
$data['domain:creation'] = "2015-26-05";
$data['domain:expiry'] = "2016-26-05";
$data['ns'] = "ns1.somedns.tld";
$data['owner']['name'] = "Owner Name";
$data['owner']['type'] = "Org";
echo json_encode($data);
That data is then append to html with AJAX like this:
$.ajax({
type: 'POST',
url: 'carnetEpp.php',
data: $(this).serialize(),
success: function (data) {
dataType: 'json',
//console.log(data);
$('#response').html(data);
$("#myModal").modal();
}
});
Now I want to pass that returned JSON object to PHP variable, so I can easy manipulate date with PHP. How do I do that? Or is best practice to do it with JS? Basically I want to print every key:pair value, so maybe for in is good choice.
And, I am not sure, should, or must I echo data in my script so AJAX can pick it up, or can I just pass data to variable and then fetch it in AJAX?
You need to add this code in success.
var obj = jQuery.parseJSON(data);
alert(obj.message);
OR
var obj = $.parseJSON(data);
alert(obj.message);
You will get the message sent from PHP.
before sending data in php, setup header for response:
$data = [
'key' => 'value',
'key2' => 'vlue2'
];
header('Content-Type: application/json');
echo json_encode($data);
then if u use jquery, $.getJson() it really cool solution for handle input json data.
i need to seperate two variables which i got from the server and i m using $.post method. but when i m doing it i m getting the combined mixed value from this method. here is the code
$(".spot_me").click(function()
{
var idea = $(this).attr("id");
var idea1 = $(this).attr("data");
alert(idea);
alert(idea1);
$.post('spot_me.php', 'val=' + idea + '&tim=' + idea1, function (data)
{
alert(data);
});
});
here var id is a userid. i wish to get the coordinates which this user had stored in the database. my php code for abc.php is
<?php
session_start();
$value = $_POST['val'];
$value1 = $_POST['tim'];
$con=mysqli_connect("localhost","root","******","anurag");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result2 = mysqli_query($con,"SELECT latitude,longitude FROM notifications WHERE uid='$value' AND time='$value1' ");
if(!$result2)
{
echo "Error in query";
}
else
{
$row = mysqli_fetch_array($result2);
$lat = $row['latitude'];
$lon = $row['longitude'];
echo $lat;
echo $lon;
}
?>
now i want to get this lat and lon value separately in my jquery $.post method in the parameter data. how can i get these values separately and "I WANT TO STORE THEM IN TWO DIFFERENT VARIABLES IN $.POST METHOD" how can i do this
You'll use JSON to communicate between the languages.
Your PHP will transform the array into JSON:
else
{
$row = mysqli_fetch_array($result2);
echo json_encode($row);
}
And your javascript will treat the data as an object, because you've told the .post() function to expect json
var post_str = 'val=' + idea + '&tim=' + idea1;
$.post('spot_me.php', post_str, function (data)
{
alert(data.latitude);
alert(data.longitude);
}, 'json');
Choose a mode of response - maybe json (my preference) or xml
Construct your response with your server code
Parse that response with jQuery, with jQuery.parseXML() or jQuery.parseJSON() for json and xml respectively
At PHP
$row = mysqli_fetch_array($result2);
echo json_encode($row);
At jQuery
$.post('spot_me.php', 'val=' + idea + '&tim=' + idea1, function (data)
{
var response = jQuery.parseJSON(data);
alert(response.latitude);
alert(response.longitude);
});
This is just an indicator oh how to do it, and not tested.
you can do it by returning you output as JSon and then parse that JSON in Javascript.
In PHP file do like this: (instead of returning two variables)
echo json_encode(array('latitude' => $row['latitude'],'longitude'=> $row['longitude']));
Response will be like this (test values use)
{"latitude":123,"longitude":456}
in you Jquery Ajax code where you return response use JSON parse method
var obj = $.parseJSON(data );
alert( obj.latitude)
alert( obj.longitude)
//From the server
$row = mysqli_fetch_array($result2);
return json_encode($row);
//and on the client
var dataasjson = $.parseJSON(data);
$.each(dataasjson, function(index, element) {
element.name //this is your label i.e databse field name as key
dataasjson[element.name] //this is your long/lat value
});