Is it possible to work with a response from AJAX request in PHP? I am not really a JS dev so i am polling my hair out with this one.
I have sort of hacked this together:
var base_url = 'http://dev.local/westview/public';
$('select.child_id').change(function() {
var child_id = $('#child_id');
var dataString = 'child_id=' + child_id;
$.ajax({
type: "POST",
url: base_url + "/finance/payment-history",
data: dataString,
dataType: 'html',
success: function(html) {
alert(html);
},
});
return false;
});
The function appears to work ok, it gives me an alert with the correct data.
{"payments":[{"id":"19","child_id":"21","club":"Breakfast Club","term":"Half Term 3","amount":"15.00","pdate":"2015-02-25","notes":"","created_at":"2015-02-11 12:16:32","updated_at":"2015-02-11 12:16:32","starting_debt":"0","debt_start_date":"2015-01-05"},{"id":"20","child_id":"21","club":"After School Club","term":"Half Term 3","amount":"11.50","pdate":"2015-02-25","notes":"","created_at":"2015-02-11 12:16:49","updated_at":"2015-02-11 12:16:49","starting_debt":"0","debt_start_date":"2015-01-05"}]}
I need to be able output this to the user so that it is readable. A lot of guides I find describe replacing data but as it stands there is no data until a child_id is selected.. i then want it show the above data in a readable way.
I have no idea how to start working with the data in my view file(php).
Thanks
[EDIT]updated with working code:
var base_url = 'http://dev.local/westview/public';
$('select.child_id').change(function() {
var response = "";
var child_id = $('#child_id').val();
var dataString = 'child_id=' + child_id;
$.ajax({
type: "POST",
url: base_url + "/finance/payment-history",
data: dataString,
success: function(response) {
var json_obj = $.parseJSON(response);
var output = "<ul>";
for (i=0; i < json_obj.payments.length; i++)
{
var payment = json_obj.payments[i];
var date = moment(payment.pdate).format('Do MMM YYYY');
output += "<li>£" + payment.amount + " - " + date + " (" + payment.club + ")</li>";
}
output += "</ul>";
$('.history-section').html(output);
},
dataType: "html"
});
});
Do like this.
var data = $.parseJSON("your_json");
var output= "<ul>";
for (i=0; i < data.payments.length; i++){
output += "<li>" + data.payments[i].id + ", " + data.payments[i].child_id + "</li>";
}
output += "</ul>";
use
dataType: 'json',
instead
dataType: 'html',
and then use each to fetch the record from response in success function
Use $.parseJSON() For Convert Json Format Data To Array
Right code at sucess of ajax..
Like,
var data = $.parseJSON(html);
data in you get array format of responce
You need to use json_encode() in your php file to send the data back as an array
For example;
$myarray = array("data1"=>"value1","data2"=>"value2");
echo json_encode($myarray);
You can then access the data separately in the js file like this;
success: function(html) {
alert(html.data1);
alert(html.data2);
},
You also need to change the dataType to 'json'
$('input[name=\'product_attribute[' + attribute_row + '][name]\']').catcomplete({
delay: 0,
source: function(request, response) {
$.ajax({
url: 'index.php?route=catalog/attribute/autocomplete&token=<?php echo $token; ?>',
type: 'POST',
dataType: 'json',
data: 'filter_name=' + encodeURIComponent(request.term),
success: function(data) {
response($.map(data, function(item) {
return {
category: item.attribute_group,
label: item.name,
value: item.attribute_id
}
}));
}
});
},
select: function(event, ui) {
$('input[name=\'product_attribute[' + attribute_row + '][name]\']').attr('value', ui.item.label);
$('input[name=\'product_attribute[' + attribute_row + '][attribute_id]\']').attr('value', ui.item.value);
return false;
}
});
You Can map your json something like this
Related
I want to fetch data from database using PHP and Ajax, which is first encoded into JSON.
But data is not printed properly on the screen. It shows elements of four rows in single line separated by comma.
$(document).ready(function() {
$(function()
{
$.ajax({
url: 'demo2.php',
data: "",
dataType: 'json',
success: function(data)
{
var name = data[0];
var email = data[1];
var msg = data[2];
var date1 = data[3];
$('#output').html("<div id='container'>" + name + " " + email + " " + msg + " " + date1 + "</div><br>");
}
});
});
});
Try this:
$(document).ready(function() {
$(function()
{
$.ajax({
url: 'demo2.php',
data: "",
dataType: 'json',
success: function(data)
{
console.log(JSON.stringify(data));
var obj = JSON.parse(data);
// Iterate object:
my_text=''
$.each(obj, function(index, value) {
console.log(value);
my_text += value
});
// var obj = JSON.parse('{ "name":"John", "email":"email#domain.com", "msg":"Hello"}');
$('#output').html("<div id='container'>" + my_text + "</div><br>");
}
});
});
});
Fiddle:
https://jsfiddle.net/fks3j500/
var a = $('.level').find(":selected").attr('value');
var b = $('.category').find(":selected").attr('value');
var c = $('.topic').find(":selected").attr('value');
var d = $('.question').val();
$.ajax({
url: "http://localhost/2016/2016_02_15_Quiz/index.php/Admin/getthecompr/" + a + "/" + b + "/" + c,
type: "GET",
dataType: 'json',
data: '',
success: function(data) {
var id = data;
$.ajax({
url: "http://localhost/2016/2016_02_15_Quiz/index.php/Admin/insert4/" + id[0]['id_comprehens'] + "/" + d,
type: "GET",
dataType: 'json',
data: '',
success: function(data) {
alert("Success");
},
error: function() {
alert("Fail")
}
});
},
error: function() {
console.log('Paastoge');
}
});
});
I got trouble making this nested-JQuery-Ajax. In the first Ajax, I take the value of compre_id that I want to use in second Ajax. In the second Ajax, I will insert the id_comprhensive and question in MySQL table. The Problem is, inserting data to SQL table is success. But, instead of displaying "success", fail alert does appear. Is there something problem with this code ?
All that I am trying is to iterate the data I have in the database using the Jquery each method, but couldn't figure when I am losing it all. Can someone look through this piece of code and tell me what I am doing wrong ?
$(function(){
var output = $("#folderOne");
$.ajax({
url: 'http://......',
dataType: 'json',
// data: {action: 'output'},
success: function(data, status){
console.log(data);
$.each(data, function(index, value) {
if (value.f_id == 1) {
var cards = "<div class='thumb'>" + value.f_id +
"</div><br>" + "<p>" + value.title + "</p> ";
}
output.append(cards);
});
},
I'm trying to write a script that pass geolocation's lat and lng as an array to PHP and return a value to the client side by using jQuery AJAX. The best solution that i could find was JSON. My following scripts return me NULL value for some reason that i couldn't tell.
index.html
<div id="geoloc"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition);
} else {
$('#geoloc').html("<p>Geolocation is not supported by this browser</p>");
}
function showPosition(position) {
var latlng = [ {"lat":position.coords.latitude, "lng":position.coords.longitude}];
$.ajax({
type: "POST",
url: "libs/filterstores.php",
data: { json: JSON.stringify(latlng) },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
$('#geoloc').html("Latitude: " + data.lat + "<br />Longitude: " + data.lng);
}
});
}
});
</script>
filterstores.php
$currloc = json_decode($_POST['latlng'], true);
$stores = array('lat'=>$currloc['lat'],'lng'=>$currloc['lng']);
echo json_encode($stores);
The following will be results what i got in returns once i hit the "share location" button pop up from the browser
Latitude: sdf
Longitude: sdfsd
Should this line:
data: { json: JSON.stringify(latlng) },
not specify currloc as the parameter?
i.e.
data: { currloc: JSON.stringify(latlng) },
I think you are making double json coding in your AJAX function. If something went wrong when codifying, JSON function will give you a null as an answer. You only have to pass the string without json codification and surely it'll work:
function showPosition(position) {
$.ajax({
type: "POST",
url: "libs/filterstores.php",
data: { lat:position.coords.latitude, lng:position.coords.longitude },
dataType: "json",
success: function(data){
$('#geoloc').html("Latitude: " + data.lat + "<br />Longitude: " + data.lng);
}
});
}
Your PHP only will have to accept the POST, without json encoding:
PHP File:
$lat = $_POST['lat'];
$lng = $_POST['lng'];
$stores = array('lat'=>$lat,'lng'=>$lng);
echo json_encode($stores);
Just try to search 'sdfsd' or "sdfsd" and 'sdf' or "sdf"
And you will yourself get solution to your problem.
Try this
$currloc = json_decode($_POST['json'], true);
instead
$currloc = json_decode($_POST['latlng'], true);
or try this in SCRIPT
function showPosition(position) {
$.ajax({
type: "POST",
url: "libs/filterstores.php",
data: {"lat":position.coords.latitude, "lng":position.coords.longitude},
dataType: "json",
success: function(data){
$('#geoloc').html("Latitude: " + data.lat + "<br />Longitude: " + data.lng);
}
});
}
IN PHP FILE
$stores = array('lat'=>$_POST['lat'],'lng'=>$_POST['lng']);
echo json_encode($stores);
Hope it will help
This is how you can send and receive JSON data
$.ajax({
type: "GET",
url: "filterstores.php",
data: {json: latlng},
contentType: "application/json; charset=utf-8;",
dataType: "json",
success: function(data){
$('#geoloc').html("Latitude: " + data.lat + "<br />Longitude: " + data.lng);
}
});
And the PHP file
$currloc = $_GET['json'];
$stores = array('lat'=>$currloc[0]['lat'],'lng'=>$currloc[0]['lng']);
echo json_encode($stores);
I have a php file with encoded json. What I would like to do is to get each data(maxVote and Id) from encoded json
Here is my php file named results.php
<?php
$result = array();
array_push($result,array("maxVote"=>300,"id"=>"li_2"),array("maxVote"=>200,"id"=>"li_1"));
echo json_encode($result);
?>
Since I am new to ajax and json,
what are the codes to put on success so that i will get each maxVote's and each id's
$.ajax({
url: "results.php",
success: function(){
...
}
});
Thanks in advance!
You can use:
$.ajax({
dataType: "json",
url: 'results.php',
success: function(data){
var items = [];
$.each(data, function(key, val) {
items.push(key + ' : ' + val + '</br>');
});
$('body').append(items.join(''));
}
});
or
$.getJSON('results.php', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push(key + ' : ' + val + '</br>');
});
$('body').append(items.join(''));
});
Add the data parameter to your success function:
$.ajax({
url: "results.php",
success: function(data){
$.each(data, function(id, elt) {
// use data[id].maxVote or elt.maxVote
}
}
});