Cannot pass array to PHP script using Ajax - php

I'm having a weird problem here and I can't seem to figure out why I can't pass one array to the PHP script using ajax, but I can pass another array without any problems.
Here's my ajax function:
function update(){
var hr = new XMLHttpRequest();
var url = "update.php";
var vars = "array="+arr;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.send(vars);
}
The variable "arr" is a 2d array loaded with coordinates, like so: [[2,3],[4,5],[5,2]...] and it's user-generated, every time user inserts new set of coordinates, I use PUSH to add them to the array.
It is declared just above this function, inside the javascript.
This seems to be working fine, because when I do alert(JSON.stringify(arr)); inside the ajax function, I can see clearly the coordinate pairs pop up in my browser.
However, when I catch the array on the other side (php script) and write it into a notepad file using:
<?php
$fp=fopen("ajax.txt","w");
$data = $_POST['array'];
fwrite($fp,$data);
fclose($fp);
?>
The file ajax.txt is created but remains empty.
However, when I initialize another array (arr1) inside the ajax function, like this:
function update(){
var arr1=[[2,3],[4,5],[5,7]];
var hr = new XMLHttpRequest();
var url = "update.php";
var vars = "array="+arr1;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.send(vars);
}
The PHP script seems to write the array to the notepad file without any problems! Why does this happen? Clearly the "arr" variable is not empty, because we can see the contents of it using alert.
Any ideas?

Related

JavaScript variable to php session variable

so I got this really simple jQuery datatable, and i'm trying to get my selected value into a php variable. Here is my code:
<script>
var hlr = 0; // Reference to the currently highlighted row
function rowClick()
{
if (hlr)
$("td:first", hlr).parent().children().each(function(){$(this).removeClass('markrow');});
hlr = this;
$("td:first", this).parent().children().each(function(){$(this).addClass('markrow');});
// You can pull the values out of the row here if required
var a = $("td:first", this).text();
var b = $("td:eq(1)", this).text();
//$_SESSION['Klantnaam']="+a+");
alert("Keuze = "+a+""); //this is what I need in my PHP session variable.
}
</script>
Thanks for reading, a response is highle appreciated.
I had already faced this question on my recent project
Here is my solution to you
But i had to take value in to session variable so
STEPS:
Created a php file which puts value to session variable
Send a ajax request to that php file with js var value

Add javascript in php mysql query

I know this sound weird but I need to be able to use a variable in javascript and use it inside a php mysqli query
I use the jQuery File Upload from blueImp. It's variable are store like this
{%=file.name%}
and I need to do something like this
$iq = $mysqli->query("SELECT * FROM image WHERE mId='".$_GET['mId']."' AND file_name = '".{%=file.name%}."'");
of course this is not working because of the {}.
Anyone have a clue how to work with those kind of programming ?
In javascript:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4) {
//POST request sent
}
};
xmlhttp.open("POST", "url_to_phpfile.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("yourvariable="+yourvariable);
Then you can use that variable in your php file like so:
$iq = $mysqli->query("SELECT * FROM image WHERE mId='".$_GET['mId']."' AND file_name = '".$_POST["yourvariable"]."'");
No, you cannot directly do this**.
Javascript is something that will execute at client side(browser).
PHP is a server side scripting language.
If you want to pass a Javascript variable in PHP , then you can do so through AJAX

write javascript array to file

i have loaded a file into an array using ajax and after splitting it i need to save it to the file again.This all happens onClick of a button.
function updatetags(){
var alreadyexistingtags;
var responsetext;
var r2 = new XMLHttpRequest();
r2.open('GET', 'tagsupdated.txt', true);
r2.send(null);
r2.onreadystatechange = function() {
if (r2.readyState == 4 && r2.status==200) {
responsetext=r2.responseText;
alreadyexistingtags=responsetext.split(' ');
}
}
}
i understand that javascripts are not server side and that's why i cannot do what i want,but i'm sure there must be a way to write alreadyexistingtags[ ] to tagsupdated.txt.Any help?Perhaps i should somehow pass the array to PHP?And if so how is that possible given that PHP gets executed when the page loads,when i need to wait for the button to be pressed?
You're going to have to use AJAX or some other method to send the data back to your server, which can then write the file out.
To do this, just create a new script on your server, say writearray.php, which accepts the Javascript array as input. Then use AJAX to send a request to that file with your array.
The PHP file would look something like so (this is a highly simplified example):
<?php
file_put_contents("where_you_want_the_file.txt", $_POST['array']);
?>
It looks like you're just storing your Javascript array as a space separated list, so the Javascript would look something like this:
var str = your_array.join('%20'); // URL encoded spaces separating array entries
var params = "array=" + str;
var http = new XMLHttpRequest();
http.open("POST", "your_script.php", true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
// Do something on success?
}
}
http.send(params);
The way this works, is you're sending a POST with a field named array, which holds the textual representation of your Javascript array. The PHP code checks $_POST['array'] to get this value, then writes it to your file.
Note that if you want to do anything more complicated, you should look into using JSON. And also as always be very careful with what you do with user data.
For send data you must doing another ajax query but in .send method you have to pass a string with data
Example:
var r3 = new XMLHttpRequest();
r3.open('POST', 'writeTextWithoutTags.php', true);
var data_string='text='+alreadyexistingtags+'&etcParams='+etc_you_params;
r3.onreadystatechange = function()
{
if (r3.readyState == 4 && r3.status==200)
{
alert(r3.responseText);//write result
}
}
r3.send(data_string);
Before sent alreadyexistingtags variable you must implode array to string with separator or better to JSON string.
But in writeTextWithoutTags.php ypu must check data because javascript execute ib user brouser and you can not be sure that the data is sent from yavastsript not undergone processing intruder!
P.S. If you can access to PHP I dont understang I do not understand why you are here JS - all this actions you can douing in PHP and not to drive data from the server to the browser and back

Use php to populate javascript array

All,
I have the following bit of code:
function addPoints() {
newpoints[0] = new Array(41.45998, 87.59643, icon0, 'Place', 'Content to open');
for(var i = 0; i < newpoints.length; i++) {
var point = new GPoint(newpoints[i][1],newpoints[i][0]);
var popuphtml = newpoints[i][4] ;
var marker = createMarker(point,newpoints[i][2],popuphtml);
map.addOverlay(marker);
}
}
There is other code around this to display the marker on my map. However this value is hardcoded. I have a PHP/mySQL database that has lat/long coordinates along with some other values. Say I have like three entries that I want to create markers for. How would I pass the addPoints function the lat/long that I got from my database so I can use it in this function correctly?
I updated my code to look like the following for the addPoints:
function addPoints(num, lat, long) {
newpoints[num] = new Array(lat, long, icon0, 'Place', 'Stuff name');
alert("The newpoints length is: "+newpoints.length);
for(var i = 1; i < newpoints.length; i++) {
var point = new GPoint(newpoints[i][1],newpoints[i][0]);
var popuphtml = newpoints[i][4] ;
var marker = createMarker(point,newpoints[i][2],popuphtml);
map.addOverlay(marker);
}
}
I call this function by doing this:
<script>
addPoints('<?php echo json_encode($num_coordinates); ?>','<?php echo json_encode($lat_coordinates); ?>', '<?php echo json_encode($long_coordinates); ?>');
</script>
It doesn't work though. When I try not to pass it to javascript and just output the lat coordinates for example. I get the following output:
{"1":"40.59479899","2":"41.4599860"}
Which are the correct coordinates in my array. No markers get created though. Any ideas on what to do next or what I'm doing wrong?
An easy and clean way to pass an array from PHP to JavaScript is to simply echo the json_encode version of the array.
$array = array(1,2,3,4,5,6);
echo 'var values = '.json_encode($array).';';
PHP executes on the server before getting sent to the the client. Therefor, if you can do things like this:
newpoints[0] = new Array(<?php echo $lattitude;?>, <?php echo $longitude;?>, icon0, 'Place', 'Content to open');
Where $lattitude and $longitude are values that you pulled out of you database with PHP.
When this page is requested by the client, your php code executes, real values get plugged in where those php tags are making it look like the example you provided, and then it gets sent to the client.
If you want to change these values using JS on the client, or fetch new ones from the server, let me know and I'll add an example of that.
EDIT:
Okay, in light of your comments, it sounds like you've got a few options. Here's one:
When the user selects a category (restaurants, bars, etc) you pass that category as a url parameter and reload either the whole page, or just the map part of it (depends on your set up but might be worth investigating). Your link would look something like this:
http://www.your-domain-here.com/maps.php?category=bars
Maps.php is ready to catch the category using the $_GET array:
$category = $_GET['category']; //'bars'
Your php then grabs the appropriate location data from the database (I'll leave that part to you) and sticks it in a variable that your JS-controlled map will be able to use:
//JS in maps.php - you could add this var to the window object
// if you have separated js files...
var locationCoords = <?php echo json_encode($arrayOfCoordinatesFromDB);?>;
When you page loads on the client machine, it now has an array of coordinates to use for the map ready to go in the locationCoords variable.
Then, depending on which coordinates you need to display on the map, you pass them as arguments to your addPoints() using standard Javascript (nothing tricky here).
That's how I'd do it. Hope that helps!
It is as simple as echoing the php values.
new Array(<?php echo $php_lat;?>, <?php echo $php_long;?>, icon0 etc...
I made a dynamic banner with this javascript array initialization. It works fine when the javascript is embedded in php.
<?php
// This is our php array with URLs obtained from the server
$urlsPHP = ["img/img01.jpg","img/img02.jpg","img/img03.jpg"];
return = "
//...Some HTML...
<script type='text/javascript'>
// Now we use this inside the javascript
var urlsJavaScript = ".stripslashes(json_encode($urlsPHP)).";
//...Some javascript style to animate the banner...
</script>
";
// if we print this:
echo stripslashes(json_encode($urlsPHP));
// We obtain:
// ["img/banner/bak01.jpg","img/banner/bak02.jpg","img/banner/bak03.jpg"]
// This is a good syntax to initialize our javascript array
// if we print this:
echo json_encode($urlsPHP);
// We obtain:
// ["img\/banner\/bak01.jpg","img\/banner\/bak02.jpg","img\/banner\/bak03.jpg"]
// This is not a good syntax to initialize our javascript URLs array
?>

Issue with PHP + Ajax + Sql

I'm sure it is just a simple issue, I have looked in the forums but couldn't find an example that was specific to my issue.
Basically I am displaying a table of hrefs, which each have an onclick() call to an ajax method, using a 'get' and a url.
function createRequestObject(){
var req;
if(window.XMLHttpRequest){
//For Firefox, Safari, Opera
req = new XMLHttpRequest();
}
else if(window.ActiveXObject){
//For IE 5+
req = new ActiveXObject("Microsoft.XMLHTTP");
}
else{
//Error for an old browser
alert("Your browser is not IE 5 or higher, or Firefox or Safari or Opera");
}
return req;
}
//Make the XMLHttpRequest Object
var http = createRequestObject();
function sendRequest(method, url){
if(method == "get" || method == "GET"){
http.open(method,url,true);
http.onreadystatechange = handleResponse;
http.send(null);
}
}
function handleResponse(){
if(http.readyState == 4 && http.status == 200){
var response = http.responseText;
if(response){
document.getElementById("DIVNAME").innerHTML = response;
}
}
}
The call for an href looks like:
echo '<td><a href="#" onClick="sendRequest(\'get\', \''.$toPass.'\')"/>'.$variable.'</a></td>';
The $toPass variable is page.php?variable1='.$variable1.'&variable2='.$variable2.'&variable3=blah&action='.$option.'
When I pass a variable 1 for example : 'TP111010114' it works fine, the _REQUEST['variable1']; grabs the variable and pushes it the through my sql request.
if the variable contains a # for example : 'Blah #2' the only piece of data that gets through is
Variable 1 = 'Blah ' with the remaining variables being unassigned.
From what it looks like it is not getting anything after the #.
I tried encoding the url in php, then unescaping it in my ajax.js where you call window.open('get', unescape(url), true); but I had the same result, it worked with any variable that didn't contain #. When I tried to encode it using urlencode() and not decoding it in my ajax.js, the request was not going through.
The encoded request looks like:
page.php%3Fvariable1%3DTP111010114%26variable2%3D64%26variable3%3Dnew%26Action%3DOthers
if it is not encoded it looks like:
page.php?variable1=TP111010114&variable2=64&variable3=new&Action=Others
I used firebug to monitor the .js variables as they go through and it looks as though when I encode it that it should grab the proper variable, but it still only grabs before the # in the variable
http://www.randomsite.ca/page.php?variable1=WF225+Amendment+#2&variable2=543&variable3=new&Action=Others
Yet this request on the php side still gets $variable = $_REQUEST['variable1']
$variable = 'WF225 Amendment ', and the other variables are unnassigned.
It must be something to do with the way something is handling the #, but I do not see what I am missing here, if anyone could help it would be much appreciated.
I have renamed information for privacy purposes
You need to urlencode the values you're putting into the URL, not the whole URL including variable names. You want to encode the "blah #2" but not the "&variable1=" part. Ex:
$toPass = 'page.php?variable1=' . urlencode($variable1) . '&variable2=' . urlencode($variable2) ...etc
You won't need any decoding on the HTML/JS end.
I believe that it may be parsing anything after the # as a named anchor which will likely disregard the variables after this point... have you tried using a method that doesn't rely on the # character? Or even try using POST as the AJAX method?

Categories