Pass a PHP array to a JavaScript function
In the following example you have an PHP array, then firstly create a JavaScript array by a PHP array:
<script type="javascript">
day = new Array(<?php echo implode(',', $day); ?>);
week = new Array(<?php echo implode(',',$week); ?>);
month = new Array(<?php echo implode(',',$month); ?>);
<!-- Then pass it to the JavaScript function: -->
drawChart(<?php echo count($day); ?>, day, week, month);
</script>
How can I pass an array from JS to PHP?
Convert the array to JSON with JSON.stringify()
. And instead of constructing the input as a string, use a jQuery function to do it:
$('<form action="csv_export/person?filename=export.csv" method="POST"/>')
.append($('{!! csrf_field() !!}'))
.append($("<input>", {
type: 'hidden',
name: 'arr',
value: JSON.stringify(arr)
});
).appendTo('body')
.submit();
In the PHP script, use json_decode($_POST['arr'], true)
to get the array.
You should also be able to use AJAX:
$.post('csv_export/person?filename=export.csv', { arr: JSON.stringify(arr) });
For a small array, you could just use { arr: arr }
and then access $_POST['arr']
as an array. But when you pass an array like this, each element becomes a separate post parameter, and by default PHP only allows 1000 parameters. You can change this in php.ini
, but using JSON is probably a simpler solution for this case.
Passing a JavaScript array to PHP
A straight forward way to do it is appending the values of your array to a hidden input field in a form.
- Use jquery to grab the list values and push to an array
- Convert the array into a string, ready for form submission
- Add a hidden input to a form with an id and an empty value attribute
- Append your string to this input field.
- On submit of your post, on PHP you will be able to see your array as a string.
- Convert back into array on the php side and presto!
You are welcome
Passing a php array to a javascript array inside a PHP function
I've heard that I can translate the array in javascript by using
<script>var records = <?php json_encode($records) ?></script>
but it doesn't work !
That doesn't work because you didn't echo
the result, you're simply running the JSON process and then discarding the result. Add an echo:
<script>var records = <?php echo json_encode($records) ?></script>
and contrary to the other answer, do not try to JSON.parse
this because it is already a valid JavaScript object.
Edit: if you're trying to concatenate the JSON to a response string then don't use <?php
tags, instead you can do:
$block .= '<script>var records = ' . json_encode($records) . '; </script>';
Passing (laravel) Array in Javascript
var app = @json($array);
Works like a charm
Passing array from Javascript to PHP via POST
$.post("mapper.php", {dataArray: selectedData});
This line is fine. I don't know why everyone is suggesting JSON, because that's unnecessary here. You can just POST objects/arrays normally without using JSON.
Note: this will not reload the page. It will POST to mapper.php
via AJAX, so aren't going to see anything anywhere on the page. You'd need to look in your dev tools to see what the AJAX call returned.
Or, you can check the data the POST returns.
$.post("mapper.php", {dataArray: selectedData}, function(data){
console.log(data); // check your console, you should see some output
});
how to use AJAX to pass JavaScript array to PHP array
If you want to send a request to PHP through ajax you have to create a PHP script file separately. I think we can't send requests to the same file. and here is the code that I use for ajax requests.
script.php this should be a separate PHP file.
<?php
if( isset($_POST['myData']) )
{
echo json_encode($_POST['myData']);
}
?>
Here is the jquery ajax code.
var str_array = [1,2,3]
$.ajax({
type: "POST",
url: "./script.php",
data: {myData:str_array},
dataType: "json",
success: function (response) {
console.log(response);
},
error:function(data) {
console.log(data.responseText);
},
});
Related Topics
PHP Regex to Get Youtube Video Id
Using a .PHP File to Generate a MySQL Dump
Post Request in Laravel - Error - 419 Sorry, Your Session/ 419 Your Page Has Expired
PHP Warning: PHP Startup: How to Load Dynamic Library
How Create an Array from the Output of an Array Printed With Print_R
How to Upload Images into MySQL Database Using PHP Code
How to Bind MySQLi Bind_Param Arguments Dynamically in PHP
Laravel 5.2 Validation Error Not Appearing in Blade
What Kind of String Is This? How to Unserialize This String
PHP: Convert Any String to Utf-8 Without Knowing the Original Character Set, or At Least Try
Login to Remote Site With PHP Curl
Download File Through an Ajax Call PHP
Search With Comma-Separated Value MySQL