javascript is not executing inserted in inner HTML - javascript

I am trying to get the response from another page for example its name is ajaxresponse.php through ajax request and I also want to perform some actions done by java script on that ajaxresponse.php page but the js code is not working. I am getting the response from that page but the js code for that page is not working. I want to only know why ajax code on mie second page is not working?
function ajaxinput(tinnerid)
{
var xmllhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("articledive").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajaxresponse.php?q="+tinnerid,true);
xmlhttp.send();
}
Here is the php code for first page
<?php
$con1=mysqli_connect("127.0.0.1","root","root","databasetry");
$result=mysqli_query($con1,"select title,articleid from article");
$tinnerid=0;
$articledivid=0;
while($row = mysqli_fetch_array($result))
{
$tinnerid=$row['articleid'];
echo "<div class='tinner' id='$tinnerid' onclick='ajaxinput($tinnerid)' style='cursor:pointer;'>";
echo"<span class='fontdiv'>";
echo $row['title']."<br>";
echo "</span>";
echo"</div>";
$tinnerid++;
$articledivid++;
}
mysqli_close($con1);
?>
Here is the js code for second page
function run()
{
alert("example");
}
Here is the php code of second page
<?php
$id=$_GET['q'];
$result=mysqli_query($con1,"select user.username,article.articleid,article.title,article.artiletext from article inner join user on article.user_id=user.user_id where article.articleid=$id");
$divid=0;
while($row = mysqli_fetch_array($result))
{
$id=0;
echo"<div class='inner' id=$divid >";
$id=$row['articleid'];
echo "<font class='ftitle'>"."Title : "."<a href='#'onclick='ajaxinput($id)'>".$row['title']."</a>"."</font>"."<br>"."<font class='ftext'>".$row['artiletext']."</font>"."<br>"."<font class='flast'>"."Posted By : ".$row['username']."</br>"."</font>"."<br>"."<br>";
echo "<button type='button' onclick='con($id)' class='button'><font size='1'>Delete</font></button>";
echo"</div>";
$divid++;
echo"<script>run()</script>";
}
mysqli_close($con1);
?>

Javascript inserted as innerHTML at runtime won't be executed. A possible solution is to remove the script tag from the second page return, and call the method run() on the first page, after the ajax callback. Like this:
function ajaxinput(tinnerid)
{
var xmllhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("articledive").innerHTML=xmlhttp.responseText;
/* CALL IT HERE AFTER INSERT */
run();
}
}
xmlhttp.open("GET","ajaxresponse.php?q="+tinnerid,true);
xmlhttp.send();

Related

Ajax Mysql Query

I am propably being a complete idiot and not seeing the big picture here. I am trying to write a little ajax thingie that would pull information from a database but i cant seem to get the thing going ... please tell me what i am doing wrong.
I put the code together by following a couple of online tutorials and i am no ajax genius. my ajax skills could propably start the next world war.
Here is my code. please feel free to tell me im an idiot if i missed something small.
<html>
<head>
<script>
function showDetail(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","process.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
Wallet Number : <input type="text" name="wallet01" id="wallet01" />
<br />
<input type="submit" id="submit" name="submit" onsubmit="showDetail(wallet01)">
</form>
<br>
<div id="txtHint"><b>Kit info will be listed here.</b></div>
</body>
</html>
and here is my php
<?php
$q = $_GET['q'];
$con = mysqli_connect('10.1.75.131','markdv','qwerty123','MTNAutomation');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"MTNAutomation");
$sql="SELECT serialNumber FROM Kit_T WHERE serialNumber = '$q'";
$result = mysqli_query($con,$sql);
echo "<table border='1'>
<tr>
<th>Wallet Number</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['serialNumber'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
There is an error in your HTML. You put 'onsubmit="showDetail(wallet01)"', but 'wallet01' is not a javascript variable.
I would suggest changing it to this:
<form onsubmit="return showDetail()">
Wallet Number : <input type="text" name="wallet01" id="wallet01" />
<br />
<input type="submit" id="submit" name="submit">
</form>
I added the "onsubmit" in the form, using the function with "return", to prevent the default submit from form. But remember to always return false in the function.
Than in the function you can get the value for the field.
function showDetail() {
var str = document.getElementById('wallet01').value;
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return false;
}
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","process.php?q="+str,true);
xmlhttp.send();
return false;
}
Or you can use the ajax from jQuery, it's easier.
See an example here
function showDetail() {
var str = $('#wallet01').val();
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return false;
}
var jqxhr = $.ajax( {
url: "example.php",
type: "GET",
data: {q: str}
}).done(function(data, textStatus, jqXHR ) {
alert( "success" );
}).fail(function(jqXHR, textStatus, errorThrown) {
alert( "error" );
}).always(function( ) {
alert( "complete" );
});
return false;
}
See the JQuery Ajax docs
You also have the function "beforeSend" to start a gif "loading".

PHP receiving black instead of js variable sent?

I am making a simple web app, in one part of it, I have to send a js variable to PHP. I am sending the JS variable using AJAX but PHP is receiveing blank instead of the data.
Here is the JS function:
function sync(){
var xmlhttp;
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)
{
console.log(xmlhttp.responseText);
}
}
xmlhttp.open("POST","sync.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var data = "data=thisisdata";
console.log(data);
xmlhttp.send(data);
}
This is the PHP code:
<?php
return $_POST["data"];
?>
The output that I get at the console is:
data=thisisdata goal.js:23
goal.js:16
i.e., I am getting a blank instead of the responseText. I am NOT getting any errors.
What's wrong? What should I do?
change
<?php
return $_POST["data"];
?>
to
<?php
echo $_POST["data"];
?>
or to see all posted variables
<?php
echo "<pre>"; print_r($_POST);
?>
You need to echo the response on the PHP side :
<?php
echo $_POST["data"];
?>

onchange in onchange won't work

When I am building 2 dropdowns filling them from the database, the second dropdown is created when a value is picked from the first dropdown. But then, when I select an option in the second, my ajax is being executed. But when I have only one value in the second dropdown, it won't work. Even if I call the javascript function manualy.
The 2nd dropdown:
<?
include ('../dbconnect.php');
$query = "CALL get_projects(".$userid.",".$q.")";
$result = mysql_query($query);
$countprojects = mysql_num_rows($result);
if ($countprojects != 0){
echo '<select class="form-control" onchange="showContent(this.value)">'."\n";
if ($countprojects > 1){
echo "<option value='none' selected>Select project</option>";
}
while($rowprojecten = mysql_fetch_assoc($result)){
echo '<option value='.$rowprojecten['projectID'].'>'.$rowprojecten['projectname'].'</option>';
$lastvalue = $rowprojecten['projectID']; // see below why i did this
}
echo '</select>';
?>
the javascript function I wrote/copied:
function showContent(str)
{
if (str=="")
{
document.getElementById("project").innerHTML="";
return;
}
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("project").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","./includes/ajax/getcontent.php?q="+str,true);
xmlhttp.send();
}
The phpfile what is called from this javascript:
<?
$q = intval($_GET['q']);
include ('../dbconnect.php');
$query = "CALL get_project(".$userid.",".$q.")";
$return = '<div id="project">';
$return .= $query;
$return .= '</div>';
echo $return;
mysql_close($con);
?>
Why do I see the div 'project' change when I select one, but does'nt it change when it is created?
I tried to call the function manualy with adding this to the first php file. But it also doesn't work.
if ($countprojects == 1){
echo '<script type="text/javascript">
showContent('.$lastvalue.')
</script>';
}
sorry for my bad english, I hope you can help me solve this.
This is because there is only one option in your second drop down list. you cannot fire change event if there is only on or zero options in drop down list. what you can do is add this code where your first Ajax call get fired when selection changes. and place your second Ajax call in inside below code.
if ($('#selectproject').children().length == 1) {
// make sure you have imported latest jquery. if not add this inside HTMl head : <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
var selectedProject = $('#selectproject').children()[0].value;
showContent(selectedProject); // i hope this is the function you are calling when executing. if not please replace your function call here.
}

Javascript pass title attribute through function

I have a function that gets the value of a select menu and this work great. But i am trying to add another value to the function. So I thought I would use the title attribute for option (please see code below). The problem is the username parameter in my JavaScript function is undefined.
Does anybody have any ideas of what im doing wrong?
FORM
<form action="">
<select id="acyear" name="acyear" onchange="showyearlogdays(this.value, this.title)">
<option value="" label="">- Year -</option>
<?php
$is_business_result = mysql_query('SELECT DISTINCT(academic_year)FROM holiday_entitlement_business_manual WHERE employee = \'' . $username . '\'');
while($acyear_filter = mysql_fetch_array($is_business_result)) {
echo '<option value="'.$acyear_filter['academic_year'].'" title="'.$username.'"';
$datestr = $acyear_filter['academic_year'];
$currentyear = substr($datestr, 0, 4);
if(intval(substr($datestr,4,2)) < 8){$ayear = ($currentyear - 1).'/'.$currentyear;}
else{$ayear = ($currentyear).'/'.($currentyear + 1);}
echo '>';
echo $ayear;
echo '</option>';
}
?>
</select>
</form>
Javascript
function showyearlogdays(str, username)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","days_yearlog.php?username="+username+"&q="+str,true);
xmlhttp.send();
}
You need to get the title attribute of the selected option. Your code is pointing to the title attribute of the select tag. Make the change below:
showyearlogdays(this.value, this.options[this.selectedIndex].title)
You should also address the security concern mentioned in the comments. The way your query is setup would make for a really simple SQL Injection attack. If you don't want to rearchitect it the way the commenter suggested, I would at least escape $username so that SQL can't be injected.

window.XMLHttpRequest combine with script .change

I have a problem with combinning two scripts.
Fisrt script is working perfectly and taking stuf from mysql:
<script type="text/javascript">
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open('GET','includes/test-search.php?q='+str,true);
xmlhttp.send();
}
</script>
The second one is working perfectly and it's simple script for inserting data after change:
<script type="text/javascript">
$("document").ready(function(){
$("#selection").change(function () {
$("#someDivName").html( $("#selection option:selected").val() );
});
});
</script>
now the hole point is to combine them.
It's look like, when I load the site it don't have id selection and second script stops but after taking data from php and mysql file test-search.php the missing id selection is on site but the first script is not checking if id selection apear and don't work.
The php code:
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("table", $con);
$sql="SELECT * FROM prod_models WHERE prod_main_group_id = '".$q."'";
$result = mysql_query($sql);
echo '
<select id="selection" name="prod_main_group_id" onchange="change_val()">
<option value="">Wybierz produkt</option>
';
while($row = mysql_fetch_array($result))
{
echo '<option value="'.$row['id'].'">';
echo $row['product_name'] . "</option>";
}
echo "</select>
";
mysql_close($con);
?>
Code to display changed script:
<input type="text" id="someDivName" value="" />
if any one can help with solving the problem will be realy nice.
Thx i'm waiting for it now and trying to solve this for my self but now I don't have other ideas for it.

Categories

Resources