Send javascript object with AJAX [duplicate] - javascript

This question already has answers here:
Passing JavaScript array to PHP through jQuery $.ajax
(9 answers)
Closed 6 years ago.
I am building a platform where users can draw graphs.
In order to do this, I am using Chart.js and each time a graph is created, I save an instance (a javascript object) of this one in a javascript array.
What I would like to do is to save that array of instances in a PHP session variable with AJAX, so that the user can retrieve his configuration later on.
From what I understood, the Javascript object sent to PHP via AJAX will be converted to PHP array format and the returned value will depend on the "dataType" that we expect (json, html, xml...)
However, what I want to retrieve is the exact same Javascript array of my graphs instances in order to re-instantiate them, not a "converted format".
Thank you in advance for your help !

If you want to be absolutely sure, that you get the same object back from PHP (no conversion what so ever), you can serialize it as a string (JSON.stringify(object)) and afterwards parse it again.
Here is one solution:
JavaScript (send data):
var data = [
{ "abc": "def" },
{ "ghi": "jkl" }
];
$.ajax({
"url": "http://localhost/savedata.php",
"method": "POST",
"data": {
"list": JSON.stringify(data)
}
});
PHP (savedata.php):
<?php
session_start();
$_SESSION['data'] = $_POST['list'];
?>
PHP (getdata.php)
<?php
session_start();
header("Content-Type: application/json");
echo $_SESSION['data'];
?>
JavaScript (receive data):
var data = [];
$.ajax({
"url": "http://localhost/getdata.php",
"method": "GET",
"success": function(response) {
data = response;
}
});

You have few options:
AJAX + PHP session + generate stuff with php (pure js, cookies, localStorage)
session ends when browser is closed
much codewritting
localStorage
storage gets wiped when browser is closed
best safety and easiest
Cookies
you have expiration date
you need to provide message about using cookies
cookies can be generated with PHP and with JS
You can provide links/codes which generates your graphs. I do it, user just send link to his mail, and he can recreate stuff any time.

Related

Communicate php and js

I'm trying to create a js that send data to a php.
My first problem is that I get get back a html code if I insert this to the php.
This is only for understand the idea. So the js should send the "param" to the php and the php should return the result6 variable in this case, but I get a html code...
$('#f_field').change (function()
{
var param = 28;
$.post('check_mutet.php', param, function(result6) {
alert(result6);
});
});
while check_mutet.php contains this
<?php
$result6=666;
echo $result6;
Thank you for your help, as you can see I'm rather noob :)
param is a plain string (it starts out as a number, but will be converted to a string by the time it gets through to HTTP).
This will be available as STDIN in PHP, which you can read as described in answers to this question.
However, you should encode the data into a structured format that is easier to use.
The traditional format for this is application/x-www-form-urlencoded, which is the default format sent by HTML forms.
If you pass an object to jQuery post, it will encode the data in that format for you:
var param = 28;
var data = { example: param };
$.post('check_mutet.php', data, function(result6) {
Then you can read it through the POST superglobal in PHP:
<?php
$result = $_POST['example'];

Using JavaScript variable as tablename in select query in PHP form [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 5 years ago.
I'm using a function in which I'm assigning a variable a tablename value like:
function mshirt(){
var tbname='m_shirts';
}
Then in PHP form action section:
include 'database_connection.php';
$tablename=tbname;
if(isset($_POST['submit'])){
$Size=$_POST['size'];
$Color=$_POST['color'];
$Code=$_POST['code'];
$Brand=$_POST['brand'];
$sql="INSERT INTO `$tablename` (size,color,code,brand) VALUES('$Size','$Color','$Code','$Brand')";
if(mysqli_query($conn,$sql)){
echo("Added Succesfully");
}
else
echo("Failed to Add");
The problem is that it assumes tbname to be undefined constant.
PROBLEM
The error is because of the line:
$tablename=tbname;
tbname is a JS (client-side) variable: you cannot simply enter it into PHP (server-side) and expect it to work. You need to instead send it over as POST data to PHP, just like you would other data.
SOLUTION
If you were doing this by AJAX and jQuery, for example:
var tbname = 'm_shirts';
$.ajax({
url: "path_to_php_file.php",
method: "post",
data: {
tbname: tbname,
// the rest of form data (the request) to be sent
}
});
And in PHP, you would get this as a regular $_POST variable index:
$tbname = $_POST["tbname"];
(If you were sending the data using a regular form or some other method, you would need to modify this... this is just an example for demonstration.)
You are trying to mix languages...
You should send the name of the table via ajax or form and then catch your value with $_GET or $POST

Handling MYSQL Query Results returned from PHP page

Using AJAX We can get php echoed data by
success: function(data)
Also We can point them to display inside any ware in the page using id of the element.
Eg-
$("#id").html(data);
My problem is how can I display those data in different places? My result gives me like 8 values and I want them to display in different places of my web page. Better if i can use php codes where ever i want to display them. eg:- <?php echo ($row[0]); ?>
I'am sure it is possible with PHP Sessions. Is there an easy way to achieve this?
Define a global variable and assign returned json to that variable then you can use that value anywhere in the page.
Var datarow;
$.ajax({
...,
success: function(dataJson) {
datarow=dataJson
}
});
$("#yourHtmlId").html(''+datarow.firstValue);

How to get MySQL query result returned using $.ajax

i'm trying to update is a javascript which when you hover over an image, a div object floats near your mouse with information, this information is stored in a .js file as an array,
eg.
Text[0]=["image 1","data 1"]
Text[1]=["image 2","data 2"]
in the past if this array is change/data added to/removed from it would require uploading a new copy of the .js file, if data was added to/removed from it would also require a change to the .dwt file for the new image which would update every file that use the .dwt file as the main template which could result in 20+ pages being uploaded
i figured i can automate this by using the database by flagging records if they are active and using a mysql query to get only those which are active, this way a blackened app can add to the database and deactivate record thus eliminating having to upload files every so soften.
to do this, i had planned on storing the information in the database and building the above array based off the results, researching how to use mysql queries in javascript lead me to code like this
$.ajax( "path/to/your.php" )
.done(function() { alert("success"); })
.fail(function() { alert("error"); })
now i understand that i need to make a .php file which runs my query and that my formatting of the query results into the array would be one in the .done part but what i don't understand is what i'm supposed to do in the .php file to output the query results how in the .done part i'm supposed to reference the output
bellow is the code i use to echo my query results to the page to ensure i am getting results
$resultIndex = 0
while($row = $results->fetch_array(MYSQLI_ASSOC))
{
echo '<'.strval($resultIndex).'><br>';
echo 'id = 'strval($row['id']).'<br>';
echo 'name = 'strval($row['name']).'<br>';
echo 'desc = 'strval($row['desc']).'<br>';
echo 'active = 'strval($row['active']).'<br>';
echo '-----------------------<br>';
$resultIndex += 1;
}
i am wondering 2 things
do i just echo or print_r what i want returned from my .php file
how to i access what my .php file returns in .done
I recommend using http://www.php.net/json_encode to output into Json. Yes, just echo the output. On success, a callback is called passed with the data from server.
$.post (url, function (data){
//do some stuff with data from server
});
See http://api.jquery.com/jQuery.post/
Your $.ajax function just points to a page and reads the data on that page. If you want that page to use MySQL, you will need to use php to set up the MySQL query and print the data. The layers of a web app are complicated, but I'll try to break it down for you.
A traditional php/mysql setup works like this:
Javascript:
Client side, only deals with content already available on the page. Often edits html based on user interaction.
HTML
Client side, defines the content on a page
PHP
Server side, runs on the server and construct the html
MYSQL
Server side, used to communicate between the php and the database
Database
Server side, used to permanently store data
Ajax is a way for the Javascript layer to call some php in the background. That php can use MySQL to access data in the database and print it out in a format that the javascript can parse and use. Typically the javascript will then edit the HTML.

jQuery $.ajax to pass multidimensional array to PHP

I am using jQuery and PHP to write JSON data to my server. I'm processing a decent amount of repeating numeric data (~.75kb), so I want to pass the data to PHP in the form of a multidimensional array.
At the moment I cannot manage to get the data to PHP in a form that it can recognize. I've tried various combinations of sending/receiving as arrays and objects with no success.
The best case scenario would be one in which I pass a the array to the PHP and the PHP converts it to a readable form. I'd rather not use associative arrays or any serializing on the part of the Javascript.
Code... This is giving me a 500 internal server error, which no longer occurs if I omit the passed data variable. (I'm not yet using $data in the php file yet because I know it's not working.)
function generateData() {
// code here
return [ one[ sub_one[], sub_two[] ], two[], three[], four[] /* Etc... */ ]
}
function saveData() {
$.ajax({
url: "scripts/save.php",
data: {
"area":"testing",
"location":"testing",
"name":"testing",
"data":generateData()
}
});
}
<?php
$area = $_GET['area'];
$location = $_GET['location'];
$name = $_GET['name'];
$data = $_GET['data']);
# Performing operations with variables...
echo 1;
?>
Thanks for any help you can offer.
Found a solution:
"data": {
data: generateCellData()
}
The above code passes data as an object to PHP, whereby I can access the original array as $data("data"). I'm still somewhat baffled by why this works when I'm already passing the data and other parameters as an object.

Categories