write javascript array to file - php

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

Related

Cannot pass array to PHP script using Ajax

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?

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

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?

Javascript get form value in URL without jQuery

If data is submitted via POST through the classic HTML form method is it possible to access those values using standard Javascript without libraries? How would this be done?
Edit for clarity: The variables have been posted. I am trying to access those values via javascript.
Thinking outside the box: (A hack that should never see the light of day)
For this example the posted variable is "a":
var val=document.URL;
var start;
start = val.search(/a=/);
var end;
end = val.search(/&/);
var thispos = val.substring(start+2,end);
document.URL returns the url of the current site.
val.search returns the position of the first occurrence of the regular expression in
the parameter field.
substring the two and...
thispos now contains the posted variable.
Brutal but functional. Is this too terrible to be an answer?
use:
var myField = document.getElementById('myFieldId');
then myField.value will contain the value.
If you have submitted the page, then you have to get the form data using PHP.
Here is a tutorial that should help: http://www.phpf1.com/tutorial/php-form.html
But if you decide to test jQuery, you can use this:
jQuery('#submit').live('click', function()
{
var form_data = jQuery("#data_form").serialize();
//Save data
jQuery.ajax({
url: siteURL +"/path/to/php/file/jquery.php",
data: {formData : form_data,
success: (function(data) {
//data is whatever you return from jquery.php
//I use json for return data
alert('Data has been saved');
}),
dataType: 'json'
});
After a post, the data is send to the server, javascript cant do anything with that since its client side. What you can do is pre-check with document.getElementById('formid') and use those values in the form. After validating or doing what you want to do, end with form.submit() to really send it to the server.
function getUrlInfo() {
var data = window.location.search.substring(1).split("&");
//returns an array of strings containing the params and their values
// data = [ "param=value","param=value","param=value"]
var params1Array = data[0].substring(0).split("=");
//Splits the first string element at the "=" symbol and
//returns an array with the param and value
//param1Array = ["param","value"]
var param1Value = param1Array[1].replace("+", " ");
//Gets the value from the second element in the param1Array
//Replaces the spaces, if any, in the second element,
//which is the value of the url param
var param2Array = data[1].substring(0).split("=");
//Repeat steps for the second param element,in the url params data array
var param2Value= param2Array[1].replace("+", " ");
return {
param1Value,
param2Value
}
};
The submitted data (either POST or GET) is proccesed on the server side. Javascript runs on the client-side so you can't access the variables from the page receiving the form request.
But you can access them before the post using the input field id (specially to check the input values before sending them).

How To Call Javascript In Ajax Response? IE: Close a form div upon success

I have a form that when you submit it, it sends the data for validation to another php script via ajax. Validation errors are echo'd back in a div in my form. A success message also is returned if validation passes.
The problem is that the form is still displayed after submit and successful validation. I want to hid the div after success.
So, I wrote this simple CSS method which works fine when called from the page the form is displayed on.
The problem is that I cannot seem to call the hide script via returned code. I can return html like
echo "<p>Thanks, your form passed validation and is being sent</p>";
So I assumed I could simply echo another line after that
echo "window.onload=displayDiv()"; inside script tags (which I cannot get to display here)...
and that it would hide the form div.
It does not work. I am assuming that the problem is that the javascript is being returned incorrectly and not being interpreted by the browser...
How can I invoke my 'hide' script on the page via returned data from my validation script? I can echo back text but the script call is ineffective.
Thanks!
This is the script on the page with the form...
I can call it to show/hide with something like onclick="displayDiv()" while on the form but I don't want the user to invoke this... it has be called as the result of a successful validation when I write the results back to the div...
<script language="javascript" type="text/javascript">
function displayDiv()
{
var divstyle = new String();
divstyle = document.getElementById("myForm").style.display;
if(divstyle.toLowerCase()=="block" || divstyle == "")
{
document.getElementById("myForm").style.display = "none";
}
else
{
document.getElementById("myForm").style.display = "block";
}
}
</script>
PS: I am using the mootools.js library for the form validation if this matters for the syntax..
The AJAX call is:
window.addEvent('domready', function(){
$('myForm').addEvent('submit', function(e) {
new Event(e).stop();
var log = $('log_res').empty().addClass('ajax-loading');
this.send({
update: log,
onComplete: function() {
log.removeClass('ajax-loading');
}
});
});
});
Div ID log is where the ajax call back text (validation errors and success message) and loading graphic appear
This is a duplicate of How to make JS execute in HTML response received using Ajax? where I provided the chosen solution.
var response = "html\<script type=\"text/javascript\">alert(\"foo\");<\/script>html";
var reScript = /\<script.*?>(.*)<\/script>/mg;
response = response.replace(reScript, function(m,m1) {
eval(m1); //will run alert("foo");
return "";
});
alert(response); // will alert "htmlhtml"
Your AJAX call should have a "success" callback. It looks like you can simply call displayDiv() in that callback.
Also note that the var divstyle = new String(); line is unnecessary. Strings are immutable in JavaScript, so you are creating an empty string object, which remains unreferenced in the following line. Simply declare the variable when you assign it from document.getElementById():
var divstyle = document.getElementById("myForm").style.display;
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
//Since your making php do the validation, there would be two cases,
//the first case is that the php script is not echoing any thing on success, and
//the other case is that its echoing the error massages which will be assignedxmhttp.responseText
//so we need to check that xmlhttp.resposeText has been asigned a value.
if(xmlhttp.resposeText){
document.getElementById(displayContainers_id).innerHTML=xmlhttp.responseText;
}
}

Categories