I'm struggling with some JavaScript code that I have used countless times across my pages just tweaking as I go. The problem I have is concatenating part of the form elements id and a string variable defined elsewhere in the page to make my ajax call dynamic.
Im am using the following code which works perfect when the element is hard coded as below(only works for the item coded and not dynamically so no good after testing)
<script type="text/javascript">
function edttodo(str)
{
if (str=="")
{
document.getElementById("todoitemwr").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("todoitemwr(2)").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","todo/edt_todo.php?q="+str,true);
xmlhttp.send();
}
</script>
So you understand what my need is for the dynamic aspect of the code I have a mysql query undertaken which is as follows:
<?php
//Get Current To-Do Items
//select database
mysql_select_db("jbsrint", $con);
//query users_dash_user
$result1 = mysql_query("SELECT * FROM todo WHERE todo_user_id_fk= '".$_SESSION['user_id']."' AND todo_item_status='1'");
while($row1 = mysql_fetch_array($result1))
{
echo"<div class=\"todoitemwr\" name=\"todoitemwr(". $row1['todo_id'] .")\" ID=\"todoitemwr(". $row1['todo_id'] .")\"><span class=\"todoitem\">" . $row1['todo_item'] . "</span><span class=\"rmv\" onclick=\"rmvtodo(". $row1['todo_id'] .")\" onmouseover=\"className='rmvon';\" onmouseout=\"className='rmv';\">X</span><img src=\"images/edit.png\" class=\"edt\" onclick=\"edttodo(". $row1['todo_id'] .")\"></img></div>";
}
?>
</div>
As you can see the div id is dynamically named based on the id of the information that has been retrieved. The use of my ajax code above is to be able to edit the text that is retrieved in-situ and once corrected/altered it can then be re-submitted and update that record.
I'm sure that it is simply a case of understanding how JavaScript requires me to combine the text and str value in the document.getElementById("todoitemwr(2)") part.
As usual any help is much appreciated.
Alan.
Instead of using id="todoitemwr(2)" write id="todoitemwr_2".
That's because braces are not allowed in ID attributes.
The code would become:
document.getElementById('todoitemwr(' + str + ')')
Related
I select an option from a drop down menu(id="field"), and on the basis of this value I wish to generate another drop down menu, I use ajax to retrieve the value of field1 input. the function is:
function showbranches(degree)
{
var XMLHttp=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.open("POST","SORS/sendegree.php?degree="+degree,true);
XMLHttp.onreadystatechange = function(){
if (XMLHttp.readyState==4 && XMLHttp.status == 200)
{
document.getElementById('br').innerHTML=XMLHttp.responseText;
}
}
XMLHttp.send(null);
}
code in sendegree.php file is simply
<?php echo $_REQUEST['degree'];
?>
Now I try to receive the string returned by ajax code into a php variable using statement:
<?php
$state="<span id=\"br\"></span>";
echo $state;
?>
Now the problem is, the first statement for echo works fine, but i am not able to use $state as a variable in sql query as below
$get_cty=mysql_query("SELECT * FROM abc WHERE city='$state'")or die(mysql_error());
You need to concatenate the variable
Try this
$get_cty=mysql_query("SELECT * FROM abc WHERE city='".$state."'") or die(mysql_error());
How I learned it in college was whenever you needed a variable to a value in the query to you added '".."' after the equals sign then put the variable in the middle.
Hope that helps.
I have a page that lists customers from a SQL database. It lists the credits they have left and I have a button that I can click to remove one credit. The way it is done is when you click on the button it calls a Ajax function that runs a php page that remopves one credit and echoes the credit after that.
The php page works fine when I input the string in the URL manually but smy Ajax function must be wrong.
here is the listing with the form:
while ($data = mysql_fetch_object($result)) {
print "<TR><TD>".$data->pass_name."</TD><TD><span id='credit'>".$data->credit_left."</span></TD><TD><form><input type='submit' value='- 1' onsubmit='removeOneCredit(pass_id=".$data->pass_id."&credit_left=".$data->credit_left.")'></form></TD></TR>\n";
}
and here is my function:
<script>
function removeOneCredit(str)
{
if (str=="")
{
document.getElementById("credit").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("credit").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","removeonecredit.php?"+str,true);
xmlhttp.send();
}
</script>
I'm not sure why the function is not working. I know for a fact that removeonecredit.php is doing its job.
turns out the = in the function arguments is a problem, I posted a question on how to escape it here: Javascript escape a equal sign PHP
trying to insert a record in my DB using AJAX for the very first time. I have the following...
Form
<form>
<input type="text" id="salary" name="salary">
<input type="button" onclick="insertSalary()">
</form>
AJAX
<script type="text/javascript">
function insertSalary()
{
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('current-salary').innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("POST","insert_salary.php",true);
xmlhttp.send("salary=" + document.getElementById("salary").value);
}
</script>
PHP
$uid = $_SESSION['oauth_id'];
$monthly_income = mysql_real_escape_string($_POST['salary']);
#Insert a new Record
$query = mysql_query("INSERT INTO `income` (user_id, monthly_income) VALUES ($uid, '$monthly_income')") or die(mysql_error());
$result = mysql_fetch_array($query);
return $result;
Nowmy data is being inserted into the table BESIDES the 'salary' which is being inputted as '0'
Once inserted I also have a div 'current-salary' that should then be populated with there inputted value only it isnt, Can anybody help me to understand where im going wrong?
If you want to save your self a lot of time, effort, and heartache, use the jquery library for your ajax requests. You can download it at http://jquery.com/
After adding a reference(Script tag) to the jquery script your javascript for the ajax request would become:
function insertSalary()
{
var salary = $("#salary").val();
$.post('insert_salary.php', {salary: salary}, function(data)
{
$("#current-salary").html(data);
});
}
Also keep in mind that using "insert_salary.php" as the url means it is a relative path and must be in the folder of the current running script.
Your php script needs to echo whatever you would like to be injected into your current-salary tag also.
I made this little script with tutorials on internet. php function calls this javascript as many times as there are buttons (foreach), right now i have three. $value is the div name of specific button (buttons are stored in php array).
Everything works fine... except when i click through all the buttons fast, the loading gif remains without javascript changing the button status. The response, witch it gets from another php is the new button state and session variable change. Session variable gets changed but the div dosent.
So, heres where i need help, how can i make it so, when i click buttons fast, the div gets changed too?
my code
function load_javascripts() {
foreach ($GLOBALS["VARIABLES"]["button_list"] as $key => $value) {
$scripts .= "
function run_alias_button_".$value."(str)
{
document.getElementById('aliasbutton_".$value."').innerHTML='<img src=ajax_loader.gif>';
if (str=='')
{
document.getElementById('aliasbutton_".$value."').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('aliasbutton_".$value."').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open('GET','?leht=alias_logimine&alias=".$value."',true);
xmlhttp.send();
}
";
}
return $scripts;
}
Put var xmlhttp; at the very beginning of the function, making the variable explicitly local. Sometimes without that statement browsers may try to find a global variable with this name and readystate monitoring is shifted from one request to another.
Just a tip. Use the open function always before the onreadystatechange event. The way you using may works on firefox but IE doens't understand. LIke this:
xmlhttp.open('GET','?leht=alias_logimine&alias=".$value."',true);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById('aliasbutton_".$value."').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.send();
I want to count the number of hit on an image and also the image will show in a lightbox.
here is my code:
//image-show-content.php
<script>
function hitcounter(imgid)
{
//alert(imgid);
var imgid = imgid;
window.location.href ="image-show-content.php?img_id="+imgid;
}
</script>
<?php
if(!empty($_REQUEST['img_id']))
{
$show = "SELECT * FROM `tbl_image_gallery` WHERE image_id =".$_REQUEST['img_id']." ";
$result_show = mysql_query($show);
$row = mysql_fetch_array($result_show);
$new_click_count = $row['click_on_image'] +1;
$update_sql = "UPDATE `tbl_image_gallery` SET click_on_image =".$new_click_count." WHERE image_id=".$_REQUEST['img_id']."";
$result_sql= mysql_query($update_sql);
}
//image...
<img src="uploadedimage/gallery/thumble/<?=$val['gallery_image']?>" onclick="hitcounter('<?=$val[image_id]?>')"/>
?>
My problem is when I click on an image it return an error.
please help to solve it.Thanks in advance.Can you refer some other option to show light box and hit counter together.
Problem is, when your page loads. Lightbox javascript is already generating dynamic node for your tag.
To achieve this you can try with onclick function into . In that function you should call AJAX call with your image id. It would be possible that your onclick function may call after lightbox call OR before lightbox call. So please debug for this too.
This would be only one way to achieve this as per my opinion.
Place your php code in one another file called, hit_image.php and place your code there,
<?php
if(!empty($_REQUEST['image_id']))
{
$show = "SELECT * FROM `tbl_image_gallery` WHERE image_id =".$_REQUEST['image_id']." ";
$result_show = mysql_query($show);
$row = mysql_fetch_array($result_show);
$new_click_count = $row['click_on_image'] +1;
$update_sql = "UPDATE `tbl_image_gallery` SET click_on_image =".$new_click_count." WHERE image_id=".$_REQUEST['image_id']."";
$result_sql= mysql_query($update_sql);
}
Now your HTML file should be like follow,
<script type="text/javascript">
function counter(imageId)
{
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","hit_image.php?image_id="+imageId,true);
xmlhttp.send();
}
</script>
<a onclick="counter(<?=$val[image_id]?>)" rel="lightbox[100,200]" title="<?=ucfirst($val['category_name'])?>"><img src="uploadedimage/gallery/thumble/<?=$val['gallery_image']?>" onclick="hitcounter('<?=$val[image_id]?>')"/></a>
This is just overview code for your hints.