asynchronous iframe using jquery - javascript

So I'm creating a code portfolio based upon what's in my svn repo.
I'm currently set up like this:
PHP loops through my JSON and creates these little menus for each file in each project. Here's some (very poorly structured) code showing how I generate each of these:
<form action = "" method = 'post'><select name = "s2" id = "s2"> <?php
foreach($proj2->item_vers as $ver)
{
?>
<option value = <?php
$base_str = (string)$ver->revision;
$full_str = "\"".$base_str."\"";
echo($full_str); ?> > <?php
echo($base_str); ?> </option>
<?php
} ?> </select><input type = 'submit'/></form>
<a href = <?php
if (isset($_POST['2']))
{
$rev2 = $_POST['s2'];
}
else
$rev2 = "";
$full_url = "https://myrepo".
$proj2->name."?p=".$rev2;
$ret_url = "\"".$full_url."\"";
echo($ret_url); ?> > Code </a></td>
So I have a form, select, option. The select will post the selected version from the drop down. Then I have a hyperlink which forms the correct url based upon the posted version number. This hyperlink will need to be replaced with an iframe. For the sake of simplicity, lets say that each project has its own iframe which is updated with appropriate project file any time you click one of the submit buttons.
So like this:
I'm looking for the simplest way to set this up to work asynchronously.
My thoughts:
I've already set up an asynchronous comment system using jQuery. The difference was that I only had three little inputs and a button to submit the comment. This just seems like it will be much more complicated as the code I posted above will loop through about 100 times. I cant just hard code a different id to every single submit button and write 100 different .js scripts to operate when each individual button is clicked.

OK, so im going to simplify your form generation code to make this clearer. I am including the outer loop you dont show:
<div id="forms-holder">
<!--this is the outer loop-->
<?php foreach ($projects as $project):?>
<!-- remove any ids in the loop, they can not be duplicated-->
<form action="" class="projectform">
<!-- add name to data attribute for easy retrieval by js-->
<select name="s2" data-projectname="<?php echo $project->name;?>">
<?php foreach ($project->item_vers as $ver):?>
<option value="<?php echo'"'. $ver->revision .'"';?>"><?php echo $ver->revision;?></option>
<?php endforeach;?>
</select>
<input type = 'submit'/>
<form>
<?php endforeach;?>
</div>
<iframe src="" frameborder="0" id="myiframe"></iframe>
<script type="text/javascript">
$(function(){
//when any form is submitted
$('.projectform').submit(function(ev){
ev.preventDefault();
//grab revision and project name
var revision = $(this).find('select').val();
var projname = $(this).find('select').attr('data-projectname');
//generate the url
var iframeurl = "https://myrepo"+projname+"?p="+revision;
//set the iframes url
$('#myiframe').attr('src', iframeurl);
})
});
</script>

Related

fetch data without reloading by passing a variable to jquery

I want to fetch some data (without reloading page) based on UserIds that are linked to a tags. I am not able to pass on UserID to jquery successfully and accurately. What it does is, just picks the last UserID and fetches it.
I have also tried to pass on variable throuh a-tag URL but could not get it accurately in jquery file. It fetches the data from already opened url, not the one being clicked right now.
HTML:
<?php foreach($Messagers as $Messagers1){ ?>
<form action="" method="post">
<input type="hidden" id="ANP" value="<?php echo ($Messagers1['UserID']*3);?>"></input>
<a class="LoadMsgsBtn">
Click to load data
</a>
</form>
<?php}?>
<div id="result">
<--The output will come here!-->
</div>
jquery:
$(document).ready(function(){
$(".LoadMsgsBtn").click(function LoadMsgsfunc(){
var ANP = $("input#ANP").val();
var Msg=6;
alert(ANP);
$("#result").load("LoadDB.php",{
ANP: ANP,
Msg: Msg
});
})
});
LoadDB.php:
<?php
$ID = $_POST['ANP'];
$Msg = $_POST['Msg'];
echo $ID . "\n";
echo $Msg;
I want to fetch data from database without reloading using UserID sent. $Messager is an array having multiple rows, there is a series of a-tags. clicking on any a-tag sents corresponding UserID to jquery code
Classic issue of multiple element selection. It's a bit tricky when you are using loops and jquery selectors ;) Check out the following code. It should work like butter B)
<?php foreach($Messagers as $Messagers1){ ?>
<form action="" method="post">
<a class="LoadMsgsBtn" href="javascript:void(0)" onclick="featchData('<?php echo ($Messagers1['UserID']*3);?>')">
Click to load data
</a>
</form>
<?php}?>
<div id="result">
<--The output will come here!-->
</div>
Javascript
function featchData(userId)
{
console.log(userId);
//if you get the id, write in the rest of the code here ;)
}

Use get_option in WordPress to create new JavaScript variable

So I've been building my first WordPress plugin, and I've of course hit some roadblocks. I first wrote all this code as a page template, but now I'm converting it to a plugin so I can use it across several sites.
It's essentially a contact form that creates a price quote based on user selection. When it was a template, I just hardcoded the values and made everything work with an external jQuery file. Now, I'm wanting to take user input from the plugin admin settings page and use that value to make calculations rather than the values I hardcoded.
Here's what I had before with the jQuery:
(function($) {
$(document).ready(function(){
$("#carpet_cleaning).change(function () {
var bedrooms = $("#carpet_cleaning").val();
/*-------CHANGE RATES HERE--------*/
var total = (bedrooms * 39);
var totalPrice = "$" + total;
$("#output1").text(totalPrice).fadeIn();
});
}(jQuery));
So basically I want to use user input from the plugin admin settings instead of hardcoding a 39. That way prices can vary depending on what price the user wants to set.
Here's my HTML for my admin settings:
<h2>Display Settings</h2>
<form method="post" action="options.php">
<?php settings_fields( 'my-plugin-settings-group' ); ?>
<?php do_settings_sections( 'my-plugin-settings-group' ); ?>
<fieldset>
<input type="text" size="3" name="carpet_cleaning_price" value="<?php echo esc_attr( get_option('carpet_cleaning_price') ); ?>" /><label>Carpet Cleaning Price Per Room</label>
</fieldset>
<?php submit_button('Save all changes', 'primary','submit', TRUE); ?>
</form>
I was under the impression that I could use get_option to store the user input. If that's the best way to do that, how could I access that value in my jQuery variable?
Ideally I'd want to do something like:
var sectionalCleaning = carpet_cleaning_price;
And then just use carpet_cleaning_price instead of 39, which would give me the user value.
Is there some way I can do this easily? I'm also going to have to do this on the backend using PHP so that someone can't adjust the values in their browser and the calculation happens on the server, so if you have a solution for that as well, I'm open to that. Go easy on me, I'm a new developer! Thank you.

Jquery and AJAX script to run a PHP script in the background to avoid any refreshing

I have built a follow/unfollow Twitter like system using PHP. Now I would like to run the follow-unfollow PHP script in the background using AJAX/JQUERY to avoid refreshing the page when you follow/unfollow a user. To make things simpler, I will be here just using the example of “unfollow”. As you notice, I am running an iteration to output all the members in the database. I am outputting here (as well for simplicity) just the member’s name and an unfollow button to each one.
This is the code using php.
members.php
<?php foreach($members as $member){ ?>
<p class="member_name"><?php echo $member->name; ?></p>
<p class="follow_button">Unfollow</p>
<?php } ?>
unfollow.php
<?php
if($_GET['unfollow_id']){
$unfollow_id=$_GET['unfollow_id'];
$unfollow=Following::unfollow($id, $unfollow_id); //Function that will make the changes in the database.
// $id argument will be gotten from a $_SESSION.
}
I am trying to achieve the same result running unfollow.php in the background to avoid any refreshing. This is what I have come up with, as you might imagine it is not working properly. I am including the Jquery script inside the iteration which I think is the only way of obtaining the $member->id property to then assign it to the Jquery variable.
members.php THE NEW ONE THAT TRYS TO RUN THE SCRIPT WITH AJAX JQUERY
<?php foreach($members as $member){ ?>
<p class="member_name"><?php echo $member_name; ?></p>
<button type="button" class="unfollow_button" id="unfollow">Unfollow</button>
<script type="text/javascript">
$(document).ready(function(){
$("#unfollow").click(function(){
// Get value from input element on the page
var memberId = "<?php $member->id ?>";
// Send the input data to the server using get
$.get("unfollow.php", {unfollow_id: memberId} , function(data){
// Success
});
});
});
</script>
<?php } ?>
Can you provide me any help for this to work?
Thanks in advance.
Remember, in HTML, id attributes have to be unique.
Because you're rendering multiple members on a single page, you should not use an id selector in jQuery, but a class selector (e.g. button.unfollow). If you use #unfollow, you'll run into ID conflicts between each of the members' buttons.
First, render all of your members with unfollow buttons without ids. I'm adding the member_id in the markup using a data attribute called data-member_id.
<?php foreach($members as $member) { ?>
<p class="member_name"><?=$member_name?></p>
<button type="button" class="unfollow_button" data-member_id="<?=$member->id?>">Unfollow</button>
<?php } ?>
Then add a single click handler for all button.follow buttons, which extracts the member_id from the clicked button's data-member_id attribute and sends it to the server.
<script type="text/javascript">
$(document).ready(function() {
$("button.unfollow_button").on('click', function() {
// Get value from input element on the page
var memberId = $(this).attr('data-member_id');
// Send the input data to the server using get
$.get("unfollow.php", {unfollow_id: memberId} , function(data) {
// Success
});
});
});
</script>
On a side-note, you should probably look into building a RESTful service for this, to which you can post proper HTTP requests using http://api.jquery.com/jquery.ajax/.
See here for an intro on REST in PHP I wrote a while back:
Create a RESTful API in PHP?

JQuery populating select box but after post options disappear

I have an SVG map. When someone clicks on a state say, "Kansas" it displays a form and populates the state select box with the state that was clicked on say, it's Kansas. Code - This is working fine. This code is in the head.
var itemval= '<option value="'+data.name+'">'+ stateData[data.name].fullName+'</option>';
$("#SelItem").html(itemval);
When the form is submitted and it posts back to the same page, I'm using
<form method="POST" action="theform.php" onsubmit="return validateForm(this);">
When the page post back to the same page the select box is empty. The select box is there but with no option.
I've searched on Google I found the code below plus a few similar ways but they don't work. I've used this code in the head and under the select but no luck.
var selectedVal = $("#SelItem").val();
$("#SelItem").val(selectedVal);
**HTML**
<select id="SelItem"><option></option></select>
I've been working on this for hours but can't seem to find a solution.
Can someone tell me how to keep the select value after the form has been submitted and returns to the same page?
When the page loads you need to check for the presence of your posted value, and if it's there pass the php value to either the javascript code to populate the select option, or use it directly in the html creating the select options.
First off, you should give your select a name attribute in the html so the value is passed into the $_POST array in php:
<select id="SelItem" name="SelItem">
Here's one way you can populate it in javascript (note this code relies on the var stateData being in the same scope):
$(document).ready(function(){
<?php if (!empty($_POST['SelItem'])): ?>
var posted_state = '<?php echo $_POST['SelItem'];?>';
if (stateData[posted_state] !== undefined) {
var itemval= '<option value="'+posted_state+'" selected>'+ stateData[posted_state].fullName+'</option>';
$("#SelItem").html(itemval);
}
<?php endif; ?>
});
EDIT: An alternative to the above would be to put it in the html for the select tag:
<select id="SelItem" name="SelItem">
<?php if (!empty($_POST['SelItem'])): ?>
<option value="<?php echo $_POST['SelItem'];?>" selected>
<?php echo $_POST['SelItem']; // this would be better if you can replace it with fullname ?>
</option>
<?php else: ?>
<option></option>
<?php endif; ?>
</select>
Note this method has a couple issues as it's written. First off, the option text in this example won't be the state full name but the abbreviation. Next, you shouldn't trust the contents of $_POST because a malicious user can easily change it to a value you didn't intend it to be. It would be better to validate the value of $_POST['SelItem'] in your php code that handles the post to make sure it is actually one of the correct values before using it. That is why in the previous example I did the check if (stateData[posted_state] !== undefined) before attempting to add the value to your select.
EDIT:
To provide the state fullname from php you need an array of states defined on the php side also (I only see it in your javascript code which is client side).
So in php if you have something like:
$states = array(
'AK' => 'Alaska',
'AL' => 'Alabama',
// etc...
);
Then you can use the posted state abbreviation to get the fullname:
if (array_key_exists($_POST['SelItem'], $states))
$fullname = $states[$_POST['SelItem']];

PHP, Javascript Help Required

I am new to this forum. I have been developing a interface and have got stuck with PHP and Javascript.
My Site has 3 Buttons
<button id="ProjectSource" class="testbutton" onClick="AddNewProject(this.id);">Project Source</button>
<button id="SelfCons" class="testbutton" onclick="AddNewProject(this.id)">Self Cons</button>
<button id="Currency" class="testbutton" onclick="AddNewProject(this.id)">Currency</button>
These buttons are sent to a Javascript function on the same page which will store the button ID in a variable, which is later used in another PHP.
Now I have an Select Box in the same page and I get the data from the database using PHP.
<select size="10" id="Database" onClick="ClearAdd()" >
<?php
while($row = mysql_fetch_assoc($get))
{
?>
<option value = "<?php echo($row['ProjectSource'])?>" >
<?php echo($row['ProjectSource']) ?>
</option>
<?php
}
?>
</select>
My First Problem is
If you see I am currently using $row['ProjectSource']), But what I need is the ID of the buttons which corresponds to the field name in the database.
My Second Problem is
The Select functions loads when the page loads, I want that to refresh when I click on any buttons.
Thanks in Advance for your help!
use mysql fetch query
For example:
while ($row = mysql_fetch_assoc($query)){
$id = $row['id'];
}
For your second Problem you should implement ajax. Either using javascript or jquery.
Regarding first problem it is not clear What are the field names and how button Id is implemented? It would be better if you post some code
Can you implement some kind of mapping of your fieldName to your buttonId using associative array? like array("fieldName1"=>"id1",....)

Categories

Resources