transfer jQuery script to external file - php

I wrote script directly in html file, it adds some pagination feature, and it works just fine until it's in HTML file, but I just cant get how to transfer this script to external js file and make it run from there. So heres html part :
<form id="moredisplay" method="get" style="display:inline;">
<input class="hiddeninteger" type="hidden" name="loadmore" value="">
<!--LIMIT CHANGER-->
<input type="checkbox" title="" id="limitcheck" name="limit" value="<?php echo $vsego;?>" style="display:none;">
<input type="checkbox" title="" id="skipforfcheck" name="skip_items" value="" style="display:none;">
<input type="checkbox" title="" id="skipbackcheck" name="skip_items" value="" style="display:none;">
<button type="submit" title="back" value="" id="rerurn_more_items"/>back</button>
<button type="submit" title="next" value="" id="skip_more_items"/>fowards</button>
<button type="submit" title="more content" value="<?php echo $vsego;?>" id="limit" name="limit" onclick=""/>more content</button>
<script>
var currentval = jQuery('.scippeditems').attr('value');
jQuery('#skip_items,#rerurn_items').attr('value',currentval);
var valuenumber = jQuery('#skip_items').val();
if (valuenumber == 0){
jQuery('#rerurn_items').attr('disabled', 'disabled').css({'opacity':'0.6'});
}
var itemsshow = jQuery('#limit').val();
var pagescount = (jQuery('#skip_items').attr('value'))/(jQuery('#limit').attr('value'));
if(pagescount >=5){jQuery('#skip_items, #limit').attr('disabled', 'disabled').css({'opacity':'0.6'});}//COUNT PAGES AND LOCK NEXT
function changepageforf(){
var elem = document.getElementById("skip_items");
var currentval = elem.value;
elem.value = parseInt(currentval) + 24;}//parseInt(itemsshow);}
function changepageback(){
var elem = document.getElementById("rerurn_items");
var currentval = elem.value;
elem.value = parseInt(currentval) - 24;}//parseInt(itemsshow);}
</script>
<script>
jQuery(document).ready(function(){
jQuery('#limit').click(changelimit);//RUN FUNCTION ON LIMIT CHANGE
if ( document.location.href.indexOf('&limit') > -1 ) {//IF URL CONTAINS LINES LIMIT
jQuery('#rerurn_items, #skip_items').hide()//HIDE PAGINATION
jQuery('#rerurn_more_items, #skip_more_items').show()//SHOW LIMIT PAGINATION
var checkval = jQuery('#limitcheck').attr('value');
var currentvalskip = jQuery('.scippeditems').attr('value');
jQuery('#skipforfcheck').attr('value', (parseInt(checkval)+parseInt(currentvalskip)));//NEXT BTN VALUE
var currentforfaction = jQuery('#skipforfcheck').attr('value')
jQuery('#skipbackcheck').attr('value',Math.ceil( ( (parseInt(currentforfaction)-parseInt(checkval) ) - parseInt(checkval) ) ) );//PREV BTN VALUE
var pagescount = (jQuery('#skipforfcheck').attr('value'))/(jQuery('#limitcheck').attr('value'));
if(pagescount >=5){jQuery('#skip_more_items, #limit').attr('disabled', 'disabled').css({'opacity':'0.6'});}//COUNT PAGES AND LOCK NEXT
if( jQuery('#skipbackcheck').attr('value') <= 0 ){ jQuery('#skipbackcheck').attr('value', 0 );}//RETURN 0 AS A VALUE IF NEGATIVE
jQuery('#skip_more_items').click(function(){//SUBMIT NEXT BTN
jQuery('#limitcheck').attr('checked', true);
jQuery('#skipforfcheck').attr('checked', true);
jQuery('#moredisplay').submit()
});
jQuery('#rerurn_more_items').click(function(){//SUBMIT PREV BTN
jQuery('#limitcheck').attr('checked', true);
jQuery('#skipbackcheck').attr('checked', true);
jQuery('#moredisplay').submit()
});
}
function changelimit(){//LIMIT INCREASE STEP
var elem = document.getElementById("limit");
var currentval = elem.value;
elem.value = parseInt(currentval) + 6;}//HOW MUCH
var valuenumber = jQuery('#skip_items').val();
if (valuenumber == 0){//HIDE PREV BTN IF NO PREV
jQuery('#rerurn_more_items').attr('disabled', 'disabled').css({'opacity':'0.6'});
}
});
</script>
</form>
What i did try: copied script and put in in the pagination.js file and called a script on the top of the page like this
$document =& JFactory::getDocument();
$document->addScript("jquery/pagination.js");
but that doesnt work...Im new to jQuery so please dont bash me if im just stupid:L)

You need to wrap your code in:
$(document).ready( function() {
// your code here
});

As Aspiring Aqib pointed out, you need to start your JQuery script with either
$(document).ready( function() {
// your code here
});
or
$(function() {
// your code here
});
This is basically saying, ' wait until the DOM has been fully created before executing the script inside that function.

Both Aspiring Aqib and Dave were right about wrapping your jQuery code in the $(function(){//code goes here}); block.
Yet one more common mistake is not loading jQuery library file and your own .js files in the correct order, which might be tricky to find out as there is no warning anywhere in your editor or browser. The jQuery library must precede all your own .js files.

Related

php Ajax and jquery form loading then submission not working

I have 4 files testmain.php test1.php test2.php test3.php, in the testmain.php I have a div with class "content_load" where I am loading 3 files on click one by one, they are loading fine but test1.php is a form file when it's finish loading I am submitting it with ajax but it's getting redirect, I am trying since yesterday but not able to solve this, if I do not load files with ajax and just submit the test1.php that works fine, but when I combine the code of loading files using load() and submit with $.ajax() then code for loading files works fine but get redirect any solve this issue for me please so I can go ahead with my learning.
testmain.php
<div id="menu_top">
<a class="menu_top" href="test1.php">TEST 1</a> /
<a class="menu_top" href="test2.php">TEST 2</a> /
<a class="menu_top" href="test3.php">TEST 3</a> /
</div>
<div class="content_load"></div>
test1.php
<form class="ajax" action="test1.php" method="post" enctype="multipart/form-data">
<input type="text" name="txt1" /> <br>
<input type="text" name="txt2" /> <br>
<select name="sel">
<?php
include '../mysql_connect.php';
$db = new DBConfig();
$conn = $db->getDbPDO();
$sql = "SELECT * FROM tbl_campus ORDER BY camp_id ASC";
//$sql = "SELECT camp_id FROM tbl_campus ORDER BY camp_id ASC";
$query = $conn->query($sql);
$result = $query->fetchAll(PDO::FETCH_ASSOC);
$arrlength = count($result);
for ($x = 0; $x < $arrlength; $x++){
?>
<option value="<?php echo $result[$x]['camp_id']; ?>"><?php echo $result[$x]['camp_name']; ?>
<?php } ?>
</select>
<br><br>
<input type="submit" value="Click" name="submit" />
</form>
test2.php & test 3.php
<h3>THIS IS TEST 2</h3> <h3>THIS IS TEST 2</h3>
jquery file
$(document).ready(function() {
$('.content_load').load($('.menu_top:first').attr('href'));
$('.menu_top').click(function(){
var page = $(this).attr('href');
$('.content_load').load(page); return false; });
$('form.ajax').on('submit', function(e){
e.preventDefault();
var that = $(this);
url = that.attr('action'), type = that.attr('method'), data = {};
that.find('[name]').each(function(index, value){
var that=$(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
console.log(response);
}
});
clearAll();
return false;
});
});
function clearAll(){
$("form :input").each(function(){
$(this).val("");
});
}
You cannot use direct event handler to the element that is not loaded yet.Just try to change this line:
$('form.ajax').on('submit', function(e){
to:
$('.content_load').on('submit','form.ajax', function(e){
otherwise javascript doesn't bind that event to the form and regular submit occurs.
Great explanation of the difference here: Direct vs. Delegated - jQuery .on()
May I misunderstood the problem, but if you submit the site would execute the form action.
If you dont want this, you need to add "return false" on submit, or make a "button" and no "input" for submitting.

How To Pass PHP Variables On jQuery Load?

I have code like this :
<?php
$username = 'johndoe';
?>
<head>
<script>
...
$('a.manage-content-link').click(function (e) {
var self = $(this),
file = self.siblings('input[type="hidden.block-hidden-input"]').val();
self.next(".manage-content-wrap").find(".manage-content").load("file-" + file + ".php");
e.preventDefault();
});
...
</script>
</head>
<body>
...
<li><input type="hidden" value="001" class="block-hidden-input" />
<a href="#" id="manage-1" class="manage-content-link">
<img src="images/web-block/web-block1.jpg"/>
<span class="orange-notice">Click to Edit Content</span>
</a>
</li>
<li><input type="hidden" value="002" class="block-hidden-input" />
<a href="#" id="manage-2" class="manage-content-link">
<img src="images/web-block/web-block2.jpg"/>
<span class="orange-notice">Click to Edit Content</span>
</a>
</li>
...
</body>
as you can see there, every time user click "manage-content-link" class, either manage-1, manage-2, ... or even manage-X (multiple li tags) jQuery will load "file-XXX.php". which XXX is actually value of hidden input in li tag.
but that "file-XXX.php" requires $username from PHP tags and ID itself, that is "manage-X". how to pass this 2 variables needed by "file-XXX.php", one from PHP and other from ID's?
Use jQuery's .ajax() instead of .load(): http://api.jquery.com/jQuery.ajax/
$('a.manage-content-link').click(function (e) {
var self = $(this),
file = self.siblings('input[type="hidden.block-hidden-input"]').val(),
this_id = self.attr('id');
$.ajax({
url: "file-" + file + ".php",
data: { username: "<?php echo $username;?>", id: this_id },
context: this,
success: function(data) {
$(this).next(".manage-content-wrap").find(".manage-content").html(data);
}
});
e.preventDefault();
});
If you want to keep the script external, you couldn't rely on php to echo the $username inside the script. So, you could add the username a few ways. You can make a hidden input somewhere in the page with the value equal to the username; you could attach the username to an element (like the body) as a data-username attribute; or you could just have a script block in the header that purely defined the username. For example:
<input type="hidden" name="username" value="<?php echo $username;?>>
Or:
<body data-username="<?php echo $username;?>">
Or:
<head>
<script>
var username = "<?php echo $username;?>";
</script>
</head>
In your <body> you can add a hidden field
<input type="hidden" value="<?=$username?>" id="username" />
and in your jquery,
$('a.manage-content-link').click(function (e) {
var self = $(this),
file = self.siblings('input[type="hidden.block-hidden-input"]').val();
var username = $("username").val(); //use this variable where ever you want
var ids = $(this).attr('id'); // this is the id
self.next(".manage-content-wrap").find(".manage-content").load("file-" + file + ".php?id="+ids+"&username="+username); //and in php file usee $_GET
e.preventDefault();
});
$('a.manage-content-link').click(function (e) {
var self = $(this);
file = self.prev('.block-hidden-input').val();
self.next(".manage-content-wrap").find(".manage-content").load("file-" + file + ".php");
e.preventDefault();
});​
Instead of passing username from script, i would suggest you store username in a session and get that value inside php using $_SESSION['username'] otherwise it will cause you security issue in the future.
DEMO

Adding a "REMOVE" link beside a textbox result by an array

[+] //each time I click this button the textbox will generate and I want to have a link beside each textbox, link is "remove" when I click "REMOVE" the textbox will remove..
[hello1] Remove
[hello2] Remove
[hello3] Remove
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var i=0,j=0;
var t1= new Array();
function createtext(){
i++;
t1[i]=document.createElement('input');
t1[i].type='text';
t1[i].name='text'+i;
t1[i].value = "hello"+i;
t1[i].size = 10;
document.forms[0].appendChild(t1[i]);
var mybr=document.createElement("br");
document.forms[0].appendChild(mybr);
}
</SCRIPT>
</HEAD>
<BODY >
<form action="" method="get" name="f1">
<input name="b1" type="button" onClick="createtext()" value="+">
<input name="b1" type="Submit"><br>
</form>
</BODY>
</HTML>
Well this is simple.
Just add a id attribute with your text field array that will be assigned to each newly created textarea like this:
t1[i].id='some_unique_suffix'+i
t1[i].onClick='remove("some_unique_suffix"'+i+')'
Then you can go on creating a remove link after each textfield via your loop and pass the id of that particular textfield to a remove function that will be called upon clicking on the remove link like this:
function remove(id)
{
$('#some_unique_suffix'+id).remove();
}
Hope you get the idea.
You can add a remove button along with the input tag like this:
var i=0,j=0;
var t1= [];
function add(){
i++;
var parent = document.forms[0];
var div = document.createElement('div');
var input = document.createElement('input');
input.type='text';
input.name='text'+i;
input.value = "hello"+i;
input.size = 10;
t1.push(input);
div.appendChild(input);
var removeButton = document.createElement("button");
removeButton.innerHTML = "Remove";
removeButton.onclick = function(e) {
this.parentNode.parentNode.removeChild(this.parentNode);
return(false);
};
div.appendChild(removeButton);
parent.appendChild(div);
}
Working demo: http://jsfiddle.net/jfriend00/ky9nv/
This code makes it easier to remove an input element and it's associated button by enclosing them in a containing div. A clicked button can then just get it's parent container and remove that.
And, since your question is tagged with jQuery (thought it doesn't save you a lot here), here's a version that uses jQuery:
var i=0,j=0;
var t1= [];
function add(){
i++;
var div = $('<div>');
var input = $('<input>')
.attr({
size: '10',
type: 'text',
name: 'text' + i,
value: 'hello' + i
}).appendTo(div).get(0);
t1.push(input);
$('<button>Remove</button>')
.click(function() {
$(this).parent().remove();
}).appendTo(div);
$("#myForm").append(div);
}
add();
add();
$("#add").click(add);
Working example: http://jsfiddle.net/jfriend00/nbXak/
<script type="text/javascript">
var i=0;
function createtext() {
i++;
$('<div id="field'+i+'">​<input type="text" name="text'+i+'" value="Hello'+i+'" size="10" /> Remove</div>').appendTo('#inputsPlaceholder');
}
function removeField (id) {
$('#'+id).remove();
}
</script>
HTML:
<form action="" method="get" name="f1" id="f1">
<input name="b1" type="button" onclick="createtext();" value="+" />
<div id="inputsPlaceholder"></div>
<input name="b1" type="submit" />
</form>
Try it: http://jsfiddle.net/Z3L5C/

Passing js variable to php variable

I want to pass the id value of the tag that has just been clicked to a php file that is being loaded onto the page using greybox.
I got the id stored in a js variable called linkID and I can get it passing the correct id using location.href but this needs a page reload and doesnt work alongside greybox. Can and maybe how can I use Ajax to help send this info in the background?
Any help would be greatly appreciated?
The Javascript to get the id of the clicked a tag
<script type="text/javascript">
function myCallback(caller)
{
var linkID =caller.id;
location.href="species/butterfly.php?linkID=" + linkID;
alert(linkID);
}
</script>
The html a tag in index.php
<div id="stump">
<a href="#" id="2" class="hedgehog descript" title="Hedgehog"
rel="gb_page_center[1020, 550]" onclick="myCallback(this)"></a>
</div><!--close stump div -->
The butterfly.php page that is trying to recieve the id
<?php
// Retrieve the URL variables (using PHP).
$linkid = $_GET['linkID'];
echo "Number: ".$linkid;
?>
var myCallback = function(caller){
var linkID = caller.id;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","species/butterfly.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("linkID="+linkID;);
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
alert("Request complete. Data: "+xmlhttp.responseText);
}
};
alert(linkID);
}
EDIT:
Pure GreyBox:
var myCallback = function(caller){
var linkID = caller.id;
caller.href = "species/butterfly.php?linkID="+linkID;
}
This will convert js variable to php variable
<script>
function sud(){
javavar=document.getElementById("text").value;
document.getElementById("rslt").innerHTML="<?php
$phpvar='"+javavar+"';
echo $phpvar.$phpvar;?>";
}
function sud2(){
document.getElementById("rslt2").innerHTML="<?php
echo $phpvar;?>";
}
</script>
<body>
<div id="rslt">
</div>
<div id="rslt2">
</div>
<input type="text" id="text" />
<button onClick="sud()" >Convert</button>
<button onClick="sud2()">Once Again</button>
</body>

How to write data option in jQuery.ajax() function when it include in a php mysql_query?

I want to add a comment system after my article,
php part code
<?php
...
while($result = mysql_fetch_array($resultset))
{
$article_title = $result['article_title'];
...
?>
<form id="postform" class="postform">
<input type="hidden" name="title" id="title" value="<?=$article_title;?>" />
<input type="text" name="content" id="content" />
<input type="button" value="Submit" class="Submit" />
</form>
...
<?php
}
?>
ajax part:
$(function($) {
$(document).ready(function(){
$(".Submit").click(function(){
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
var anyBlank = 0;
if(anyBlank == "0")
{
var title = $("#title").val();
var content = $("#content").val();
$.ajax({
type: "POST",
url: "ajax_post.php",
data: "title="+title+"&content="+content,
success: function(date_added){
if(date_added != 0)
{
structure = '<div class="comment_date_added">'+date_added+'</div><div id="comment_text"><div id="comment_content">'+content+'</div>';
$("#post_comment").prepend(structure);
}
});
});
ajax_post.php
echo $title;
echo $content;//get $title and $content and insert into database.
my question: <form id="postform" class="postform"> is written into a MYSQL_QUERY result circle. how to modify ajax part so that every div.submit can post its own value to ajax_post.php and then return the data into $("#post_comment").prepend(structure); Thanks to all.
You have to give the input fields a class instead of an ID. IDs have to be unique in an HTML document:
<form class="postform">
<input type="hidden" name="title" class="title" value="<?=$article_title;?>" />
<input type="text" name="content" class="content" />
<input type="button" value="Submit" class="Submit" />
</form>
Then you can make the data lookup relative to the clicked element:
var title = $(this).siblings('.title').val();
var content = $(this).siblings('.content').val();
I also suggest to pass an object to the data attribute for automatic URL encoding of the values:
data: {title: title, content: content}
Then, when you create a new entry for the #post_comment section, you have to give these elements also a class instead of an ID (and don't forget to use var!):
var structure = '<div class="comment_date_added">'+date_added+'</div><div class="comment_text"><div class="comment_content">'+content+'</div>';
or more jQuery like:
$('<div />', {class:'comment_data_added'})
.append($('<div />', {class: 'comment_date_added', text: date_added}))
.append($('<div />', {class: 'comment_content', text: content}))
.prependTo('#post_comment');
Further notes:
You have somehow a nested ready() handler:
$(function($) { // <--┐
$(document).ready(function(){ // <--┴- this is the same
//...
});
});
Either do:
jQuery.noConflict();
jQuery(function($) {
$('.Submit')...
)};
or
$(function() {
$('.Submit')...
)};
This part in the click handler:
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
var anyBlank = 0;
does not seem to do anything. Besides that, the submit button has no ID and no name.
Depending on the further structure of your PHP code, you should have a look at the alternative syntax for control structures. It makes easier to mix PHP and HTML without fiddling around with brackets.

Categories