Here is the Javascript AJAX code:
var anything=document.getElementById("textarea").val;
I have Javascript AJAX implemented:
httpRequest.open('POST',anyURL,true);
http.send(anything);
Now, my question is since this is the post data, and this is not actually associated with any html tag or id, how do I receive this in php?
<?php
$parameter=$_POST[' '];
?>
What should I put in the white space there?
Add a new variable and use JSON.stringify on your anything variable that was turned into a key value pair.
var anything={myTextArea: document.getElementById("textarea").value};
var JSONstr = JSON.stringify(anything);
PHP:
<?php
$parameter=$_POST['JSONstr'];
?>
Related
I know there a fair few entries on SO and the web on this however I just can't get to work - any help would be appreciated.
So i have an array in Javascript which I'm trying to pass on to PHP.
I've got a little JS function to first POST it, so:
function sendToPHP() {
$.post("index.php", { "variable": toSearchArray });
}
Then down the page, I have the PHP:
<?php
$myval = $_POST['variable'];
print_r ($myval);
?>
*The prints just there for me to check.
Any ideas - fyi I'm using MAMP so its localhost:8888/index.php. Could this be causing issues in that the URL is not correct?
Thanks.
You have a misunderstanding about how ajax works. Although jquery makes it easy, it is still not automatic. You should just find a tutorial about ajax with jquery, but if you want to just send an array to php and see the output on screen, something like this would work:
index.php
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//attach to the button a click event
$('#btn').click(function(){
//get the value from the textbox
var txt=$('#txt').val();
//if txt is blank, alert an error
if(txt == ''){
alert("Enter some text");
} else {
//send txt to the server
//notice the function at the end. this gets called after the data has been sent
$.post('catcher.php', {'text':txt}, function(data){
//now data is an object, so put the message in the div
$('#response').text(data.message);
}, 'json');
}
});
});
</script>
</head>
<body>
<input type="text" id="txt">
<input type="button" id="btn">
<pre id="response" style="overflow:auto;width:800px;height:600px;margin:0 auto;border:1px solid black;"> </pre>
</body>
</html>
catcher.php:
<?php
//if something was posted
if(!empty($_POST)){
//start an output var
$output = array();
//do any processing here.
$output['message'] = "Success!";
//send the output back to the client
echo json_encode($output);
}
It is better to use 2 files, one for the user to load that initiates the ajax call and one page to handle the ajax call. Sending an array works the same, just replace getting the textbox value with sending an array.
Instead of declaring variable toSearchArray as array. consider it an javascript object.
var toSearchArray = {}.
This is what happens when you open your page (index.php)
A GET request is issued to index.php and the content is returned. There are no values in the $_POST array so your print_r() line does nothing.
Javascript is executed that sends a POST request to index.php via AJAX. Note that this is an entirely new request, separate to the original GET. The $_POST array will be populated on this request however the response is discarded.
Hopefully this will illustrate what you can do.
ajax.php
<?php
header("content-type: application/json");
exit(json_encode($_POST));
index.php
<script>
const toSearchArray = ['some', 'array', 'with', 'values'];
$.post('ajax.php', {
variable: toSearchArray
}).done(data => {
console.log(data) // here you will see the result of the ajax.php script
})
</script>
Well I don't think thats the right way to do it when it comes to arrays, see you need to use JSON encode in javascript then JSON decode in php
Refer to this question Pass Javascript Array -> PHP
I know there a fair few entries on SO and the web on this however I just can't get to work - any help would be appreciated.
So i have an array in Javascript which I'm trying to pass on to PHP.
I've got a little JS function to first POST it, so:
function sendToPHP() {
$.post("index.php", { "variable": toSearchArray });
}
Then down the page, I have the PHP:
<?php
$myval = $_POST['variable'];
print_r ($myval);
?>
*The prints just there for me to check.
Any ideas - fyi I'm using MAMP so its localhost:8888/index.php. Could this be causing issues in that the URL is not correct?
Thanks.
You have a misunderstanding about how ajax works. Although jquery makes it easy, it is still not automatic. You should just find a tutorial about ajax with jquery, but if you want to just send an array to php and see the output on screen, something like this would work:
index.php
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//attach to the button a click event
$('#btn').click(function(){
//get the value from the textbox
var txt=$('#txt').val();
//if txt is blank, alert an error
if(txt == ''){
alert("Enter some text");
} else {
//send txt to the server
//notice the function at the end. this gets called after the data has been sent
$.post('catcher.php', {'text':txt}, function(data){
//now data is an object, so put the message in the div
$('#response').text(data.message);
}, 'json');
}
});
});
</script>
</head>
<body>
<input type="text" id="txt">
<input type="button" id="btn">
<pre id="response" style="overflow:auto;width:800px;height:600px;margin:0 auto;border:1px solid black;"> </pre>
</body>
</html>
catcher.php:
<?php
//if something was posted
if(!empty($_POST)){
//start an output var
$output = array();
//do any processing here.
$output['message'] = "Success!";
//send the output back to the client
echo json_encode($output);
}
It is better to use 2 files, one for the user to load that initiates the ajax call and one page to handle the ajax call. Sending an array works the same, just replace getting the textbox value with sending an array.
Instead of declaring variable toSearchArray as array. consider it an javascript object.
var toSearchArray = {}.
This is what happens when you open your page (index.php)
A GET request is issued to index.php and the content is returned. There are no values in the $_POST array so your print_r() line does nothing.
Javascript is executed that sends a POST request to index.php via AJAX. Note that this is an entirely new request, separate to the original GET. The $_POST array will be populated on this request however the response is discarded.
Hopefully this will illustrate what you can do.
ajax.php
<?php
header("content-type: application/json");
exit(json_encode($_POST));
index.php
<script>
const toSearchArray = ['some', 'array', 'with', 'values'];
$.post('ajax.php', {
variable: toSearchArray
}).done(data => {
console.log(data) // here you will see the result of the ajax.php script
})
</script>
Well I don't think thats the right way to do it when it comes to arrays, see you need to use JSON encode in javascript then JSON decode in php
Refer to this question Pass Javascript Array -> PHP
I use DHTMLX. I want to use the ajax component get the data from php, the php will create the xml. How to get this xml data into javascript.
enter code here
dhtmlxAjax.get("php/getUsername.php", function(r){
r = r.xmlDoc.responseXML; // will give you DOM object
//console.log(r.firstChild.tagName);
alert(r.firstChild.tagName("param1"));
});
thank you
Just use the php echo function to echo the php variable into a java script variable.
eg. If you have a php variable called $XMLData you would do the following
var XMLdata = <?php echo $XMLData; ?>
Then on page load your php variable becomes a javascript variable and can be used. from anywhere in javascript provided that the variable is within its scope.
Im trying to send a variable from a controller to a JavaScript, I have my controller, and I can send an array:
public function index()
{
$casa = new Casa(true);
$result = $casa->where(['show'=>true])->get();
return view('casa', array('casa' => $result));
}
If i go to my HTML and I make and echo:
<html>
<body>
<?php echo $casa ?>
</body>
</html>
I can show my array in the body, I was thinking about make an invisible element and get the array with document.getElementById().innerHTML, but I think this is not the best way.
Also, I think that I could make an Ajax petition sending a post and get the result, but I dont know if I can get my variable in a simpler way.
I tried to make and echo in Javascript and doesn´t work. some ideas?
Can I have 2 method post to get request in my controller? I already have one to get data from a form, and if I set the Ajax request I will have two post request. I would like have just one.
Jeffrey Way created a package for that. He also made a video explaining it in laracasts.com.
The package can be found here: https://github.com/laracasts/PHP-Vars-To-Js-Transformer
You can simply get PHP variable in JavaScript like this:
<script>
var casa = '<?php echo $casa ?>';
</script>
you can use alert to see the result in popup dialog too:
<script>
var casa = alert('<?php echo $casa ?>');
</script>
I have xml page contents in a javascript string. I need to save this into my.xml in the server side using php. But i can't seem to pass the xml-content-string value via POST method. I tried file_get_contents and curl but figured out that's not what I want since I have my xml content in string format and not in a file.
Can anyone help me to save this string in javascript as proper xml content.
Thanks in advance
Pre
I am attaching my code below
Page1.php
<form name = "frm_first" method = "POST">
<input type = "hidden" name = "xml_string">
...............
<script type = "text/javascript" language = "javascript">
function getDataXML(){
xmlString = chart.getDataXML();// This is where I get my xml data into the string
document.frm_first.xml_string.value = xmlString;
alert(xml_string); //Good
document.frm_first.submit();
}
</script>
Page2.php //This is the page to which post is submitted.
<?php
echo print_r($_POST);//xml_string vaiable is empty. Other variables are getting displayed.
$domtree = new DOMDocument('1.0','UTF-8');
$domtree->loadXML($_POST['xml_string']);// Error :empty string supplied as input
$domtree->save("my.xml"); //Yes , I have access to the file.
?>
$_POST['xml_string'] is empty is my issue. Other variables are getting passed via POST.
Adjusting the header with PHP did the trick when i tried to save a XML file:
header("Content-Disposition: attachment; filename=file.xml");
But sending the XML should be possible as string. Do you get any error messages?
Sorry to be answering my own question, but thought that it might be of use to someone else too.
I did a if array_key_exists('xml_string', $_POST)
<?php
if array-_key_exists('xml_string', $_POST)
{
echo print_r($_POST);
$domtree = new DOMDocument('1.0','UTF-8');
$domtree->loadXML($_POST['xml_string']);
$domtree->save("my.xml");
?>
and now $_POST variables are coming in properly.