using AJAX query to pass javascript array to php - javascript

After reading through quite a few posts here, (and even just straight copying code,) I still cannot figure out why this is not working.
On my main page, I have a textbox that a user pastes data into. Upon paste, this script runs (this and the ajax query below are in the same script function):
var lines = $('textarea').val().split('\n'); //create array from pasted data
I now have a JavaScript array with the pasted data. I'm trying to send this over to a separate PHP file that I will load into a div on this main page by doing the following:
$.ajax({
type: 'POST',
url: 'return.php',
data: {lines:lines},
success:function(data){
$("#info").load("return.php");
}
});
for (i=0; i < lines.length; i++) { // log the output
if (lines[i]){
console.log("line ", i , lines[i]);
}
}
In my return.php file, I have this:
$lines = $_REQUEST['lines'];
echo '<pre>';
echo($lines);
echo '</pre>';
My console.log is outputting the array perfectly, but for some reason it is not making its way over to return.php, as my echo is blank.
What am I doing wrong?
The response I get from return.php is:
<pre>testArrayArray
(
[0] => DL4004-13-F
[1] => S1G-13-F
[2] => ZXMP3A13FTA
[3] => B260A-13-F
[4] => S1J-13-F
[5] => S3B-13-F
[6] => SSN1N45BTA
[7] => GBJ1010-F
[8] => BPW20RF
[9] => T3035H-6I
[10] => ZXMP7A17KTC
[11] =>
)
</pre>

The success handler on your ajax request is calling return.php with nothing and loading it into #info.
Change success to instead do:
$("#info").html(data)

The $lines variable in your PHP code is an array, not a string. If you have the errors turned on, PHP should warn you that you're doing an "Array to string conversion" (at least it does for me using your code).
You can't echo an array like that, you have to iterate through the results somehow.

Related

Can't select specific element in JSON parsed array with JavaScript

So I have a mySQL database and I am pulling data from it to my website and want to change content with the help of JavaScript. The problem is that I can't seem to select specific elements out of my data which I received from the databse.
Here is how I pull data and parse it into a JSON string:
while($row = $result->fetch_assoc()) {
$return_array = array("region" => $row['region'], "capital" => $row['capital'], "surface_area" => $row['surface_area'], "land_area" => $row['land_area'], "water_area" => $row['water_area'], "global_area_rank" => $row['global_area_rank'], "land_boundary" => $row['land_boundary'], "bordering_countries" => $row['bordering_countries'], "coastline" => $row['coastline'], "climate" => $row['climate'], "terrain" => $row['terrain'], "avg_elevation" => $row['avg_elevation'], "highest_elevation" => $row['highest_elevation'], "lowest_elevation" => $row['lowest_elevation'], "natural_resources" => $row['natural_resources'], "land_use" => $row['land_use'], "irrigated_land" => $row['irrigated_land'], "natural_hazards" => $row['natural_hazards']);
}
echo json_encode($return_array);
In my JavaScript method I call this PHP script and receive the parsed JSON string which I temporarily output in a single div:
$.post('ajax/retrieve_data.php', { sel1: sel1, sel2: sel2 }, function(data) {
var return_array = $.parseJSON(data);
$('div#test-div').text(return_array.region);
});
The output however, just shows the entire JSON string with curly brackets and all identifiers, which means that the return_array.region selector does not work. I tried it with indices and all sorts of other syntax, but it did not work. Everywhere on the internet everyone uses this syntax to select specific elements, but it somehow doesn't work. I probably have a very stupid error in there, but I appreciate every help. I just can't seem to see the error.
My guess is that your PHP script isn't returning data with the proper Content-Type header. Make sure, in your PHP script, you run the following:
header('Content-Type: application/json');
This must come before echoing anything.

How to flush PHP output buffer properly?

I need PHP to stream output to Javascript but Javascript keeps the old responses and prints them like so...
Console logs:
[0]: Line to show.
[0]: Line to show.[1]: Line to show.
[0]: Line to show.[1]: Line to show.[2]: Line to show.
[0]: Line to show.[1]: Line to show.[2]: Line to show.[3]: Line to show.
[0]: Line to show.[1]: Line to show.[2]: Line to show.[3]: Line to show.[4]: Line to show.
[0]: Line to show.[1]: Line to show.[2]: Line to show.[3]: Line to show.[4]: Line to show.Array
(
[0] => [0]: Line to show.
[1] =>
[2] =>
[3] => [1]: Line to show.
[4] =>
[5] =>
[6] => [2]: Line to show.
[7] =>
[8] =>
[9] => [3]: Line to show.
[10] =>
[11] =>
[12] => [4]: Line to show.
[13] =>
[14] =>
)
So Javascript console logs state that the responseText is "saving" old responses. However, take a look at the array I saved in PHP and you can see that no previous echos are flushed to JS.
Javascript:
$.ajax({
url: "../controller/controller.php",
type: "POST",
data: {operation: 'rxMode'},
xhr: function(){
var xhr = $.ajaxSettings.xhr();
xhr.onprogress = function(e){ console.log(e.currentTarget.responseText); };
console.log(xhr);
return xhr;
}
});
PHP:
$out = array();
for ($i = 0; $i<5; $i++){
echo "[$i]: Line to show.";
array_push($out, ob_get_contents());
ob_flush();
array_push($out, ob_get_contents());
flush();
array_push($out, ob_get_contents());
sleep(2);
}
print_r($out);
My desired responseText is
[0]: Line to show.
[1]: Line to show.
[2]: Line to show.
[3]: Line to show.
[4]: Line to show.
Edit: I do not want to remove the old responses rather I would prefer that Javascript only gives me my desired responseText.
responseText always contains the entire response from the server. When you use the progress event, it contains the accumulated response so far, not just the incremental string added to the response in the most recent flush from the server.
Save the length of the previous response text in a variable, and then on subsequent calls just print the substring after that.
var responseLen = 0;
$.ajax({
url: "../controller/controller.php",
type: "POST",
data: {operation: 'rxMode'},
xhr: function(){
var xhr = $.ajaxSettings.xhr();
xhr.onprogress = function(e){
console.log(e.currentTarget.responseText.substr(responseLen));
responseLen = e.currentTarget.responseText.length;
};
console.log(xhr);
return xhr;
}
});

Associative php array sent via jquery returns [Object object]

I have to pass a php multidimensional array via ajax/jQuery to another php file.
I have encoded the array using
I expected theat every item in the array would have been an array itself. Instead it returns [Object object].
How can I access the data using php?
here's my code:
in the first php file:
<script type="text/javascript">
var arr_data = <?php echo json_encode($itemsData); ?>;
$("#confirmButton").click(function(){
$.post("send_test.php", {"my_array_data[]":my_array_data}, function( data ) {
alert(data);
});
});
</script>
the other php file:
<?php
$my_array_data = $_POST['my_array_data'];
?>
if I try to retrieve the first row ($my_array_data[0]) I get [Object object]
I just want to access to $my_array_data[0]['category'] etc.
A couple of errors here:
the data you are passing to ajax has an incorrect key using brackets[]
you are not passing the correct object through ajax since my_array_data is never defined
redo your code like this:
PHP
$itemsData = array(
array(
"test" => 30,
"test2" => 10,
),
array(
"test" => 90,
"test2" => 50,
)
);
JS
var arr_data = <?php echo json_encode($itemsData); ?>;
$("#confirmButton").click(function () {
$.post("send_test.php", {my_array_data: arr_data}, function (data) {
console.log(data);
});
});
Then in send_test.php
$data = $_POST['my_array_data'];
print_r($data);
Result:
Array
(
[0] => stdClass Object
(
[test] => 30
[test2] => 10
)
[1] => stdClass Object
(
[test] => 90
[test2] => 50
)
)
You're putting json-encoded data into the arr_data javascript variable - however you don't appear to be sending that to the other php file.
In the other php file, try using json_decode on the data you're receiving in the POST request:
$my_array_data = json_decode($_POST['my_array_data']);
Yes, as Aric says, name array consistently like this:
var my_arr_data = <?php echo json_encode($itemsData); ?>;

Create and edit file javascript with "file_put_contents"?

i would like to create a file.js with php but i think that in my code there are a lot of errors:
i have multidimensional array:
$report= array();
$report= array(array(3,6),array(4,8));
that is:
Array
(
[0] => Array
(
[0] => 3
[1] => 6
)
[1] => Array
(
[0] => 4
[1] => 8
)
)
Set a content-type for js file
$header = "Content-type: text/javascript";
$dir = "outreport/";
$nomefile = "report.js";
//delete a file with same name if exists
foreach (glob($dir."*".$nomefile) as $v){
unlink($v);
}
$percorso = $dir.$nomefile;
file_put_contents($percorso, $report);
header($header);
print($report);
There are two problems:
1) when launching the file.php asks me to download the same file but in javascript
2) in the "outvulcani" it creates the file report.js but is empty
I wish that in the file "report.js" there is the array $report but
written in javascript code:
var reports = [
[3,6]
[4,8]
];
Kindly, you can help me out?
Thanks a lot!
Sorry for my english
PHP has an function to convert Arrays to JSON. You could use this code for "inspiration".
$report = array(array(3,6),array(4,8));
$javascriptContent = json_encode($report);
// Convert to string
$javascriptContent = "var reports = ". $javascriptContent . ";\n";
file_put_contents($percorso, $javascriptContent);
The reason for "Download" is the header, please remove it.

Populating Google Map Markers from PHP array using json_encode

When I use the hard coded javascript array as input for the map markers the markers show up just fine, so I know that the code I'm using to display the markers is good.
My problem is when I try and convert a php multi-array using json_encode, nothing shows up on the map.
The hard coded markers are:
var locations = [
['Sausalito', 37.8590937, -122.4852507,'url'],
['Sacramento', 38.5815719, -121.4943996,'url'],
['Soledad', 36.424687, -121.3263187,'url'],
['Shingletown', 40.4923784, -121.8891586,'url']
];
and they work.
The php array is:
$locations = array(array(Sausalito, 37.8590937, -122.4852507,'url'),array(Sacramento, 38.5815719, -121.4943996,'url'));
which produces the array,
Array
(
[0] => Array
(
[0] => Sausalito
[1] => 37.8590937
[2] => -122.4852507
[3] => url
)
[1] => Array
(
[0] => Sacramento
[1] => 38.5815719
[2] => -121.4943996
[3] => url
)
)
so no problem as yet.
Now when I json_encode the above array
var locations = '<?php echo json_encode($locations); ?>';
it does not get read by the javascript map code. and if I print the variable
document.write(locations);
it shows up as
[["Sausalito",37.8590937,-122.4852507,"url"],["Sacramento",38.5815719,-121.4943996,"url"]]
which kinda looks like the hard-coded above, but it does not get read by the map code which works with the hard-coded data.
Can anyone assist me, please, much appreciated.
Remove the single-quotes, otherwise locations will be a string and not an array:
var locations = '<?php echo json_encode($locations); ?>';
//--------------^--------------------------------------^

Categories

Resources