I created a json with this structure
var data =
{
"people": [
{ "name" : "John", "id" : 1 },
{ "name" : "Marc", "id" : 2 }
]
}
Now here's how i send the data to the php
var ordenDeCompra = JSON.stringify(data);
$.post("../Backend/ordenesDeCompra.php",
{
ventas: data,
idcliente : $('#sltCliente').val(),
subtotal: subtotalfactura
},
respuesta);
Now when i tried to handle the data in the php it doesn't have any values, i know that the values are sending well, because i see the data sending with charles debugging proxy.
This is how i tried the get the value in the php
$array = json_decode(stripslashes($_POST['ventas']), true);
Am i sending the values corrected??
change
ventas: data,
to
ventas: ordenDeCompra,
Use:
var ordenDeCompra = JSON.stringify(data);
$.post("../Backend/ordenesDeCompra.php",
{
ventas: ordenDeCompra,
idcliente : $('#sltCliente').val(),
subtotal: subtotalfactura
},
respuesta);
var ordenDeCompra = JSON.stringify(data);
$.post("../Backend/ordenesDeCompra.php",
{
ventas: ordenDeCompra, // shouldn't it be ordenDeCompra than data
idcliente : $('#sltCliente').val(),
subtotal: subtotalfactura
},
respuesta);
Related
I am using jQuery data tables and fill the data via ajax as json:
https://datatables.net/examples/ajax/simple.html
var tbl = $('.mytbl').DataTable({
"ajax": {
url: "ajax/getData.php",
type: "POST"
}
});
The response of getData.php will be like this:
$myArray['data'][] = array(
"Value 1",
"Value 2",
"Value 3"
}
echo json_encode($myArray);
This works fine:
But how can I define that - for example - value 2 should be text-align right in my table?
Try this
var tbl = $('.mytbl').DataTable({
"ajax": {
url: "ajax/getData.php",
type: "POST"
},
'columnDefs': [{
"targets": 1,
"className": "text-right",
}]
});
You can use render method available in Datatables.
{
data: 'value 2 column',
render: function ( data, type, row ) {
return `<span style="text-align:right">${data}</span>`;
}
}
You can also use css if all column values are right aligned.
I'm trying to use Data-tables but I need to pass a value from Ajax to PHP file.
the Ajax part is like this:
<script>
$(document).ready(function() {
var oTable =
$('#user-list').DataTable({
"serverSide": true,
"ajax": {
"url": "assets/server_processing_reminders.php",
"data": {
"CurrentFlag": 1
}
},
"columnDefs": [{
"width": "6%",
"targets": 0
}],
"order": [
[1, "asc"]
]
});
});
</script>
on the server side Im trying to get the variable "CurrentFlag" using:
<?php
if (isset($_GET["CurrentFlag"])){
$cf = $_GET["CurrentFlag"];
}
echo $cf;
but the php file is not printing out the value send.
Thanks for any help
Please use $_REQUEST instead of $_GET like this :
if(isset($_REQUEST["CurrentFlag"]))
{
$cf = $_REQUEST["CurrentFlag"];
}
echo $cf;
OR
If you want print data using $_GET method please add type:GET under ajax call
You need to provide request type as GET as shown here.
"ajax" : {
"url": "assets/server_processing_reminders.php",
type: "GET",
"data": {
"CurrentFlag": 1
}
}
Use Jquery for better code and results.
Learn Ajax using this link :
https://www.w3schools.com/js/js_ajax_intro.asp
I am creating Google chart using MYSQL data through PHP. Below is the part of jQuery.
$.ajax({
method: 'GET',
//dataType: 'JSON',
url: "/php/abc.php",
success: function (data1) {
var data = new google.visualization.DataTable();
// Add legends with data type
data.addColumn('string', 'type');
data.addColumn('number', 'value');
//Parse data into Json
var jsonData = $.parseJSON(data1);
//var jsonData = (data1);
for (var i = 0; i < jsonData.length; i++) {
alert (jsonData[i].length);
alert (jsonData[i].type);
data.addRow([jsonData[i].type, parseInt(jsonData[i].value)]);
}
I am getting below output from php when i check direct php page on browser
{"type":"New_Userstory","value":"10"}{"type":"Active_Userstory","value":"20"}{"type":"Resolved_Userstory","value":"30"}{"type":"Closed_Userstory","value":"40"}
but through json it is not showing anything, says incorrect character '{'. When i have used header('Content-Type: application/json'); or dataType: 'JSON', this eror is gone but result is "undefined" any other way to get this JSON ?
This is not the correct JSON output.
{"type":"New_Userstory","value":"10"}{"type":"Active_Userstory","value":"20"}{"type":"Resolved_Userstory","value":"30"}{"type":"Closed_Userstory","value":"40"}
The correct JSON output would be
[
{
"type": "New_Userstory",
"value": "10"
},
{
"type": "Active_Userstory",
"value": "20"
},
{
"type": "Resolved_Userstory",
"value": "30"
},
{
"type": "Closed_Userstory",
"value": "40"
}
]
According to your PHP Code, here is what you need to change.
$this->temp_sql_display = "SELECT * FROM SalesSummary";
try {
$result = $this->hookup->query($this->temp_sql_display);
while ($row = $result->fetch_assoc())
{
$this->json[] = $row;
}
echo json_encode($this->json);
}
I have simple trouble in json
This is my Json code
{ "id" : "1", "name" : "test1" },
{ "id" : "2", "name" : "test2" },
{ "id" : "3", "name" : "test3" },
{ "id" : "4", "name" : "test4" },
{ "id" : "5", "name" : "test5" }
And this it the ajax code I am getting the data
function load_res()
{
$.ajax({
url: 'data.js',
type: 'POST',
dataType: 'json',
success: function(data) {
var div_data='';
$.each(data, function(index, element) {
div_data +="<div ><a href='"+data.name+"'>"+data[index].name+"</a></div>";
});
$('#9lessonsLinks').append(div_data);
}
});
}
HTML part
<a onclick="load_res()">Button</a>
<div id="9lessonsLinks"></div>
Above code it working well and data retrieve and display. But my problem is, when I add a new row to JSON file and I click on load_res() function, it will show old printed data with new data again, multiple printing with multiple clicking. I only want to get the newly added data as last line.
please help me to resolve this. appreciate your great ideas.
Thanks!
Easy fix: change .append to .html
$('#9lessonsLinks').html(div_data);
Empty the list before adding the items to it...
$('#9lessonsLinks').empty().append(div_data);
With javascript like this:
document.getElementById("9lessonsLinks").innerHTML = div_data;
Using ammaps' dataLoader, is there a way to pass post parameters to an external file?
I'm creating a report that contains a map, which when clicked, will provide a list of news articles from a MySQL table. I'm pulling in json data using dataLoader. However, I need to be able to pass a value (reportId) to the script that generates the json file.
here's my code:
var map = AmCharts.makeChart("mapdiv", {
type: "map",
"dataLoader": {
"url": "maparticlesfeed.json.php",
"format":"json",
"showErrors": false//,
// tried this:
//"type" : "post",
//"data" : {"reportIdFromPost" : 1}
},
. . . //the rest of the map config
And this is maparticlesfeed.json.php:
<?php include('database-connect.php');
$con=Database::connect();
$query=$con->prepare("SELECT * from articles Where reportId=$POST['reportIdFromPost']");
$query=>execute();
$articlesList=$query->fetchall(PDO::FETCH_ASSOC);
?>
{
"map" : "MyMapName",
"_comment" : "Here, instead of hard-coding the headlines, we will iterate through $articlesList",
"areas" : [
{ "title" : "Virginia",
"id" : "US-VA",
"selectable" : true,
"numArticles" : 4,
"articles" : [
{ "headline" : "This is the first headline",
"link" : "link url"
},
{ "headline" : "This is the second headline",
"link" : "link url"
},
{ "headline" : "This is the third headline",
"link" : "link url"
},
{ "headline" : "This is the fourth headline",
"link" : "link url"
}
]
},
{ "title" : "Tennessee",
"id" : "US-TN",
"selectable" : false,
"numArticles" : 6
}
]
}
I went the jQuery route to solve this. I'd still like to know if there's a way to do this with dataLoader, but here's a workaround in case anyone else has this issue in the future:
$.ajax({
dataType: "json",
url: "maparticlesfeed.json.php",
data: { reportIdFromPost: 1 },
type: "post",
success: function(data){
console.log(data); // for debugging
makeMap(data);
},
error: function(data) {
console.log('it did not work.');
console.log(data.responseText);
}
});
function makeMap(theData) {
var map = AmCharts.makeChart("mapdiv", {
type: "map",
/* DON'T NEED THIS ANYMORE:
"dataLoader": {
"url": "maparticlesfeed.json.php",
"format":"json",
"showErrors": false
},*/
// replace instead with this:
"dataProvider" : theData,
// ... the rest of the map config ...
}
});
And, in maparticlesfeed.json.php:
<?php
include('database-connect.php');
$con=Database::connect();
if(!empty($_POST) && isset($_POST['reportIdFromPost']) ) {
$postedReportId= $_POST['reportIdFromPost'];
}
include('database-connect.php');
$con=Database::connect();
$query=$con->prepare("SELECT * from articles Where reportId=$postedReportId ");
$query->execute();
$articlesList=$query->fetchall(PDO::FETCH_ASSOC);
?>
{
"map" : "MyMapName",
"areas" : [
// Code to json_encode the results from $articlesList
]
}
It may be that you're posting json data and then not decoding it when you're trying to use the value in your php script.
Try this at the top of maparticlesfeed.json.php:
<?php
include('database-connect.php');
$postedValues = json_decode($POST['reportIdFromPost'], true);
$con=Database::connect();
$query=$con->prepare("SELECT * from articles Where reportId=$postedValues['reportIdFromPost']");
$query=>execute();
$articlesList=$query->fetchall(PDO::FETCH_ASSOC);
?>
You'll also need to uncomment the two lines in the map config:
"type" : "post",
"data" : {"reportIdFromPost" : 1}
Maybe you could add the parameters in the "url" parameter of the dataloader.
"url": "urlA.do?param1=" + $('.selector').val()
and then in some trigger (ie. button click) modify the url and reload
var url = "same URL with different parameters values";
chart.dataLoader.url = url;
chart.dataLoader.loadData()