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.
Related
<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>
echo "<input type=\"button\" id=\"csubmit\" value=\"SUBMIT\" onClick=\"<script type='text/javascript'>ajax_post();</script>\">";
when I click the csubmit button ajax_post method is not called, no alert is given and data is not getting inserted inside database which is done inside comments.php
<script>
function ajax_post(){
// Create our XMLHttpRequest object
alert("button clicked");
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
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>
Replace with
echo "<input type=\"button\" id=\"csubmit\" value=\"SUBMIT\" onClick=\"ajax_post()\">";
I have 2 php files, the first is BAConsult.php which is the main file, and the other is BAConsultRecordsAJAX.php. This line of code is in BAConsultRecordsAJAX.php:
while($row = mysqli_fetch_array($consultresult)) {
$skincareinuse=explode(",",$row['skincarecurrentlyinuse']);
}
In BAConsult.php I have this:
echo $skincareinuse;
Is it possible to bring over the $skincareinuse value from the BAConsultRecordsAJAX.php page, to the $skincareinuse variable on the BAConsult.php page?
Such that, lets say whenever I do a click on the table row, the value of $skincareinuse will be updated and shown by the echo, without the page refreshing?
[EDITED TO SHOW MORE OF MY CODES]
This is BAConsult.php file, where my main code is.
<?php echo $jsonvariable; ?>//Lets say i want to store the JSON data into this variable
function showconsultationdata(str) { //face e.g and checkboxes for that date selected.
if (str == "") {
document.getElementById("txtHint2").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint2").innerHTML = xmlhttp.responseText;
var a = JSON.parse($(xmlhttp.responseText).filter('#arrayoutput').html());
$("textarea#skinconditionremarks").val(a.skinconditionremarks);
$("textarea#skincareremarks").val(a.skincareremarks);
var test = a.skincareinuse;
//I want to store this ^^ into the php variable of this page.
}
};
xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str,true);
xmlhttp.send();
}
}
This is my BAConsultRecordsAJAX.php page.
$q = $_GET['q']; //get dateconsulted value
$consult="SELECT * FROM Counsel where nric='$_SESSION[nric]' and dateconsulted='$q'";
$consultresult = mysqli_query($dbconn,$consult);
while($row = mysqli_fetch_array($consultresult)) {
$skincareinuse=explode(",",$row['skincarecurrentlyinuse']);
$skincondition=explode(",",$row['skincondition']);
$queryResult[] = $row['skincareremarks'];
$queryResult[] = $row['skinconditionremarks'];
}
$skincareremarks = $queryResult[0];
$skinconditionremarks = $queryResult[1];
echo "<div id='arrayoutput'>";
echo json_encode(array('skincareremarks'=>$skincareremarks
'skinconditionremarks'=>$skinconditionremarks
'skincareinuse'=>$skincareinuse,
'skincondition'=>$skincondition));
echo "</div>";
You don't actually want to transfer the variable from BAConsultRecordsAJAX.php to BAConsult.php, but to BAConsult.js (I suppose that's the name of your JS file).
In reality, even that's what you wanted to do, it's impossible, because your main PHP is processed before the page even loads. What you can do, however, is overwrite the rendered value with a new one with the use of JavaScript.
To do that, send an AJAX request to BAConsultRecordsAJAX.php requesting the variable's value as shown below:
In JavaScript:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
// Check if the AJAX request was successful
if (xhttp.readyState === 4 && xhttp.status === 200) {
var td = document.getElementById("your table td value's id");
var td.innerHTML = xhttp.responseText; // gets the value echoed in the PHP file
}
xhttp.open("POST", "BAConsultRecordsAJAX.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(""); // You don't need to send anything to the PHP file
In PHP:
<?php
echo $skincareinuse;
?>
[EDIT]:
If you are using inline JavaScript use the following code:
<script type = "application/javascript">
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
// Check if the AJAX request was successful
if (xhttp.readyState === 4 && xhttp.status === 200) {
var td = document.getElementById("your table td value's id");
td.innerHTML = xhttp.responseText; // gets the value echoed in the PHP file
}
xhttp.open("POST", "BAConsultRecordsAJAX.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(""); // You don't need to send anything to the PHP file
</script>
[EDIT 2]:
To pass a JSON object to PHP file via an AJAX request you have to make it a string. That requires the following code:
var JSONstring = JSON.stringify(yourJSONobject);
Then you can pass it in your PHP file with the AJAX request by putting it inside send() as shown:
xhttp.send("json_object=" + JSONstring);
Then in PHP, in order to use it, you have to decode it:
<?php
$json_object = json_decode($_POST["json_object"]);
// Now it's ready to use
?>
[About the code]:
Notes about the first file:
First of all, you have put your plain JavaScript code inside a PHP file and therefore it will not work. You have to wrap it in <script type = "application/javascript></script>
I don't have a clue what you are trying to do here:
Code:
var a = JSON.parse($(xmlhttp.responseText).filter('#arrayoutput').html());
It seems like you are trying to filter out and parse the innerHTML of #arrayoutput.
If the response is a JSON string, not HTML, so you absolutely can't do that. The logic of this above line is flawed.
How I would write your code:
function showconsultationdata(str) {
var xmlhttp;
if (!str) {
$("#txtHint2").empty();
} else {
xmlhttp = new XMLHttpRequest();
// Providing support for a 15-year-old browser in 2016 is unnecessary
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
$("#txtHint2").html(xmlhttp.responseText);
var a = JSON.parse(xmlhttp.responseText);
$("textarea#skinconditionremarks").val(a.skinconditionremarks);
$("textarea#skincareremarks").val(a.skincareremarks);
var test = a.skincareinuse; // The variable you want
// Its saved in "text" and can use something like:
// $("#element").html(test); to have it replace your current text
}
};
xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str,true);
xmlhttp.send();
}
}
Notes about the second file:
I don't know if the query works for you, but it probably shouldn't, because:
$_SESSION is an associative array and you pass nric, whereas it should be "nric".
As $_SESSION is an array, the proper method to insert its value to your query is: {$_SESSION["nric"]}.
To ensure that you don't become the victim of an SQL Injection, use parameterised queries or at least sanitise somehow the received data, because GET is relatively easy to hack. Check the improved code later on how to do it.
How I would write your code:
$q = $_GET['q']; //get dateconsulted value
$dbconn = mysqli_connect("localhost", "root", "") or die("Error!");
mysqli_select_db($dbconn, "database") or die("Error!");
$consult = "SELECT * FROM Counsel where nric='{$_SESSION["nric"]}' and dateconsulted = ?";
if ($stmt = mysqli_prepare($dbconn, $consult)) { // By using a prepared statement
mysqli_stmt_bind_param($stmt, "s", $q); // you eliminate the chances to have
if (mysqli_stmt_execute($stmt)) { // an SQL Injection break your database
$consultresult = mysqli_stmt_get_result($stmt);
if (mysqli_num_rows($consultresult) > 0) {
while ($row = mysqli_fetch_array($consultresult)) {
$skincareinuse = explode(",",$row['skincarecurrentlyinuse']);
$skincondition = explode(",",$row['skincondition']);
$queryResult[] = $row['skincareremarks'];
$queryResult[] = $row['skinconditionremarks'];
}
$skincareremarks = $queryResult[0];
$skinconditionremarks = $queryResult[1];
$array = array('skincareremarks'=>$skincareremarks
'skinconditionremarks'=>$skinconditionremarks
'skincareinuse'=>$skincareinuse,
'skincondition'=>$skincondition);
echo "<div id='arrayoutput'>";
echo json_encode($array);
echo "</div>";
mysqli_stmt_close($stmt);
mysqli_close($dbconn);
exit;
}
}
}
Obviously you may change the values to suit your requirements, you must have jquery installed, the time value could be anything you want
$.ajaxSetup({ cache: false });
setInterval(function() {
var url = "pagethatrequiresrefreshing.php";
$('#divtorefresh').load(url);
}, 4000);
Using include will most likely work. From the docs:
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward.
BAConsultRecordsAJAX.php
while($row = mysqli_fetch_array($consultresult)) {
$skincareinuse[] = explode(",",$row['skincarecurrentlyinuse']);
}
include "BAConsult.php";
Okay, I've been struggling with this for a few hours now. I'm using ajax to update a div in my site with a php code however, i'm trying to send parameters in the function from the external javascript file to update the correct link(there are multiple drop down boxes)
for example: this is my select box
<script type='text/javascript' src='ajax.js'></script>//include ajax file
<select onchange='MakeRequest(raceupdate);
this.options[this.selectedIndex].value;'> //so no use of a button is needed to auto link to anchor tag
<option>Deathmateched</option>
<?php
dmList()
?>
</select>
Then next my external ajax function MakeRequest().
function MakeRequest(value)
{
var linkInfo = "teleport.php?call=" + value;//create appropriate link depending on function parameters
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", linkInfo, true); //update page using link info variable created above
xmlHttp.send(null);
}
So as you can see I'm trying to pass a sting of text into this function, but I seem to be failing somewhere.
You probably want to setup your tag to pass "this". I don't see where your raceupdate variable is declared, unless it's global... in which case you should show us what you're doing with that variable.
<select onchange='MakeRequest(this);'>
<option>Deathmateched</option>
<?php
dmList();
?>
If you did it that way, you'd have to change this function as such:
function MakeRequest(element)
{
var linkInfo = "teleport.php?call=" + element.value;//create appropriate link depending on function parameters
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", linkInfo, true); //update page using link info variable created above
xmlHttp.send(null);
}
And what are you trying to do here?
this.options[this.selectedIndex].value;
In your comments, it looks like you're saying you want to jump to an anchor tag? If so, then you would want to do something like
var anchorTag = document.getElementID("YOUR_ANCHOR_TAG_ID");
anchorTag.focus();
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;