how to pass a parameter to ajaxed loop script? - javascript

This function get a parameter and pass it to this this
$.arte({'ajax_url':'getRealTimeUpdates.php?activity_id='+id, 'on_success':updateLiveUpdates}).start();
[where this line of code feches the upadtes from server each a
specific time period as a jaxed loop]
when I call the function showLiveUpdates(id) with some parameter for example id=5, this line remember id=5 for all this function calls even different parameters !
I want each time I call the function with different id this line of code get the new id
{{ where arte is JQuery plug-in : Ajax Real Time Extension, this is its website click here}}
js code :
function showLiveUpdates(id)
{
//$.arte().stop();
$("#liveUpdates").fadeIn("slow");
$("#liveUpdates").html("");
$("#liveUpdates").append("<div><textarea rows='2' cols='49' id='txtLiveUpdates'></textarea></div>");
$("#liveUpdates").append("<div><input type='button' id='btnliveUpdatesShare' value='share' onClick='addComment("+id+","+getCookie("userId")+")'></div>");
last="";
$.arte({'ajax_url':'getRealTimeUpdates.php?activity_id='+id, 'on_success':updateLiveUpdates}).start();
}
I call it like this:
<input type='button' onClick='showLiveUpdates(<? echo $_GET["id"];?>)' />
edit
function updateLiveUpdates(data)
{
if(data!=last)
{
$("#liveUpdates").append("<div id='updates"+ii+"' style='display:none' >"+data+"</div>");
$("#updates"+ii).fadeIn();
last=data;
}
ii++;
}
getRealTimeUpdates.php
<?php
require("database.php");
$activity_id=$_GET["activity_id"];
$query = "SELECT id,comment from comments where activity_id=$activity_id order by id desc limit 0,1";
echo $query;
$result = mysql_query($query);
$row = #mysql_fetch_assoc($result);
echo $row["id"]."-".$row["comment"];
?>

How about this? Creating a function scope for the id variable:
function createData(id) {
return function () {
return {
'ajax_url':'getRealTimeUpdates.php?activity_id='+id,
'on_success':updateLiveUpdates
}
}
}
for (var id = 0; id < 5; i++) {
$.arte(createData(id)()).start();
}
EDIT 1 Just looked at the code at http://code.google.com/p/arte/source/browse/trunk/jquery-plugin-arte.js.
There is a shared _config property that gets overwritten, and the URL used is always _config['ajax_url'].
EDIT 2 I've posted a demo of this here to demonstrate your issue. So it looks like you cannot call this function multiple times, because the internal state is shared.
EDIT 3 I've updated a jsfiddle with a rough attempt at making this code work as you desire. The demo is here. The new code keeps no state and (seems to) successfully run 5 update loops before terminating them after 3 seconds.

Related

passing primary key instead of attribute on submit

I have an input tag that takes a users input that calls an AJAX dynamically outputs suggestions from my database. The issue is I want to store the primary key associated with that attribute.
I have figured out a way set it to the primary key when the user selects a value; however I would rather only have the attribute displayed on the front end. Essentially what I was thinking about doing was using the option tag and setting the value to the primary key, but after reading the documentation for it, that doesnt look like it would work.
HTML:
<input type="text" id = "zip_id" class="tftextinput2" autocomplete = "off" name="zip" placeholder="Zip Code" onkeyup = "autocompleter()">
<ul id = "zip_codes_list_id"></ul>
JS:
function autocompleter()
{
var min_length = 1; // min caracters to display the autocomplete
var keyword = $('#zip_id').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'ajax_refresh.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#zip_codes_list_id').show();
$('#zip_codes_list_id').html(data);
}
});
} else {
$('#zip_codes_list_id').hide();
}
}
// set_item : this function will be executed when we select an item
function set_item(item)
{
// change input value
$('#zip_id').val(item);
// hide proposition list
$('#zip_codes_list_id').hide();
}
PHP:
<?php
//connect to db here
$keyword = '%'.$_POST['keyword'].'%';
$sql = "SELECT * FROM zip_codes WHERE zip LIKE (:keyword) ORDER BY zip_codes_id ASC LIMIT 0, 10";
$query = $pdo->prepare($sql);
$query->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs)
{
// put in bold the written text
$zip = str_replace($_POST['keyword'], '<b>'.$_POST['keyword'].'</b>', $rs['zip']);
// add new option
// echo '<li onclick="set_item(\''.str_replace("'", "\'", $rs['zip']).'\')">'.$zip.'</li>'; (this one only passes the attribute)
echo '<li " onclick="set_item(\''.str_replace("'", "\'", $rs['zip_codes_id']).'\')">'.$zip.'</li>';
//this one passes the attribute but changes the displayed value to the primary key.
}
?>
As you can see from the PHP file, what I am trying to do is pass in the primary key value but keep the displayed value the attribute. I am not sure how to do that. Should I be using the UL tag?
The issue in your code is that you try to the zip_id value for the input, but this input contains the zip field value - I assume it's the textual representation. There are a few ways how you could save the zip_id on the frontend - either store it in the model (if you're using some MVC framework, but I gues it's not the case) or simply add a hidden input field:
<input type="hidden" id="actual_zip_id" name="zip_id">
And
function set_item(item)
{
// change input value
$('#actual_zip_id').val(item);
// hide proposition list
$('#zip_codes_list_id').hide();
}
UPD
Speakng about the entire idea of autocompleting zip codes, it looks pretty nasty, as pointed by Darren Gourley (check the comments).
So you'd rather validate it with regex first, and then do your db-related logic like that:
$('#zip_id').on('change', function(){
// your stuff
})
Best regards, Alexander

Issue passing PHP variables through Javascript and back

so this function seems to be confusing me.
echo"
<td style='font-size:12px;width:150px;'><div style=\"overflow-y:auto; max-height:250px; width:200px;\">
{$row['Notes']} </div><br /><center><br />
<button onclick=\"myFunction('{$row['ID']}','$rowID')\">Add Note</button>
<form action=\"http://calls.fantomworks.com/functions/notes.php\" id='notesForm' name='notesForm' method='post'>
<input type='hidden' id='notesID' name='notesID' />
<input type='hidden' id='rowID' name='rowID'/>
<input type='hidden' id='notes' name='notes' />
</form>
</center>";
Calls this javascript
<script language="JavaScript" type="text/javascript">
function myFunction(ID,rowID)
{
var x;
var ID = ID;
var rowID = rowID;
var note = prompt("Customer Note","Write your customer note here...");
if (note != null) {
document.getElementById("notes").value = note;
document.getElementById("notesID").value = ID;
document.getElementById("rowID").value = rowID;
document.getElementById("notesForm").submit();
}
else{
return false;
}
}
</script>
and ends up at this php page
$notesID = $_POST['notesID'];
$rowID = $_POST['rowID'];
$note = $_POST['notes'];
//Redirect to browser
header("Location: ./index.php#row_$rowID");
The only problem is that the rowID does not seem to be making it through and generates links ending like "index.php#row_"
I can't make sense of why rowID isn't coming through but NotesID and notes are.
As you can see from the debug the value is there.
Thanks for any thoughts or suggestions!!
The script at "http://calls.fantomworks.com/index.php" is being POSTed to by your javascript function - thus the variable that you seek ought to be available through the $_POST global.
Try changing
header("Location: ./index.php#row_$rowID");
To
header("Location: ./index.php#row_{$_POST['rowID']}");
Incidentally, the three variables you define in the javascript function seem redundant and could be removed by the looks of things, namely:-
var x;
var ID = ID;
var rowID = rowID;
Have had a closer look since posting original ( and hadn't noticed the assignment of posted vars by the #OP ) - there are hundreds of forms on the page in question - same IDS used from row to row to row. IMHO - this is definitely NOT the way forward - You could have just one form for "Add Note" as you dynamcally set the value by clicking the button. It does appear that the relevant vars ( rowID etc ) are being set and assigned to the button that calls the javascript so theoretically you could have just one form that is used to post to "notes.php" but have this button on each row.
In terms of a general critique / suggestions
The page is very slow to load - due in part to there being hundreds of complex table row layouts, and by the looks of things a form for every button - then there are the images which themselves are fullsize but could really be ( and should be ) thumbnails. The number of forms could be drastically reduced if each button were to dynamically assign the variables like the one in the question above.

Filemaker, PHP and jquery > show hide elements

I am echoing out a form (foreach) from my filemaker records which will result in the items ID, Name, a Checkbox and then an image.
In my understanding i will have to use classes or the elements will all have the same id.
My Code;
foreach($result->getRecords() as $record){
$id = $record->getField('Record_ID_PHP');
$name = $record->getField('DB_Name');
$pic = $record->getField('Photo_Path');
echo '"'.$id.'"<br>';
echo $name.'<br>';
echo '<input type="checkbox" class="check" value="Invoices/Photos/RC_Data_FMS/Invoices_db/Photos/'.$pic.'">';
echo '<div class="pics">';
echo '<img style="width:200px;" src="Invoices/Photos/RC_Data_FMS/Invoices_db/Photos/'.$pic.'"><br>';
echo '<hr>';
echo '</div>';
}
Which results in a page full of the records, a checkbox and the relating image.
I wish to only show these images when the checkbox is checked but cannot find a solution, i have tried many jquery scripts, to no avail.
The images will then populate the next page as a pdf to be printed.
I am hoping not to have to grab the checkbox's values as an array to then use the get method with 100's of if statements but cant see another way ?
The jquery ive used.
$(document).ready(function () {
$('.pics').hide();
$('.check').click(function () {
$('pics').show;
});
$('.pics').hide;
});
and
$(function() {
$(".check").click(function(e) {
e.preventDefault();
$('.pics').hide();
$('.pics').show();
});
});
Plus many similar alternatives.
Is there something obvious i am missing ?
Query to filemaker method;
I have changed the path field to a calculated value which works great, thank you, although with 1000's of records, i would need lots of php code to echo the checkbox's to the website and lots more to be able to edit them from the website.
I have done this previously with the value held within the checkbox in filemaker.
$sesame = $print->getField('Allergens::Allergens[11]'); if ($sesame == "Sesame") { $sesame = "checked" ;} else if ($sesame !== "Sesame") {$sesame = "" ;}
This displays the checkbox synced with filemaker.
if ($_POST['Sesame'] == 'Sesame'){ $a_sesame = 'Sesame';} else { $a_sesame = 'No Sesame'; }
This is sent as a variable to my script.
if($a_sesame == "Sesame"){$contains_sesame = "Yes";} else { $contains_sesame = "No";}
This grabs the new value from the form.
Which all work great, but then i am writing a script in filemaker too to enable the to and from of the different names for each checkbox state.
which is for this part 120 lines long, this is a sample which i have to repeat for each repetition of this field.
Set Variable [ $sesame; Value:GetValue ( Get ( ScriptParameter ) ; 11 ) ]
If [ $sesame = "Sesame" ]
Set Field [ Allergens::Allergens[11]; "Sesame" ] Commit Records/Requests
[ Skip data entry validation; No dialog ]
Else If [ $sesame = "No Sesame" ]
Clear [ Allergens::Allergens[11] ] [ Select ]
Commit Records/Requests
[ Skip data entry validation; No dialog ]
Refresh Window
[ Flush cached join results; Flush cached external data ]
End If
This would be far too large to write for so many records, just for these 14 fields used 120 in filemaker and 400 plus in the php.
I am not 100% sure what you are trying to do but this should work. First add an extra div that closes input and div pics like below.
foreach($result->getRecords() as $record){
$id = $record->getField('Record_ID_PHP');
$name = $record->getField('DB_Name');
$pic = $record->getField('Photo_Path');
echo <<<TEXT
'{$id}'<br>
{$name}<br>
<div>
<input type='checkbox' class='check' value='Invoices/Photos/RC_Data_FMS/Invoices_db/Photos/{$pic}'>
<div class='pics'>
<img style='width: 200px;' src='Invoices/Photos/RC_Data_FMS/Invoices_db/Photos/{$pic}'><br>
<hr>
</div>
</div>
TEXT;
}
then change your java to this
$(document).ready(function() {
$(".pics").hide();
$(".check").click(function() {
$(this).siblings().toggle();
});
});
well I hope this helps
Another alternative would be to set up a simple calculated container field in FileMaker, with a calculated value of:
If ( checkbox; imageField )
This would only pass the image when the checkbox was ticked for a record. This should be faster than handling this in JavaScript, since you'd be limiting the number of images being sent over the wire.
Note: For performance, you might try this with this calculated container field stored and unstored. I suspect stored v unstored should make little difference, in which case I'd suggest leaving this unstored to minimize disk space consumed.
You can use the toggle()function:
$(function() {
$('.pics').hide();
$(".check").is(':checked',function(e) {
e.preventDefault();
$('.pics').toggle();
});
});

onClick value + restartCode

<input type="button" onclick="restartBattle('Battle=Trainer&BattleID=294','nFOgYlQGjn')" value="Restart Battle" style="width:160px;">
That is the coding of the button. Unless the restart code is entered as well (it's dynamic, changes every refresh), I can't click the button with the methods of Javascript or jQuery that I've tried.
'nFOgYlQGjn' is the restartCode. I've tried this coding to click the button, but it won't work.
var btn = document.querySelector('input[value="Restart Battle"]');
if (btn) {
var x = Math.round((Math.random() * 90) + 663);
var y = Math.round((Math.random() * 15) + 589);
function restartBattle(url, restartCode) {
$('#battleContent').html('Loading...<br /><br />');
$('#battle').load('http://tpkrpg.net/core/battles/battle.php?'+url+'&RestartCode='+restartCode);
}
//btn.click();
}
This should work, since I took the function restartBattle part out of the source code, but it still won't work. Any ideas?
Pass the data as an object to the script. You could use on('click', method here) or click(method here) on the id of the input tag. Make sure jquery is included too.
button:
<input type="button" value="Restart Battle" id="restart" />
css:
#restart
{
width:160px;
}
jQuery:
/* sample how to get the values as variables
method one, static hard coded
var battleType = "Training";
var battleId = 294;
var restartCode = "nFOgYlQGjn";
method 2, php set via echo, requires page to be created by php, example uses theoretical data returned from a database stored as an associative array but could be changed for variables
var battleType = <?php echo $battle['training']; ?>;
var battleId = <?php echo $battle['id']; ?>;
var restartCode = <?php echo $battle['restart_code']; ?>;
*/
function restartBattle( varz )
{
$("#battleContent").html("Loading...<br /><br />");
$("#battle").load("http://tpkrpg.net/core/battles/battle.php", {Battle : varz.data.type, BattleId : varz.data.id, RestartCode : varz.data.code});
}
// handle the click of the button and execute functon with passed data.
$("#restart").on("click", { type : "Training", id : 294, code : "nFOgYlQGjn" }, restartBattle);
Your php code needs to check for this data being passed to it so it can return the data either some json, html, or plain text using echo.
battle.php:
$restartCode = ( ( isset( $_REQUEST['RestartCode'] ) ) ? $_REQUEST['RestartCode'] : false );
if( !$restartCode ) echo "Error : No restart code!";
That is a start, but you need to create variables that hold the data being sent to the php script or else it's hard coded to those values.
See method API

Is it possible to change a Javascript Variable from an Ajax Response?

I'm trying to update a Javascript variable that controls a scrolling script based upon some Ajax code. The Ajax code is supposed to add to the JS Var when conditions are true in the Ajax script. Is there any way to trigger this?
Thanks!
edit: I'm not sure how to change the value of the variable. I've tried changing it via the Ajax but it doesn't get parsed. I've also tried using PHP inside of JS to check a condition, but doing that only works once.
JS Code
function speedUp()
{
actualheight = actualheight + 50;
}
function slowDown()
{
actualheight = actualheight - 50;
}
function ajaxFunction()
{
var xmlhttp = createRequestObject();
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
document.getElementById('iemarquee').innerHTML=xmlhttp.responseText;
document.getElementById('iemarquee2').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","saleCallTest.php",true);
xmlhttp.send(null);
}
/*
Cross browser Marquee II- © Dynamic Drive (www.dynamicdrive.com)
For full source code, 100's more DHTML scripts, and TOS, visit http://www.dynamicdrive.com
Modified by jscheuer1 for continuous content. Credit MUST stay intact for use
*/
//Specify the marquee's width (in pixels)
var marqueewidth="500px"
//Specify the marquee's height
var marqueeheight="500px"
//Specify the marquee's marquee speed (larger is faster 1-10)
var marqueespeed=1
//Specify initial pause before scrolling in milliseconds
var initPause=1000
//Specify start with Full(1)or Empty(0) Marquee
var full=1
//Pause marquee onMousever (0=no. 1=yes)?
var pauseit=0
//Specify Break characters for IE as the two iterations
//of the marquee, if text, will be too close together in IE
var iebreak='<p></p>'
//Specify the marquee's content
//Keep all content on ONE line, and backslash any single quotations (ie: that\'s great):
var marqueecontent='<?php for($i=0;$i<=count($saleItems);$i++)
{
if ($saleItems[$i]['stateOfItem'] =="Sold" || $saleItems[$i]['stateOfItem'] =="Unsold")
{
$_SESSION['countItems']++;
echo $saleItems[$i]['itemNumber'];
echo $saleItems[$i]['stateOfItem'] . '<br />';
}};
?>'
////NO NEED TO EDIT BELOW THIS LINE////////////
var copyspeed=marqueespeed
var pausespeed=(pauseit==0)? copyspeed: 0
var iedom=document.all||document.getElementById
var actualheight=''
var cross_marquee, cross_marquee2, ns_marquee
function populate(){
if (iedom){
var lb=document.getElementById&&!document.all? '' : iebreak
cross_marquee=document.getElementById? document.getElementById("iemarquee") : document.all.iemarquee
cross_marquee2=document.getElementById? document.getElementById("iemarquee2") : document.all.iemarquee2
cross_marquee.style.top=(full==1)? '8px' : parseInt(marqueeheight)+8+"px"
cross_marquee2.innerHTML=cross_marquee.innerHTML=marqueecontent+lb
actualheight=cross_marquee.offsetHeight
cross_marquee2.style.top=(parseInt(cross_marquee.style.top)+actualheight+8)+"px" //indicates following #1
}
else if (document.layers){
ns_marquee=document.ns_marquee.document.ns_marquee2
ns_marquee.top=parseInt(marqueeheight)+8
ns_marquee.document.write(marqueecontent)
ns_marquee.document.close()
actualheight=ns_marquee.document.height
}
setTimeout('lefttime=setInterval("scrollmarquee()",20)',initPause)
}
window.onload=populate
function scrollmarquee(){
if (iedom){
if (parseInt(cross_marquee.style.top)<(actualheight*(-1)+8))
cross_marquee.style.top=(parseInt(cross_marquee2.style.top)+actualheight+8)+"px"
if (parseInt(cross_marquee2.style.top)<(actualheight*(-1)+8))
cross_marquee2.style.top=(parseInt(cross_marquee.style.top)+actualheight+8)+"px"
cross_marquee2.style.top=parseInt(cross_marquee2.style.top)-copyspeed+"px"
cross_marquee.style.top=parseInt(cross_marquee.style.top)-copyspeed+"px"
}
else if (document.layers){
if (ns_marquee.top>(actualheight*(-1)+8))
ns_marquee.top-=copyspeed
else
ns_marquee.top=parseInt(marqueeheight)+8
}
}
if (iedom||document.layers){
with (document){
if (iedom){
write('<div style="position:relative;width:'+marqueewidth+';height:'+marqueeheight+';overflow:hidden" onMouseover="copyspeed=pausespeed" onMouseout="copyspeed=marqueespeed">')
write('<div id="iemarquee" style="position:absolute;left:0px;top:0px;width:100%;background:black;color:white;font-size:30pt;">')
write('</div><div id="iemarquee2" style="position:absolute;left:0px;top:0px;width:100%;z-index:100;background:black;color:white;font-size:30pt;">')
write('</div></div>')
}
else if (document.layers){
write('<ilayer width='+marqueewidth+' height='+marqueeheight+' name="ns_marquee">')
write('<layer name="ns_marquee2" width='+marqueewidth+' height='+marqueeheight+' left=0 top=0 onMouseover="copyspeed=pausespeed" onMouseout="copyspeed=marqueespeed"></layer>')
write('</ilayer>')
}
}
}
</script>
AJAX->PHP CODE
<?php
session_start();
//NuSoap Library
require_once('./lib/nusoap.php');
$_SESSION['countTotal'] = 0;
//Creating a Client
$client = new nusoap_client('http://xx.xx.x.xxx:xxxx/WSSERVICE/services/SERVICE?WSDL');
$saleItems= $client->call("getItems", array("Sale" => '001'));
$_SESSION['countNew'] = 0;
$countPresale = count($saleItems);
$timer = $countPresale * 3.15;
for($i=0;$i<=count($saleItems);$i++)
{
if ($saleItems[$i]['stateOfItem'] =="Sold" || $saleItems[$i]['stateOfItem'] =="Unsold")
{
$_SESSION['countNew']++;
echo $saleItems[$i]['itemNumber'];
echo $saleItems[$i]['stateOfItem'] . '<br />';
}};
if($_SESSION['countNew'] < $_SESSION['countVehicles'])
{
$_SESSION['countTotal']--;
}
if($_SESSION['countNew'] > $_SESSION['countVehicles'])
{
$_SESSION['countTotal']++;
}
if($_SESSION['countTotal'] < 0)
{
$opx = 3 * ($_SESSION['countItems'] - $_SESSION['countNew']);
echo 'actualheight = parseInt(actualheight) + parseInt(' . $opx . ');';
$_SESSION['countVehicles'] = $_SESSION['countNew'];
}
if($_SESSION['countTotal'] > 0)
{
$opx = 3 * ($_SESSION['countItems'] + ($_SESSION['countNew'] - $_SESSION['countNew']));
echo 'actualheight = parseInt(actualheight) - parseInt(' . $opx . ');';
$_SESSION['countItems'] = $_SESSION['countNew'];
}
?>
Assuming that the variable is not locked away in a different namespace with no interface made available, then of course.
"Ajax" just means "Fetch some data from the server using JS without leaving the page, then run some JS".
There is nothing special that adds extra limitations to what that JS can do.
I ran into some issues with this as well. Probably namespace problems like another answer here suggests.
Rather than figure out the what/when/why, I just used <input name="blah" type=hidden> and then update that and read that with Javascript:
Then, to write the variable:document.getElementById('blah').value='some new value';
To read the variable: somevar=document.getElementById('blah').value;
That has worked every time. Actually figuring out the correct namespace would be a better option, but this works.
EDIT: Are you using any Javascript libraries to do your ajax for you, or just coding it from scratch? I've used xajax, Prototype, and Jquery for things like this. Jquery is my new baby, but 5 years ago already this was dead simple in xajax.
I'm not sure I want to steer you down that path but for a php programmer, xajax is a pretty simple method to learn. Jquery is more powerful and extensible though in my opinion.
EDIT2: Far as I can tell you are returning both HTML and javascript to be executed in the same response. Including a javascript in your response doesn't make it get executed. Perhaps you should be serializing your return with JSON so you can eval your javascript to be executed, and assign your innerHTML separately.
Just for reference, the same thing you could do in xajax with just:
$objResponse->addAssign("idhere","innerHTML", "some html");
$objResponse->addScript("somvar = somevar + someothervar");

Categories

Resources