onClick value + restartCode - javascript

<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

Related

AJAX data returned is not correct

I have this posts.php where it uses a unique id to view different contents. For example: posts.php?id=1 will display all data on my table which has an id of 1, id = 2 for 2 and so on...
This id is held on a php var $post_id on each page and in order to send this php variable on my jquery/javascript, I used:
<div id = "dummy_disp" style = "display: none;">
<?php echo htmlspecialchars($post_id); ?>
</div>
<div id = "real_commentsno"></div>
( I know, not the best way to do it but it works)
It connects to my js:
var commentid = document.getElementById("dummy_disp");
var commentidreal = commentid.textContent;
$.ajax ({
type:"GET",
url:"php/post_comments.php",
data:'comid='+commentidreal,
success: function(data){
$("#real_commentsno").html(data);
}
});
I have this post_comments.php where it has:
$cc_g_postid = htmlentities($_GET['comid']);
$cc_postid = mysqli_real_escape_string($con,$cc_g_postid);
$cc_sql = "SELECT * FROM comments WHERE postuniqueid = '$cc_postid' ";
$cc_result = mysqli_query($con,$cc_sql);
$cc_count = mysqli_num_rows($cc_result);
echo $cc_count;
When I try to view the post_comments.php alongside with the attached url var: ?comid=1 the page displays 2 which is correct since post id=1 on my table has only 2 comments. But when I go to my posts.php the ajax displays 0, not 2. I tried looking at the console, there were no errors.
Is there anything I missed or misdo? Also, post_comments.php is on located on mypage/php/post_comments.php whereas posts.php is located on mypage/posts.php ( i dunno if this is necessary info but maybe the url is jamming it or something? )
The problem is that the DIV has newlines and spaces around the ID number. You need to remove all this whitespace.
var commentidreal = commentid.textContent.trim();

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();
});
});

Hidden input value to php session

I have a form, which uses the following input towards the end:
<input type="hidden" id="ct_count" name="ct_count" value=""/>
The initialisation of the form is:
<form action="email_submission.php" method="post" id="form1" onsubmit="mySubmit();">
And the mySubmit function is:
function mySubmit() {
document.getElementById('ct_count').value = ct;
document.getElementById("form1").submit();
}
When i hit submit, I want to pass the value of ct, which is a variable count on the page, to email_submission.php and store it in a session variable. The session variable is returning blank on every submit, and i'm unsure if the value of the "ct" variable used is being passed through on the hidden field.
Is someone able to pick up where i'm going wrong? There are already variables stored correctly through this, so it's not my session settings as far as i know.
tldr: What's the correct way to take a javascript variable count and pass it through form submit to php?
EDIT:
this is the code for adding fields.
intiial loop for the variable "ct"
function new_link()
{
ct++;
<?php $ct = $ct + 1; ?>
document.getElementById("sec4_lender").setAttribute('name', 'sec4_lender_<?php echo $ct;?>');
document.getElementById("sec4_balance").setAttribute('name', 'sec4_balance_<?php echo $ct;?>');
document.getElementById("sec4_termdate").setAttribute('name', 'sec4_lender_<?php echo $ct;?>');
document.getElementById("sec4_security").setAttribute('name', 'sec4_security_<?php echo $ct;?>');
document.getElementById("sec4_description").setAttribute('name', 'sec4_description_<?php echo $ct;?>');
document.getElementById("sec4_status").setAttribute('name', 'sec4_status_<?php echo $ct;?>');
document.getElementById("sec4_repayment").setAttribute('name', 'sec4_repayment_<?php echo $ct;?>');
document.getElementById("sec4_repayment2").setAttribute('name', 'sec4_repayment_2_<?php echo $ct;?>');
var div1 = document.createElement('tr');
div1.id = 'sect4busloan_div_'+ct+'';
// link to delete extended form elements
var delLink = '<tr style="text-align:right;margin-right:65px">Del</tr>';
div1.innerHTML = document.getElementById('newlinktpl').innerHTML + delLink;
document.getElementById('newlink').appendChild(div1);
}
// function to delete the newly added set of elements
function delIt(eleId)
{
d = document;
var ele = d.getElementById(eleId);
var parentEle = d.getElementById('newlink');
parentEle.removeChild(parentEle.childNodes[eleId]);
var newct = ct - 1;
ct = newct;
<?php $ct = $ct - 1;?>
}
You're taking the input's value and always setting it to ct -
document.getElementById('ct_count').value = ct;
You should get a warning or error about ct in the console if you do it this. What you should do is set a variable to the value of the input -
var ct = document.getElementById('ct_count').value;
It also appears that you never set the value of the hidden field, so in the example I post here ct's value will always be blank.
It turned out that while bug testing i had moved that single session out of the conditionals for my script. So for every page other than the first i was moving on to, it was requesting a blank variable.
Idiocy at its finest. Thank you very much for everyone helping in this matter.

how to pass a parameter to ajaxed loop script?

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.

Categories

Resources