jQuery $.ajax to pass multidimensional array to PHP - javascript

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.

Related

extracting array data from (data) in an AJAX call

This does not answer the question - jQuery Ajax return html AND json data
I can not use the wrap method because I do not have a single html string. I am not using Phery, I have tried the first option here and the second nested call runs before the first so that data is undefined- jquery Use two done callbacks in same function, one with datatype json one without and we are not using html5 only for this. Therefore the referenced answer does not address the question.
In my .done function I have (data) returning. This data is a mixture of php echo's and a single JSON_encode array. Sample data:
.....
//other divs and data above this point
<div id="test">text</div>
{"ids":["1","5","2","6"]}0
AJAX
.done(function(data) {
console.log(data);
func2(json_string)
})
I want to be able to extract and separately work with the array {"ids":["1","5","2","6"]}0. I am trying to pass it along to another function, but only that portion of the data
Here's a very simple content-negotiation example using a query string parameter...
In your PHP, break up your HTML and JSON parts like this
<?php
$format = $_GET["format"] ?? "html";
if ($format === "json") {
header("Content-type: application/json");
echo json_encode(["ids" => [1, 5, 2, 6]]);
exit;
}
?>
.....
//other divs and data above this point
<div id="test">text</div>
Then in your JavaScript code, fetch the two parts using
$.ajax(my_ajax.ajax_url, {
dataType: "html",
// etc
}).done(html => {
// html content here
})
and
$.ajax(`${my_ajax.ajax_url}?format=json`, {
dataType: "json",
// etc
}).done(json => {
// json content here
})

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'];

What is wrong with the way I am handling these variables in PHP?

Originally I wanted to use node.js, but after an entire day of frustration, I switched to using jquery and mySQL. The logins seem to be working, but something is wrong in the way it is handling variables. All I want to do is update the database with two things: score and name. Here is the code I modded for my project in PHP:
<?php
$db = "myDatabaseNameIsCorrect";//Your database name
$dbu = "soIsMyUsername";//Your database username
$dbp = "AndMyPassword";//Your database users' password
$host = "localhost";//MySQL server - usually localhost
$dblink = mysql_connect($host,$dbu,$dbp);
$seldb = mysql_select_db($db);
if(isset($_GET['name']) && isset($_GET['this.score'])){
//Lightly sanitize the GET's to prevent SQL injections and possible XSS attacks
$name = strip_tags(mysql_real_escape_string($_GET['name']));
$score = strip_tags(mysql_real_escape_string($_GET['this.score']));
$sql = mysql_query("INSERT INTO `$db`.`scores` (`id`,`name`,`score`) VALUES ('','$name','$score');");
if($sql){
//The query returned true - now do whatever you like here.
echo 'Your score was saved. Congrats!';
}else{
//The query returned false - you might want to put some sort of error reporting here. Even logging the error to a text file is fine.
echo 'There was a problem saving your score. Please try again later.';
}
}else{
echo 'Your name or score wasnt passed in the request. Make sure you add ?name=NAME_HERE&score=1337 to the tags.';
}
mysql_close($dblink);//Close off the MySQL connection to save resources.
?>
And here is the JS! that runs the PHP:
let gameoverScene = new Phaser.Scene('GameOver');
gameoverScene.create = function(){
this.laughSound=this.sound.add('laughSound')
this.gameW = this.sys.game.config.width;
this.gameH = this.sys.game.config.height;
this.goToTitle=function(){
var name = prompt('Enter your name');
jQuery.ajax({
type: "POST",
url: 'savescores.php?name=' +name +'&score=' + this.score,
dataType: 'text',
data: {functionname: 'add', arguments: [name, this.score]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
yourVariable = obj.result;
}
else {
console.log(obj.error);
}
}
});
this.scene.start('Title')
};
I also tried changing the data type and that didn't work, but I'm not ruling it out yet as a problem.
Here are links to the project and the database:
www.igglepud.com/DeerDefender/Testing
www.igglepud.com/DeerDefender/Testing/getscores.php
This is the error I get:
gameover.js:20 Uncaught TypeError: Cannot use 'in' operator to search for 'error' in
Your name or score wasnt passed in the request. Make sure you add ?name=NAME_HERE&score=1337 to the tags.
at Object.success (gameover.js:20)
at fire (jquery.js:3268)
at Object.fireWith [as resolveWith] (jquery.js:3398)
at done (jquery.js:9305)
at XMLHttpRequest.<anonymous> (jquery.js:9548)
So, the error you're getting is because, in the JavaScript, obj (or the parameter in obj's position) is a string, not an array.
You can see some examples here of how you can properly check for and catch errors.
Edit:
So, in regards to your question about the score variable.
It's important to note that there are 2 types of variables at play here.
The first one is PHP GET variables. PHP GET variables are set via the following format:
var=value
You can set these variables by calling a PHP script like this:
script.php?var1=value1&var2=value2&var3=value3 // etc...
You can access them like this:
echo $_GET["var1"];
echo $_GET["var2"];
echo $_GET["var3"];
Which produces the result:
value1
value2
value3
The second variable at play is a JavaScript variable. Those can only be accessed in JavaScript. a JavaScript variable means nothing in PHP.
So, let's examine what you're doing from the JavaScript:
url: 'savescores.php?name=' +name +'&score=' + this.score,
For the purpose of explaining let's say name = Chipster, and this.score = 123.
What this code will do is try to open the following file:
savescores.php?name=Chipster&score=123
Remembering that PHP GET variables are set by the format script.php?var1=value1&var2=value2&var3=value3 // etc... we can see that there are 2 GET variables available from the PHP script called name and score. Thus, to access score from PHP you need to do it like this:
echo $_GET["score"];
This will output 123 in our example.
This may not solve your problem, but one issue I see with your code is calling strip_tags (or another function that alters the string) after it has already been quoted for insertion with mysql_real_escape_string may defeat the purpose of mysql_real_escape_string. It should be the very last function called on data before it's inserted.
Also, if score is an integer string, intval serves just as well as mysql_real_escape_string for sanitizing integers for insertion.
EDIT: You're also checking for GET variables in the PHP when the submission method used in the jQuery is POST. Try looking at $_POST instead of $_GET on the PHP side. You don't need to put variables in a query string if you're putting them in the request body via POST either.

How is dynamically created array in jquery is accessed in PHP

I have created a script that adds items on click into an array.
$(document).ready(function()
{
var array_ids = [];
$('.add').click(function()
{
array_ids.push($(this).parent().siblings('.row_id').html().trim());
alert(array_ids);
});
});
Items are coming from mysql database so I am storing primary keys of items. keys are stored in array like this manner
1,2,3,4,5
Now I want to access this array in php so that I could store in database one by one.
I thought to doing some ajax and this is my code
$('.show').click(function(e)
{
//e.preventDefault();
$.ajax(
{
method: 'POST',
url: 'createsale.php',
data: {items: array_ids},
success: function()
{
alert('done');
}
});
});
I get the done alert but couldn't manage to get it stored in database. Can anyone tell how do I insert those items in mysql?
Send the value from Javascript by using Json {"key":value} or array [1,2,3]. While getting them to use them in PHP, you can use json_decode() to convert the Json or array from Javascript to PHP.
If you want your information from PHP to Javascript, Just use the funtion json_encode() that will send a json string.
Ref: json_encode, json_decode
your createsale.php file should has something like this below code to receive array Data & dont forget to escape your data using mysql_real_escape_string before doing any mysql query
<?php
if(isset($_POST["items"]) && $_POST["items"] !=""){
$arr = $_POST["items"];
//convert JS array to PHP array
$arr = json_decode($arr,true);
//then you have your PHP array => new array(1,2,3,...);
/* use for/forEach loop
for($i=0;$i<count($arr);$i++){
do the task
}
*/
}
?>

Send javascript object with AJAX [duplicate]

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.

Categories