Hi I'm using ajax for posting the data in to database, I'm using php as server background for posting the data in mysql database, for
Ex: $name = $_POST['name'];
$query = "INSERT INTO table('name') VALUES ('".$name."');
$result = mysql_query($query)
when the user click on the submit button, i just made a onlick function of ajax post_data(),
so what i need is i want the value in the textbox so that i can pass it to ajax, how to get the value of the textbox
var url = "get_data.php";
var params = "name=?"; (how to get the name enter in the text box)
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
You can give the textbox and id.
And then using this code
var textValue = document.getElementById("textboxid").value;
you can get as well set the value in the textbox.
You shouldn't send $POST vars directly to the db. Look up sanitization.
var url = "get_data.php";
var validValue=validate(document.getElementById('textboxid').value) ;
var params = "name=?"+validValue;
http.open("POST", url, true);
<!-- assuming your text box is-->
<input type =textbox id="textboxid">
And don't forget to sanitize at the server side too.
var params = "name=?"; (how to get the name enter in the text box)
you can try:
var params = "name="+document.getElementById('theTextBoxId').value;
Related
I created a date selection function with display of the choice at the bottom (Second box in green). I would now like to be able to retrieve the user's choice in PHP and then send it in JSON format. Thank you in advance for any suggestion or help.
enter image description here
Here's my code:
function setToSelected(me){
const x = document.querySelector("span.active");
if (x !== null) {
x.classList.remove("active");
}
me.className='active';
console.log(me.id);
var dateselected=me.id.split('-')
var day=dateselected[0].split('_')[0]
var daynum=dateselected[0].split('_')[1]
var month=dateselected[0].split('_')[2]
switch(day){
case 'lun':
day='Lundi'
break;
etc...
default:
console.log("erreur conversion day")
}
switch(month){
case 'jan':
month='Janvier'
break;
case 'fev':
month='Fevrier'
break;
default:
console.log("erreur conversion month")
}
document.getElementById("dateselected").innerHTML = "Selected restart date : "+day+" "+daynum+" "+month+" à "+dateselected[1]+"h"
}
});
So we have 2 technologies at work here, Javascript working in your front end and php working server side. To retrieve data server side in php you`ll need to do a post request to a php page from your front end because php is only executed serverside and not frontend. Steps as follows
get your date info in javascript
prepare data to send
send data to php page via xhr request
Example
// Step 1
var selecteddate = day+" "+daynum+" "+month+" "+dateselected[1]+"h";
// Now we have our javascriptobject called selecteddate;
// set target php page to post to
var url = "datereceiver.php";
// Step 2 create a post object
var dataToSend = {"fontenddate": selecteddate };
// Step 3 set request paramaters
var xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
// send request
xhr.send(selecteddate);
// set callback function to capture response from your php page(server)
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
// check response code
console.log(xhr.status);
// get your response from your php page
console.log(xhr.responseText);
}};
On the php side your (datereceiver.php) page can look something like
<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
$yourselecteddate = $_POST['frontenddate'];
$response = "date received";
}
else{
$response = "bad request";
}
// set response headers
header('Content-type: application/text');
echo $response;
?>
In my JS code, I take in 3 inputs on a html page and save them to local storage. I then want to send these variables to php in order to save them to my database. No matter how hard I try no tutorial using ajax, jquery etc allows me to successfully post and echo variables from javascript in my php code. I see no reason why my code below doesn't echo the variables, but it doesn't.
Full code: https://codeshare.io/ayvK9e
Exact PHP elements (just trying to send normal variables right now as it still won't work"
PHP:
foreach($_POST as $post_var){
echo($post_var);
}
JS:
const xhr = new XMLHttpRequest();
xhr.onload = function(){
const serverResponse = document.getElementById("serverResponse");
serverResponse.innerHTML = this.responseText
};
xhr.open("POST", "eDBase.php");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("name=dominic&message=bumbaclaat");
If $post not work try using input php
$data = json_decode(file_get_contents('php://input'), true);
When calling my function with the inputs onclick=showFunction; I was passing nothing to the function. In order for my values to be echoed in php I had to pass a parameter to the function onclick=function('text or variable'); IDK how I missed that.
Try using the FormData()
let form = new FormData();
form.append('name', 'dominic');
form.append('message', 'bumbaclaat');
const xhr = new XMLHttpRequest();
xhr.open("POST", "eDBase.php");
xhr.onreadystatechange = function(){
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
const serverResponse = document.getElementById("serverResponse");
serverResponse.innerHTML = this.responseText;
}
else console.log('error')
};
xhr.send(form);
Comment out the setRequestHeader to test it.
And at PHP
if(isset($_POST['name'])){
echo $_POST['name'];
echo $_POST['message'];
}
else{
echo 'There was a problem';
}
<script src="jquery-3.2.1.min.js">
function ajax_post(){
loadScript('javascript/jquery-3.2.1.min.js');
// Create our XMLHttpRequest object
alert("button clicked");
// code for modern browsers
// Create some variables we need to send to our PHP file
var hr = new XMLHttpRequest();
var url = "comments.php";
var bid='<?php echo $b; ?>';
var userid='<?php echo $userid; ?>';
var cm = document.getElementById("latest_comment").value;
var vars = "your_comment="+cm+"&bookid="+bid+"&uid="+userid;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("comment").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("comment").innerHTML = "processing...";
}
</script>
this is javascript function which should run when i click the csubmit button, but when i click it the console gives an error written in the title. this function has to take the data written in the input tag, go to the comments.php page and insert it in database and display the comments in the comment div
I HAVE BEEN STUCK ON THIS ERROR FOR A VERY LONG TIME,BUT NOT ABLE TO FIND WHERE IS THE ERROR
<input type="button" id="csubmit" value="SUBMIT" onclick="ajax_post();">
Put ajax_post function in other script tag, you can not put JS code in script tag which already have src
<script src="jquery-3.2.1.min.js"></script>
<script>
function ajax_post() {
loadScript('javascript/jquery-3.2.1.min.js');
// Create our XMLHttpRequest object
alert("button clicked");
// code for modern browsers
// Create some variables we need to send to our PHP file
var hr = new XMLHttpRequest();
var url = "comments.php";
var bid = '<?php echo $b; ?>';
var userid = '<?php echo $userid; ?>';
var cm = document.getElementById("latest_comment").value;
var vars = "your_comment=" + cm + "&bookid=" + bid + "&uid=" + userid;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("comment").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("comment").innerHTML = "processing...";
}
</script>
This is the problem with your code: Your script is inside a <script> tag with a src attribute. When a src attribute is present, the content inside the <script> tag is completely ignored.
This should work:
<script src="jquery-3.2.1.min.js">
function ajax_post(){
loadScript('javascript/jquery-3.2.1.min.js');
// Create our XMLHttpRequest object
alert("button clicked");
// code for modern browsers
// Create some variables we need to send to our PHP file
var hr = new XMLHttpRequest();
var url = "comments.php";
var bid='<?php echo $b; ?>';
var userid='<?php echo $userid; ?>';
var cm = document.getElementById("latest_comment").value;
var vars = "your_comment="+cm+"&bookid="+bid+"&uid="+userid;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("comment").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("comment").innerHTML = "processing...";
}
</script>
I dont know much about ajax or jquery yet but i currently have an ajax script that does successfully send A variable through and does work properly.
--the way i have it set up is like this for my loop:
<?php
$tt= mysql_query("SELECT * FROM monsters");
while ($row= mysql_fetch_array($tt))
{
$namee= $row['name'];
echo "<a id='namee' onclick='post();'>$namee</a>", "</br>";
}
which echos:
horseman
dragon
---the results do make a list of all the names from the table as shown above and they are clickable which is working great
my ajax request is this:
<script type="text/javascript">
function post(){
var hr = new XMLHttpRequest();
var url = "mess.php";
var vars =document.getElementById("namee").innerHTML;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("new").innerHTML = return_data;
}
}
hr.send(vars); // Actually execute the request
alert(vars);
}
</script>
the alert when i click on horseman returns "horseman"
but when i click on dragon it still alerts "horseman"
i would like to get the specific variable ( when i click horseman it says horseman and when i click dragon it says dragon etc) so i can send it through ajax to update a database ( which i already know to to set up)
please help me and show me if you can full code so i can learn and see how it works and understand your response since im new like i said :)
thanks in advance:
if have any questions feel free to ask
Thats because ids should be unique, jquery will get only the first element with that id, my suggestion is to pass the value by parameter:
echo "<a class='namee' onclick='post($namee);'>$namee</a>", "</br>";
And then the js:
function post(vars) {
var hr = new XMLHttpRequest();
var url = "mess.php";
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function () {
if (hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("new").innerHTML = return_data;
}
}
hr.send(vars); // Actually execute the request
alert(vars);
}
I am very close with this but struggling to get my dynamic php and Javascript to work together. Heres where I'm up too.
<script language="javascript" type="text/javascript">
function exefunction(id){
if (document.getElementById(id).checked == true) {
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "update.php";
var id = document.getElementById(id).value
var check = 1;
var vars = "id="+id+"&check="+check;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.send(vars); // Actually execute the request
}
else if (document.getElementById(id).checked == false){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "update.php";
var id = document.getElementById(id).value
var check = 0;
var vars = "id="+id+"&check="+check;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.send(vars); // Actually execute the request
}
</script>
My php checks the database and will auto check the tick boxes accordingly:
if ($checkboxone == 1){
$Trans .='<td width="60">
<input id="'.$id.'" type="checkbox" onClick="exefunction(this.id)" value="'.$id.'" checked /></td>';
}else{
$Trans .='<td width="60"><input id="'.$id.'" type="checkbox" onClick="exefunction(this.id);" value="'.$id.'" /></td>';
}
What I need it to do is when a tick box is checked or unchecked it updates my database the issue I'm having is passing the unique id of the checkbox through my javascript. The javascript works if I put the id in and have one checkbox.
Hope that makes sense.