Reputation: 105
I've got a problem using Javascript (as I'm pretty new into this language)
My problem is : I've got a Javascript script which adds form fields when you click on a button, and change their name by incrementing it.
The data is then stored into an array. When I've saved those filled fields, I need to get them back and show them into a <input type="text" value="<?php $myvalue[] ?>"/>
. The problem is, I need to do it into the javascript file, and I don't know how it can interpret the stuff inside as a PHP script.
Here's what I've tried :
var counter = 1;
var limit = 10;
var new_div = '<?php echo json_encode($arraySpecialite['+ counter +']); ?>';
function addInput(divName){
if (counter == limit) {
alert('You cannot add more than' + counter + ' fields');
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = 'Specialité ' + (counter + 1) + ' <br><input type="text" name="specialite[]" id="specialite[]"" value="'+ new_div +'">';
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
Thank's in advance.
Upvotes: 0
Views: 73
Reputation: 2809
You can do differents things:
In the PHP that return the initial view, return a response that contains the javascript that will hold the data.
Eg:
<script>
var new_div = '<?php echo json_encode(array(1,2,3)); ?>'
</script>
So if your javascript run in the same scope, or in a Inner scope it will have access to the variable.
OR
Make an AJAX request and read the response from the server
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
console.log(xmlhttp.responseText);
}
}
xmlhttp.open("POST","myscript.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("name=Shikaka&lastname=Ventura");
when myscript.php receive the request work with it (Make sure that you escape the values) And then return a response
<?php
echo json_encode(array(1,2,3));
Upvotes: 1
Reputation: 475
When you submit a HTTP request to the server (Fetch, POST, GET, and so on) the server reads your Server script and acts accordingly, but with javascript it is your web browser the one who acts. If you want your script to work you need to do the following.
write an stand alone PHP script (its own file).
Use Javascript to submit an HTTP request to the PHP script (you can send whatever you want).
Access the response from the PHP file and do whatever you want.
Upvotes: 1