How to pass value to the second page using Javascript AJAX - javascript

I have an html select on my page
<pre>
$query = mysql_query("select * from results");
echo "<select id='date' onchange='showdata()' class='form-control'>";
while ($arr = mysql_fetch_array($query)) {
echo "<option value=".$arr['month'].">".$arr['month']." / ".$arr['year']. "</option>" ;
}
echo "</select>";
</pre>
the options are coming from database. After this I have ajax script
<script>
function showdata() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "result.php", true);
xhttp.send();
}
</script>
I want it to send the selected value in the html select to the page result.php

another way of doing the same thing using jquery ajax ...
<select id="item" onchange="send_item(this.value)">
<?php $someVariable = $_GET["someVariable"];
$query = mysql_query("select * from results");
echo "";
while ($arr = mysql_fetch_array($query)) {?>
<option value="<?php echo your value?>"><?php echo your value?></option>
<?php }?>
</select>
<script>
function send_item(str){
$.ajax({
url: '',
type: "post",
data: {
'str':str,
},
success: function(data) {
},
});
}
</script>

Try with this:
$someVariable = $_GET["someVariable"];
$query = mysql_query("select * from results");
echo "";
while ($arr = mysql_fetch_array($query)) {
echo "".$arr['month']." / ".$arr['year']. "" ;
}
echo "";
And JS:
<script>
function showdata() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "result.php?someVariable=test", true);
xhttp.send();
}
</script>
If you need example for POST, visit Send POST data using XMLHttpRequest

Related

How do I send a value from Javascript to PHP that will not be changed?

I have function that is running multiple times and executing a PHP file. I do, however, want to make sure the functions does not interfere with each other.
for(int i = 0; i<5; i++){
functionName(i)
}
function functionName(number){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
}
};
var PageToSendTo = "phpFile.php?";
var MyVariable = number;
var VariablePlaceholder = "name=";
var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;
xhttp.open("GET", UrlToSend, true);
xhttp.send();
}
This is how my code looks so far, how do I change it so that the next iteration of the function does not effect the previous one?
phpFile.php
<?php
require '../notWebsite/dbh.php';
session_start();
$variable = $_GET['name'];
$sqlInsertClass = "INSERT INTO class (className) VALUES (?)";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sqlInsertClass)) {
header("Location: ../Website.php?error=InsertError");
exit();
} else {
mysqli_stmt_bind_param($stmt, "s", $variable);
mysqli_stmt_execute($stmt);
exit();
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
?>

chat system - how to send data in this code - php ,ajax ,js

I have a problem when sending data using Ajax
t_id This is the variable I am trying to send to the chat.php using ajax.
function tid() {
var t_id = "<?php echo $AC["id"]; ?>";
$.ajax({
type: 'POST',
url: 'ajax/chat.php',
data: 't_id=' + t_id
});
}
function ajax() {
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
document.getElementById('chat').innerHTML = req.responseText;
}
}
req.open('GET', 'ajax/chat.php', true);
req.send();
}
setInterval(function() {
ajax()
}, 1000);
setInterval(function() {
tid()
}, 1000);
chat.php page code
<?php
include("../INC/header.php");
function formatDate($date){
return date('g:i a', strtotime($date));
}
$path = ""; include("../INC/emo.php");
$t_id = $_POST["t_id"];
$query = "SELECT * FROM chat WHERE f_id='$UID' AND t_id='$t_id' OR f_id='$t_id' AND t_id='$UID' ORDER BY msg_data DESC"; $run = $CONFIG->query($query);
while($row = $run->fetch_array()) :
$r_id = $row["f_id"];
$t_id = $row["t_id"];
$r_s = "SELECT * FROM accounts WHERE id='$r_id' "; $r_q = mysqli_query($CONFIG, $r_s); $r_i = mysqli_fetch_assoc($r_q); ?>
<div id="chat_data" class="text-right">
<span class="btn <? if($r_id == $UID){echo"btn-info";}else{echo"btn-secondary";} ?>"><img width="45" style="border-radius:100%;" src="IMG/<?php echo $r_i['img_i']; ?>"></span> :
<span style="<? if($r_id == $UID){echo"color:green;";} ?>text-align:right;"><?php echo $msg = str_replace($EMO_1,$EMO_2,$row["msg"]); ?></span>
<span style="float:left;"><?php echo formatDate($row['msg_data']); ?></span>
</div><hr>
<? endwhile; ?>
The problem now is that the function ajax() is sent and then the function tid() is sent. I want to send all at the same time instead of sending one by one

New variable ajaxObj does not work

For some weird reason this line of code is not working:
var ajax = ajaxObj("POST", "php_parsers/status_system.php");
What could it be?
I figured it must be the above line using window.alert's since after that line window.alert does not run.
Full code:
The function is called:
$status_ui = '<textarea id="statustext" onkeyup="statusMax(this,250)" placeholder="What's new with you '.$u.'?"></textarea>';
$status_ui .= '<button id="statusBtn" onclick="postToStatus(\'status_post\',\'a\',\''.$u.'\',\'statustext\')">Post</button>';
The function:
function postToStatus(action,type,user,ta){
window.alert("status passed 1");
var data = _(ta).value;
if(data == ""){
alert("Type something first weenis");
return false;
}
window.alert("status passed 2");
_("statusBtn").disabled = true;
var ajax = ajaxObj("POST", "php_parsers/newsfeed_system.php");
window.alert("status passed 3");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if(datArray[0] == "post_ok"){
var sid = datArray[1];
data = data.replace(/</g,"<").replace(/>/g,">").replace(/\n/g,"<br />").replace(/\r/g,"<br />");
var currentHTML = _("statusarea").innerHTML;
_("statusarea").innerHTML = '<div id="status_'+sid+'" class="status_boxes"><div><b>Posted by you just now:</b> <span id="sdb_'+sid+'">delete status</span><br />'+data+'</div></div><textarea id="replytext_'+sid+'" class="replytext" onkeyup="statusMax(this,250)" placeholder="write a comment here"></textarea><button id="replyBtn_'+sid+'" onclick="replyToStatus('+sid+',\'<?php echo $u; ?>\',\'replytext_'+sid+'\',this)">Reply</button>'+currentHTML;
_("statusBtn").disabled = false;
_(ta).value = "";
} else {
alert(ajax.responseText);
}
}
}
ajax.send("action="+action+"&type="+type+"&user="+user+"&data="+data);
window.alert("status passed 4");
}
newsfeed_system.php
if (isset($_POST['action']) && $_POST['action'] == "status_post"){
// Make sure post data is not empty
if(strlen($_POST['data']) < 1){
mysqli_close($db_conx);
echo "data_empty";
exit();
}
// Make sure type is a
if($_POST['type'] != "a"){
mysqli_close($db_conx);
echo "type_unknown";
exit();
}
// Clean all of the $_POST vars that will interact with the database
$type = preg_replace('#[^a-z]#', '', $_POST['type']);
$data = htmlentities($_POST['data']);
$data = mysqli_real_escape_string($db_conx, $data);
// Insert the status post into the database now
$sql = "INSERT INTO newsfeed(author, type, data, postdate)
VALUES('$log_username','$type','$data',now())";
$query = mysqli_query($db_conx, $sql);
$id = mysqli_insert_id($db_conx);
mysqli_query($db_conx, "UPDATE newsfeed SET osid='$id' WHERE id='$id' LIMIT 1");
mysqli_close($db_conx);
echo "post_ok|$id";
exit();
}
Ajax methods:
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
Please help!
The ajax is not refrenced! You need to include the library or put the code for calling an 'ajaxObj'.

Like button increment counter not working. PHP, AJAX, MySQL, javascript

I am implementing a facebook like "Like" button counter so everytime a user clicks on the button, a DIV tag besides it retrieves it from the db and updates it (see logic of the code below). However it isn't working. Please see all codes below:-
javascript:
function likeAJAX(strName)
{
If(strName == "")
{
document.getElementById('likeCount').innerHTML="";
return;
}
else
if(window.XMLHttpRequest)
{
xmlHTTP = new XMLHttpRequest();
}
else
{
xmlHTTP = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlHTTP.onreadystatechange = function()
{
if(xmlHTTP.readystate == 4 && xmlHTTP.status == 200)
{
document.getElementById('likeCount').innerHTML = xmlHTTP.responseText;
}
}
xmlHTTP.open("GET","getLikes.php?n=" + strName,true);
xmlHTTP.send();
}
HTML/PHP front-end:
<img src="./images/like.jpg" style="cursor:hand;" onclick="likeAJAX(<?php echo $_GET['val']; ?>)"><?php echo $likeVal; ?> people like this</span>
PHP/MySQL:
<?php
$q = $_GET['n'];
$temp;
$con = mysql_connect('localhost','xxxx','xxxx');
mysql_select_db("xxxx");
$SQLQuery = "SELECT * FROM likes where name= '" . $q . "'";
$res = mysql_query($SQLQuery);
while($data = mysql_fetch_array($res))
{
$temp = $data['likes'];
}
mysql_free_result($res);
mysql_close($con);
if($temp == "")
{
$temp = "0";
}
$intCount = int($temp);
$intCount++;
$con = mysql_connect('localhost','xxxx','xxxx');
mysql_select_db("xxxx");
$SQLQuery = "UPDATE likes set likes = '" . $intCount . "' WHERE busname = '". $q . "';";
$res = mysql_query($SQLQuery);
mysql_free_result($res);
mysql_close($con);
echo $intCount;
?>
Apologies for any formatting issues.
Where am i going wrong? The way i see it, seems like upon clicking the Like image, the javascript function doesn't even seems to be called?
Regards,
Ochen
Try this correction to your js:
function likeAJAX(strName) {
if (strName == "") {
document.getElementById('likeCount').innerHTML="";
return;
} else {
if(window.XMLHttpRequest) {
xmlHTTP = new XMLHttpRequest();
} else {
xmlHTTP = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlHTTP.onreadystatechange = function() {
if (xmlHTTP.readystate == 4 && xmlHTTP.status == 200) {
document.getElementById('likeCount').innerHTML = xmlHTTP.responseText;
}
}
xmlHTTP.open("GET","getLikes.php?n=" + strName,true);
xmlHTTP.send();
}
}

JSON php MySql menu not showing data in HTML page

I'm trying to populate a drop-down menu from a MySql.
My problem is that the data from JASON are not showing in my HTML page.
This is what I want to achieve.
ID: Select ID
JASON //This works and the output: {"article1":{ "title":"acGH2867" },"article2":{ "title":"apGS0158" }}
$jsonData = '{';
foreach ($conn_db->query("SELECT customerID FROM customers WHERE furniture='33' ") as $result){
$i++;
$jsonData .= '"article'.$i.'":{ "title":"'.$result['customerID'].'" },';
}
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData;
HTML
<script type="text/javascript">
$(document).ready(function(){
var ddlist = document.getElementById("ddlist");
var hr = new XMLHttpRequest();
hr.open("cData.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var d = JSON.parse(hr.responseText);
for(var o in d){
if(d[o].title){
ddlist.innerHTML += '</option><option value='+d[o].title+'</option>';
}
}
}
}
ddlist.innerHTML = "Loading....";
$('#dlist').on('change', function(){
$('#val1').value() = $(this).val();
});
});
</script>
</head>
<div class="dlist" id="ddlist">
</div>
try this
$jsonData = array();
foreach ($conn_db->query("SELECT customerID as title FROM customers WHERE furniture='33' ") as $result)
{
$i++;
$jsonData["article'.$i]=$result;
}
echo json_encode($jsonData);

Categories