Passing Unique ID to AJAX Script - php

I'm working on my first AJAX script with some PHP pages - it's my first time with AJAX and I've finally got the script to work. I'm also a bit of a Javascript newbie too.
I have a PHP website that allows users to search a library catalog and then select/add books to a shopping cart. We've now changed the "Select" link to load via AJAX so the search results page doesn't refresh.
To finish the AJAX changes I now need to pass a unique ID for each of the table cells that has the AJAX link to the script. I'm using PHP to generate a unique ID for each table cell by using the $bookID variable as follows:
<td class="hidden-narrow" id="<?php echo 'selectRecord'.$bookID; ?>">
<?php
if (in_array($bookID, $_SESSION['selectedBooks'])) {
echo "Selected";
} else {
echo 'Select';
}
?>
</td>
I now need to update my script to work with the unique ID's - to get it working I hardcoded it to an ID named "selectRecord" using an example script that I found. Here's my script:
function selectRecord(id) {
// Allocate an XMLHttpRequest object
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
var xmlhttp=new XMLHttpRequest();
} else {
// IE6, IE5
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
// Set up the readyState change event handler
xmlhttp.onreadystatechange = function() {
if ((this.readyState == 4) && (this.status == 200)) {
document.getElementById("selectRecord").innerHTML="Selected";
}
}
// Open an asynchronous POST connection and send request
xmlhttp.open("POST", "selectRecord.php", true);
xmlhttp.send("id="+id);
return false; // Do not follow hyperlink
I gather I need to change this line:
document.getElementById("selectRecord").innerHTML="Selected";
but not sure of the syntax to handle unique ID's for each table row cell.

You can pass the id to the getElementById function:
document.getElementById("selectRecord" + id).innerHTML="Selected";

Have you tried
document.getElementById(id).innerHTML="Selected";
? id should get enclosed by the readystate function and keep its value.

Related

Data from javascript code insert to mysql database

Here I have a script which help me to get places from google places API. So now I want to store all this into mysql but how? I'm new to mysql and php, and how to store data that I get from google places to database?
What I need to do here? Can someone show me on my example...
How to combine php and javascript;
CODE: http://jsbin.com/AlEVaCa/1
So I need to store data which I got from google:
google.maps.event.addListener(marker,'click',function(){
service.getDetails(request, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var contentStr = '<h5>'+place.name+'</h5><p>'+place.formatted_address;
if (!!place.formatted_phone_number) contentStr += '<br>'+place.formatted_phone_number;
if (!!place.website) contentStr += '<br><a target="_blank" href="'+place.website+'">'+place.website+'</a>';
contentStr += '<br>'+place.types+'</p>';
infowindow.setContent(contentStr);
infowindow.open(map,marker);
} else {
var contentStr = "<h5>No Result, status="+status+"</h5>";
infowindow.setContent(contentStr);
infowindow.open(map,marker);
}
});
});
I want to store all place.name,website ... etc. data to mydatabase. How to do that?
Is there any way to store this data?
Use AJAX to send data to PHP file.
Use jQuery $.post()-AJAX method to send data to php file
data = "name="+name+"&place="+website;
$.post('file_to_store.php', data, function(data) {
//Here you can get the output from PHP file which is (data) here
});
Pure javascript way
function loadXMLDoc()
{
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)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
data = "name="+name+"&place="+website;
xmlhttp.open("POST","file_to_store.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(data);
}
In file_to_store.php receive all data from $_POST[] global array
if(isset($_POST)){
$name = $_POST['name'];
$website = $_POST['website'];
//Do same for all other variables
//Steps to insert Data into Database
//1. Connect to database
//2. Select Database
//3. Generate Database Insert Query
//4. Run mysql Query to insert
// Return appropriate return back to Javascript code - Success or Failure
}
Use serialize($data) then put it into database, use unserialize() after getting data from db.
Addition: this will store raw data, you'll probably need a parser also.
Addition 2: sorry I assumed that you got an array.
Alternative solution if you got non-array data:
you can use base64_encode($raw_data) to store and base64_decode($encoded_data) to use the encoded data coming from SQL.
Fundamentally, your JavaScript program, executing on the client side, does not have direct access to the SQL database on the host. You must use AJAX to issue requests to the host, and the host-side software must be programmed to handle them. Lots(!) of existing tutorials on this subject are already out there ... everywhere.

Modifying Results Table to use AJAX

I have a PHP website that allows users to search a library catalog and then select/add books to a shopping cart. This all works well but we would like to implement AJAX into the search results table so that instead of clicking a link which runs another php script to add the selected record to their cart, it does this inline within the same page. This will remove the search results page refreshing when they "select" a record and it pops back to the top of the page (annoying if you were at the bottom of the page).
I've found a similar example of implementing AJAX with a link - this is my first time with AJAX - but I'm stuck as nothing happens when the user clicks the link.
Here's my script:
function selectRecord() {
// Allocate an XMLHttpRequest object
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
var xmlhttp=new XMLHttpRequest();
} else {
// IE6, IE5
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
// Set up the readyState change event handler
xmlhttp.onreadystatechange = function() {
if ((this.readyState == 4) && (this.status == 200)) {
document.getElementById("selectRecord").innerHTML=xmlhttp.responseText;
}
}
// Open an asynchronous POST connection and send request
xmlhttp.open("POST", "selectRecord.php", true);
return false; // Do not follow hyperlink
}
and here's the table cell with the link:
<td class="hidden-narrow" id="selectRecord">
<?php
if (in_array($bookID, $_SESSION['selectedBooks'])) {
echo "Selected";
} else {
echo 'Select';
}
?>
</td>
In case it's not clear the result I'm after is a link ("Select") in the table cell - when the user clicks this link it then performs the selectRecord.php script which will echo "Selected" or an error message if there was an error. At present nothing happens when the user clicks the Select link.
I also need to work out how to pass the $bookID PHP variable to the AJAX script so the selectRecord.php knows which Book ID to add to the cart.
You can add a parameter to your selectRecord() call like this:
echo 'Select';
Then your selectRecord function should look like this:
function selectRecord(id) {
// Allocate an XMLHttpRequest object
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
var xmlhttp=new XMLHttpRequest();
} else {
// IE6, IE5
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
// Set up the readyState change event handler
xmlhttp.onreadystatechange = function() {
if ((this.readyState == 4) && (this.status == 200)) {
document.getElementById("selectRecord").innerHTML="Selected";
}
}
// Open an asynchronous POST connection and send request
xmlhttp.open("POST", "selectRecord.php", true);
xmlhttp.send("id="+id);
return false; // Do not follow hyperlink
}
This works well as long there is only one element in your document with id selectRecord. You can always modify the id of any link by simply adding the BookId number as a postfix.
Please note your code wasn't working because it was missing the .open call on the xmlHttpRequest object which actually perform the request.

jquery div not showing more them on user profile

I have been working on this code for a while and I am finally stumped and cannot figure out what the heck to do to get this issue fixed.
I have a jquery code that works beautifully for the get profile, but when i need to return the values in a div, it only shows the first profile of the user, but if a user posts more then once on the blog, it will not show the profile information. I have tried to append more information for each profile div to be different, but its still not working.
Here is the jQuery code for the GET user profile and return response.
function showUser(str)
{
var profileDiv = document.getElementById("profile_"+ str);
if (str=="")
{
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)
{
profileDiv.innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
Also here is the PHP script that i am using to pass the information
"<div id=\"info\" onmouseover=\"showUser(" .$blogrow['id_user'].")\"><imgalign= \"left\" style=\"vertical-align:top;\" class=\"imgb\" height=\"41\" width=\"41\" src=\"profilepics/".$blogrow['pic']."\" />".$blogrow['author']." <br>".$blogrow['timestamp']."<br></div><br>";
echo "</div>";
here is the div part as well that stores the information
echo "<div id=\"txtHint\"><div id=\"profile_".$blogrow['id_user']."\"></div></div>";
The problem relies on your HTML markup, which is invalid. Element ids must be unique in a HTML page but I see a lot of repeated ids such as #info, #theDiv, #txtHint and #profile_X
A quick fix for your problem would be to change all those and any other repeating ids to a class and then use the ajax code provided by #Rohan Kumar but using a class selector to append the content to every mention of the user in the page
function showUser(str)
{
$.ajax({
url:'getuser.php',
data:{q:str},
type:'GET',
success:function(data){
$(".profile_"+ str).html(data);
}
});
}
This is definitely not the most efficient or elegant solution but I think it would work. If you were to try and improve your code I would suggest binding all divs of class .info to a mouseenter handler, using data-attributes to get the user id and maybe maintaining a list of the profiles retrieved so you don't end up making redundant calls to your php
Using $.ajax it will more simple like,
function showUser(str)
{
$.ajax({
url:'getuser.php',
data:{q:str},
type:'GET',
success:function(data){
$("#profile_"+ str).html(data);
}
});
}
But, before this you need to add any version of jQuery

Javascript document.getElementById concatenating

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 + ')')

How to force a DOM refresh when running multiple Ajax tasks in a loop

I have a page that sends emails to customers. It has a send all button at the bottom of the page to provide the convenience of being able to send all the emails at once. Problem is it works badly or not at all. It either isn't redrawing the page or isn't managing to process all the Ajax calls.
Here is the JavaScript...
function ajaxemail(element,name,email,bonus)
{
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(element).innerHTML= xmlhttp.responseText
//document.getElementById(element).style.display = 'none'
//document.getElementById(element).style.display = 'block'
//alert(xmlhttp.responseText)
}
}
xmlhttp.open("POST",<?php echo "\"$_SERVER[PHP_SELF]\"";?>,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("emailto=true&name="+name+"&email="+email+"&bonus="+bonus);
}
function sendall(info)
{
document.getElementById('sendallmails').disabled = true
document.getElementById('sendallmails').value = 'Sending mails...'
length = info.length
for( i=0; i < length; i++)
{
ajaxemail(info[i][0],info[i][1],info[i][2],info[i][3])
}
}
And if it helps, here is where the array info is constructed and then the function called...
echo "<script>\nvar email_info_array = new Array()\n";
$j = 0;
while($row = mssql_fetch_row($rs))
{
echo "email_info_array[$j] = new Array('sendlink$j','$row[1]','$row[2]','$row[4]')\n";
++$j;
}
echo "</script>\n\n";
echo "<input type=\"button\" name=\"sendallmails\" id=\"sendallmails\" value=\"Send all Mails\" onclick=\"javascript:sendall(email_info_array)\">\n";
The failure isn't in the page being called by function ajaxemail() because that works fine when called once or one at a time. It's when called by the loop that it doesn't work. It seems to do the last one or two items in the loop... or it might do some in between if I do something that forces the browser to redraw (such as resize it).
If I add an alert as a way of testing that execution of the loop is at least working it successfully runs the Ajax call on every iteration (but I have to press ok on many alerts!
I need to somehow forcibly refresh the browser DOM on every single iteration of the loop. It doesn't matter if the page becomes less responsive (but would rather it didn't become totally unresponsive)
I am testing in the latest Firefox (will test in other browsers once I have it working in FF)
The problem here is you are using asynchronous requests with a global variable that holds the Ajax call. You are basiclaly overwritting the previous call on each iteration of the loop. You need to use a library that does not use a global variable for the Ajax call.
Best bet is to use jQuery, Dojo, YUI, or some other JavaScript framework that supports Ajax requests.
Other option is to use an array to hold your calls. basic idea without doing it all
var ind = xmlhttp.push(new XMLHttpRequest()) - 1;
and
xmlhttp[ind].onreadystatechange ...
xmlhttp[ind].open ...

Categories