$.post Jquery send array - javascript

I have problem with send array in $.post to php.
var_dump result is "NULL"
JSON.stringify doesn't work..
JQUERY
var photobox = [];
photobox.push(e.target.result);
$.post("../modules/upload.php",{"images[]" : photobox, count : sum},
function(data)
{
$('.list').prepend(data);
}).done(function() {
$('#files').prop('disabled', false);
$('.file-search').html("Szukaj...");
$(".img-thumbnail").removeClass("first");
$(".img-thumbnail").first().addClass("first");
e.target.result is base64 code
PHP
$images = $_POST['images'];
var_dump($images);

You can send arrays like this:
$.post('/thepage.php', {'NameOfKey': variableName});
The above code will allow VariableName to be an Array.

You would need to encode to JSON on your client, but when on your server (PHP) convert it back to an array by using json_decode:
http://php.net/manual/en/function.json-decode.php

Related

UTF-8 Passing Data from Javascript to PHP with Ajax

I'm having issues with formulating the right combination for an identical match of input and output from Javascript to PHP and then back to Javascript
Javascript Encode: (textarea=input1) => outputs to (textarea=input2)
btoa(unescape(encodeURIComponent(document.querySelector('.input1').value)));
PHP Decode: (textarea=input2) => outputs to (textarea=input3)
htmlspecialchars(SQLite3::escapeString(base64_decode($_POST['input2'])));
PHP Encode: (textarea=input3) => outputs to (textarea=input4)
base64_encode(htmlspecialchars(urldecode(($d['data']))));
Javascript Decode: (textarea=input4) => outputs to (textarea=input5)
decodeURIComponent(escape(atob(document.querySelector('.input4').value)));
But they do not match, I use https://text-compare.com/ to compare, it outputs in input and shows " and it also Deletes all + signs
How do I get a both input and output to match identically?
What I used, do correct me if I'm wrong/quicker way, it encodes, passes through ajax to php, decodes, encodes, passes back through ajax to js response, then final decode, the match from input to output was identical even with emojis
I'm posting the method below to help anyone in the same situation as I was
Method was
JS Encode: url > btoa
PHP Clean: ' ' > '+'
PHP Decode: json > base64 > url
PHP Encode: url > base64 > json
JS Decode: json > atob > url
JS Page:
Encode to pass through AJAX to PHP :
//create the json objects
var obj = {"data":{}};
//add data
obj['data'][0] = window.btoa(encodeURIComponent((data)));
Decode from PHP through AJax
//parse json
var json = JSON.parse(xhr.responseText);
//decode
var x = (decodeURIComponent(window.atob(json.data[0])));
Ajax Header: Post
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
PHP Page:
Decode:
//clean post
$clean = strtr($_POST["x"], ' ', '+');
//decode json
$obj = json_decode($clean, true);
//decode javascript post
$decode['data']['0'] = rawurldecode(base64_decode($obj['data'][0]));
Encode:
//encode javascript post
$encode['data']['0'] = base64_encode(rawurlencode($decode['data'][0]));
//encode json
echo json_encode($encode);
The clean of the post I got from this page JavaScript atob operation using PHP
The rawurl I got from this page PHP equivalent for javascript escape/unescape

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

Passing php array to javascript then accessing values by key

I'm using $.post to return an array from a separate php file, and trying to access the values of the array in javascript by the keys, but am having trouble doing so.
Here's the post code:
$(document).ready(function(){
var limRefresh = setInterval(refreshLIM, 10000);
var dbAction = "feedRefresh";
var newestRow = <?php echo $newestRow ?>;
$.post("jsDb.php",{ action: dbAction,lastRow: newestRow },function(status){
console.log(status);
console.log(newArr['status']);
console.log(newArr.status);
console.log(newArr[0]);
});
});
Here's the excerpt of how the response is being formatted in the external php file:
echo json_encode(array("status" => "success","actId" => $newActId));
And here's the respective console logs (just trying different options):
{"status":"success","actId":"585924418"}
undefined
undefined
{
Any ideas where I'm going wrong?
The response you get as status from $.post is a string. You need to parse it order to use it as you intend. Moreover, newArr is undefined because you have not defined it anywhere. This is probably because you have reused someone else's code and missed this part:
newArr = JSON.parse(status)
The response is coming as string, so you need to parse it before you can access it as JSON:
$.post("jsDb.php",{ action: dbAction,lastRow: newestRow },function(status){
var data = JSON.parse(status);
console.log(data['status'])
console.log(data['actId'])
}

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
}
*/
}
?>

JSON stringify and decode JS/PHP

I have a problem with sending an object in PHP. I stringify the object before sending it to the PHP file.
The PHP file then uses json_decode. But the decode shows a blank variable.
The object which i console.log shows this as its structure:
Its then sent to PHP with this :
console.log(my_Obj);
var as = JSON.stringify(my_Obj);
call_data('add.php?&as='+as, nxtFunc);
Now in the PHP file i have this which handles the situation:
$path = json_decode($_GET['as']);
echo $_GET['as'].'<br/>';
print_r($path);
die;
The result is:
[null,null,{\"8\":[null,null,null,null,null,null,[],[],[],[],[]],\"9\":
[null,null,null,null,null,null,null,null,null,null,[]],\"10\":
[null,null,null,null,null,null,null,null,null,null,[],[]],\"11\":
[null,null,null,null,null,null,null,null,null,null,null,[]]}]
<br/>
My XHR request url in Chrome shows:
add.php?as=[null,null,{%228%22:[null,null,null,null,null,null,[],[],[],[],[]],%229%22:[null,null,null,null,null,null,null,null,null,null,[]],%2210%22:[null,null,null,null,null,null,null,null,null,null,[],[]],%2211%22:[null,null,null,null,null,null,null,null,null,null,null,[]]}]
Notice the print_r shows nothing. Should i not be using stringify ?
Thats because my_Obj is an array and not an object.
Try this:
var as = JSON.stringify({data: my_Obj});
Note:
You will also need to clean up the array before stringifying - i.e. clear out all null/undefined indices. Check this answer: https://stackoverflow.com/a/281335/921204

Categories