Pass data from jQuery to PHP file in one set - php

I have a table and some <td> have a data, but not all of them. On a button click I run jQuery function which checks each <td> and where the data is present, grabs the data.
After that the data is being passed to php file and inserted into my DB. Everything works great.
function insert_data() {
if(confirm("\nAre you sure?.\n")) {
$("#myTable td").each( function() {
var worker = $(this).attr("id");
var quarter = $(this).attr("title");
var station = $(this).attr("name");
var type = $(this).attr("class");
$.post({ url: "insert_data.php", data: {worker:worker, quarter:quarter, station:station, type:type} });
});
}
else { return false; }
}
I am wondering if instead of calling the php with ajax for every <td>, maybe there is a way to pass the data like one package? I checked at least couple dozen different articles here and on other websites and it seems that very often JSON is used for that purpose.
I've never worked with JSON and after several days of trying different approaches, still can't figure out what I am doing wrong. I will appreciate any help.
All I need is to pass data from my table into php file (and unpack it in there). I do not need to display it simultaneously on the html page.
Here is one of the versions which doesn't work:
JS:
function insert_data() {
if(confirm("\nAre you sure?.\n")) {
var myArray = []; // var to store all records for json data transfer
$("#myTable td").each( function() {
var worker = $(this).attr("id");
var quarter = $(this).attr("title");
var station = $(this).attr("name");
var type = $(this).attr("class");
var record = {worker:worker, quarter:quarter, station:station, type:type}; // sd - short for schedule data
myArray.push(record); // add every record to same array
});
console.log(myArray);
$.post({ url: "insert_data.php", data: {myArray: myArray }, success: function(data){ alert('Items added'); }, error: function(e){ console.log(e.message); } });
}
else { return false; }
}
In console I see following data (it looks like the data is being added to the array without issues):
(4) [{...}, {...}, {...}, {...}]
0: {worker: "556", quarter: "1", station: "abc_15", type: "rework"}
1: {worker: "147", quarter: "2", station: "abc_37", type: "rework"}
2: {worker: "345", quarter: "3", station: "abc_15", type: "rework"}
3: {worker: "12", quarter: "4", station: "abc_15", type: "rework"}
PHP:
$mySchedule = array();
$mySchedule[] = $_POST["myArray"]; // get the json array
var_dump($mySchedule);
foreach ($mySchedule as $sched) {
$worker = $sched['worker']; // or: $sched->worker; - doesn't change the result
$quarter = $sched['quarter'];
$station = $sched['station'];
$type = $sched['type'];
// code to insert data into my DB - works fine when I pass data one by one instead of array
}
HTML:
I also added this script to the page with my table:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-json/2.6.0/jquery.json.min.js"></script>
I am not sure if it is needed or not.
--
It feels that the problem is in the way how I "unpack" the array. But I am not sure... I tried to follow all advises I could find here, but maybe I just miss something really important.
I tried:
$mySchedule[] = json_decode($_POST["myArray"]); // in insert_data.php
data: { json: JSON.stringify(myArray) } // in jQuery function
and some other advises...

update
I got some help from one of my colleges. So, the jQuery code stayed without changes. PHP code had couple minor changes and it works fine now. The changes in PHP:
$mySchedule = $_POST["myArray"]; // get the json array
instead of:
$mySchedule = array();
$mySchedule[] = $_POST["myArray"]; // get the json array
That is it. Thank you very much for help and advises. I hope this example will be helpful to others.

Related

Retrieve data from PHP file by ajax

I found a script on the net, which makes two PHP files interact.
Specifically, the first file (details.php) shows some statistical data of a football match. If the match is in progress, I show the live score by running another PHP file (live_score.php). The two files interact thanks to the following script, present in the details.php file
$(document).ready(function(){
setInterval(function() {
var id=<?php echo"$id"?>;
var x = "<?php echo"$cod"?>";
$("#risultato").load("live_score.php", {var:id, x});
refresh();
}, 5000);
});
from details.php, I call live_score.php passing it some parameters.
These parameters are used by the live_score.php file to retrieve the score and other information in real time.
To print the result on the screen in details.php, I use a simple ECHO inside the live_score.php file, but I would like to retrieve this data and the others in a different way, via ajax if possible, but I don't know if it can be done and how....can you help me please? Thank you
I think you have already solved half of your problem. From your code , you should first remove the "refresh()" to stop reloading the page every 5 seconds.
then make sure that the the payload is correct, because the word "var" is a reserved keyword in JavaScript.
HTML
<div id="risultato"></div>
Javascript
$.ajax({
url: "live_score.php",
type: "POST",
data: { id, x},
success: function(response) {
//this response will be the data from "live_score.php"
//now assuming that
// 1. you use vanilla javascript with plain html + css
// 2. the returning reponse looks like this
// [{"teamName": "theTeam1", "score": 10}, {"teamName": "theTeam2", "score": 10}]
//Clear the current score
$("#risultato").empty();
// Now iterate through the response,
$.each(response, function(index, item) {
var teamName = item.teamName;
var score = item.score;
var html = "<p><strong>" + teamName + "</strong>: " + score + "</p>";
// this code will append (add to the end) the data iterated
$("#risultato").append(html);
});
},
error: function(xhr, status, error) {
//if your code or ajax call had any problems ,
//you can debug here and write error handling logic here, like
if(error){
alert("failed to fetch data");
console.log(error);
}
}
});

appending $.ajax response to Jquery UI dialog box in table format

I am getting data in a php file from db as
while ($row=mysqli_fetch_row($result))
{
printf ("beacon id : %s \n",$row[2]);
printf ("beacon uuid :(%s)\n",$row[3]);
}
now i want to append that data in table and show in JQueryUI Dialog box like this
In ajax success form i tried to create hardcore table and get data
success: function(response){
for (var i = 0; i < 3; i++) {
var row = $('<tr></tr>').appendTo(mytable);
for (var j = 0; j < 3; j++) {
$('<td></td>').text("text1").appendTo(row);
}
}
$('<table></table>').appendTo("#dialog");
$("#dialog").dialog("open");
}
it is working fine
///////////////
when I tried to get to get my data in table its not working
I tried
success: function(response){
var table = $("#table tbody");
$.each(response, function(idx, elem){
table.append("<tr><td>"+elem.id+"</td></tr>");
});
$('<table></table>').appendTo("#dialog");
$("#dialog").dialog("open");
}
but it is not working ,
console.log is coming like
what can i modify to display data ?
You're not appending the table with data, instead you're creating a new empty table element and appending it.
Edit:
You also can't loop over a string (which is the ajax response). If you output the html in php things will be simpler. This is also untested but hopefully you get the idea.
php:
while ($row = mysqli_fetch_row($result)) {
printf("<tr><th>beacon id :<th> <td>%s</td><tr>", $row[2]);
printf("<tr><th>beacon uuid :<th> <td>(%s)</td><tr>", $row[3]);
};
js:
success: function (response) {
if (response) {
var table = $("#table tbody");
table.append(response);
table.appendTo("#dialog");
$("#dialog").dialog("open");
}
}
First, I would adjust your PHP so that it is sending back JSON data. The data you are sending back now is just text. It will not be read as an Object by JS.
PHP
$beacon = array();
while ($row=mysqli_fetch_row($result)){
$beacon[] = array("id" => $row[2], "uuid" => $row[3]);
}
header('Content-type:application/json;charset=utf-8');
echo json_encode($beacon);
See: Returning JSON from a PHP Script
This creates an array of arrays. The resulting page should be something like:
[
{
"id": "Beacon00UUID::fda50693-a4e2-4fb1-afcf-c6eb07647825",
"uuid": "(Beacon00RSSI::-69)"
},
{
"id": "Beacon01UUID::2f234454-f491-1ba9-ffaf-000000000001",
"uuid": "(Beacon01RSSI::-53)"
},
{
"id": "Beacon02UUID::b9407f30-f5f8-466e-aff9-25556b57fe6d",
"uuid": "(Beacon02RSSI::-75)"
},
{
"id": "Beacon04UUID::00000000-0000-0000-0000-000000000000",
"uuid": "(Beacon04RSSI::-88)"
},
]
This will allow your jQuery to collect the content as JSON. In your success callback, you can handle this better. this is also assuming you have dataType: "json" elsewhere in your AJAX call.
jQuery
success: function(response){
var $tbl = $("<table>");
$.each(response, function(key, val){
var $row = $("<tr>").appendTo($tbl);
if(key % 2 == 0){
$row.addClass("even");
} else {
$row.addClass("odd");
}
var $cell = $("<td>").html(val.id).appendTo($row);
});
$("#dialog").html($tbl.prop("outerHTML")).dialog("open");
}
Now, if your data was coming back with a key of beacon id, you would need to call this exactly. For example, it would not be elem.id, it would have to be elem['beacon id'] to call the right index in the object. You can't use the dot notation that includes a space in the index name. Bare that in mind when naming your indexes.
There is a subtle difference with $.each() and .each(), the former is designed for arrays and objects, with a key and value pair and the latter designed for jQuery objects, with an index and element pair. nothing wrong with what you did, just explaining why you might use one over the other.
Hope this helps. Let me know if something is not clear.

Print an element array in jquery

I have a jquery function that calls a controller which in turn calls a function that I extracted the data from the users table. I return an array cin all the data in the table. ID, username etc etc.. So mold date in jQuery and indeed the array is full. Ex. [{"Id_user": "21", "username": "cassy1994"}].
From this array I have to extract only the username. How can I do?
This is the Ajax function:
$(".apprezzamenti").click(function()
{
var id = $(this).attr('id');
var txt = "";
$.get("http://localhost/laravel/public/index.php/apprezzamenti/"+id,
function(data)
{
$(".modal-body-apprezzamenti>p").html(data);
});
});
If the json is parsed, your object is stored in an array, so:
data[0].username
If not (if it is a string), you need to parse it first:
data_parsed = JSON.parse(data);
// data_parsed[0].username
assuming data is where your response is stored, data[0].username should work. Example:
$(".modal-body-apprezzamenti>p").html(data[0].username);
To print all usernames:
var count = 0;
$.each($(".modal-body-apprezzamenti>p"), function() {
this.html(data[count].username);
count++;
]);
Hope this helps!
So, this is the problem. It's okay though, I realized that with this code I'm using can not seem to generate as many sections as there are users want to print and it shows me only the last username because it can generate only a paragraph in html. A possible solution which would it be?
This is the code:
$(".apprezzamenti").click(function()
{
var id = $(this).attr('id');
var txt = "";
$.get("http://localhost/laravel/public/index.php/apprezzamenti/"+id,
function(data)
{
data_parsed = JSON.parse(data);
for(var i=0; i<data_parsed.length; i++)
{
$(".modal-body-apprezzamenti>p").html((data_parsed[i].username));
}
});
});

Send a request to a php page and then get back results using ajax

I have a script where i am trying to send some location information to a php page, carry out a mysql search query and get the results back without going to another page.
my php works fine, and i have had the page working that it redirects to the php page, however when i try and use the code below, i do not get any results passed back.
Javascript code
function phpRedirect(loc) {
// var radius = get('r'); // Retrieve GET values for search radius and
// var numResults = get('n'); // number of results
var radius = 10; // Retrieve GET values for search radius and
var numResults = 5; // number of results
var latitude = loc.coords.latitude; // Get long, lat and accuracy from
var longitude = loc.coords.longitude; // location object
var accuracy = loc.coords.accuracy;
var xmlHttp = new XMLHttpRequest(); //not the cross browser way of doing it
xmlHttp.open("GET", "find.php?lat=" + latitude + "&long=" +
longitude + "&acc=" + accuracy + "&r=" + radius
+ "&n=" + numResults, true);
xmlHttp.send(null);
}
$(function ()
{
$.ajax({
url: 'find.php', //the script to call to get data
type: "post",
data: { getData: true },
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var name = data[0];
$('#output').html("<b>username: </b>"+username);
}
});
});
function error(loc) {
// This is called if the location can't be found.
document.write("Error finding GPS location");
}
// Use navigator to get current user location. If found, calls 'phpRedirect()',
// If not available calls 'error()'. Includes timeout and ensures highest acc.
navigator.geolocation.getCurrentPosition(phpRedirect, error, {maximumAge:60000, timeout:5000, enableHighAccuracy:true});
<div id="output">this element will be accessed by jquery and this text replaced </div>
Below is the output from my php query,
$result=mysql_query($query) or die (mysql_error());
while($row=mysql_fetch_assoc($result)) $data[]=$row; // Turn result to array
$acc_package = array('location_accuracy'=>"$accuracy"); // Include result array
$output[] = $acc_package; // and accuracy value inside
$output[] = $data; // an output array.
print(json_encode($output)); // Convert output array to json format and print
Which gives the following results
[{"location_accuracy":"122000"},[{"username":"bobbyj","distance":"0.484367160806139"}]]
Sam, I have a few suggestions for you.
First, the jQuery library is great and the AJAX module works amazing :) It's great that you are using it! No need to mix that old XMLHTTP junk with it (they do basically the same thing). So get rid of that and replace it with jQuery ajax.
Let's start with something really basic:
$.ajax({
url: 'find.php',
type: "POST",
data: { lat: lattitude }
}).done(function( msg ) {
alert(msg);
});
Put your other variables in the data: as well.
On your PHP page, try a simple var_dump($_POST); so you can see what is coming through. The AJAX should make an alert with contents of the PHP page.
Work your way up from this with your Mysql :)

Using php, ajax and jqplot to make a pie chart

I am attempting to make a pie chart using a php file that gets the information from MySQL, JSON encodes it, and then sends it to my JS file to make the pie chart. I have looked at most of the other questions posted here and none of them help me at all. I have attempted to re-qrite my code to match ones that seem to fit, but nothing is working.
My php file is:
$shelvDate = $_POST['shelvDate'];
$x = 0;
// get information from database for shelving chart
$shelv = $conn -> query ("SELECT sum(quantity) as qty, date_process, created_by, first_name from inventory LEFT JOIN users on users.user_id =inventory.created_by
WHERE date_process = '$shelvDate' GROUP BY created_by" );
$num_rows = $shelv->num_rows;
if($num_rows > 0){
while($row = $shelv->fetch_assoc()) {
if($row['qty'] > 0){
$qtyArray[$x] = $row['qty'];
$nameArray[$x] = $row['first_name'];
}
$x++;
$pairs = array('first_name' => $nameArray, 'qty' => $qtyArray);
} // end of while statement
} //end of if statement
$conn->close();
echo json_encode(array($pairs));
When I attempt to get the data into my ajax/js I get an error. My JS is:
$("#getRecords").live('click', function() {
var ajaxDataRenderer = function(url, plot, options) {
var ret = null;
$.ajax({
type: "POST",
async: false,
url: url,
dataType:"json",
data: ({shelvDate: $('#shelvDate').val()}),
success: function(data) {
for(var x=0; x<data.first_name.length; x++) {
var info = [data.first_name[x], data.qty[x]];
ret.push(info);
}
}); // end of ajax call
return ret;
}; // end of ajaxDataRenerer call
// The url for our json data
var jsonurl = "shelvChart.php";
var plot2 = $.jqplot('shelvChart', jsonurl,{
seriesDefaults: {
// Make this a pie chart.
renderer: jQuery.jqplot.PieRenderer,
rendererOptions: {
// Put data labels on the pie slices.
// By default, labels show the percentage of the slice.
showDataLabels: true
}
},
title: "Books Shelved",
dataRenderer: ajaxDataRenderer,
dataRendererOptions: {
unusedOptionalUrl: jsonurl
}
});
});
I am don't know what I'm doing wrong or even where to go from here as I am still new to AJAX and JS. Any help will be greatly appreciated.
Jim
It would be very useful to see a real JSON string you are getting, cause I am not sure how you can get name[object,object],qty[object,object] after calling alert(ret) or maybe you are referring to other alert?.
Anyway from what you are saying your problem is that you must make sure that the array returned by the ajaxDataRenderer function is of a proper format that is accepted by a pie chart.
Therefore, for example, inside your PHP or JavaScript code you need to make sure that the returned array ret is of the following format:
ret = [[name[0], qty[0]], [name[1], qty[1]], ...];
This way all values that are in name array will be used as labels and qty array will be used as values from which the percentage will be evaluated.
Similar approach that shows how to prepare data for a chart is shown in this answer.

Categories