How To Pass PHP Variables On jQuery Load? - php

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

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.

specifying div id with jquery

I have buttons and divs and in each part I have them with the same ID I want to get the ID of button and use it for refreshing the div html.how should I write the * section?
$(function() {
$(".button").click(function(){
var id=$(this).attr('id');
var dataString = 'id='+ id ;
$.ajax({
type: "POST",
url: "download_number.php",
data: dataString,
cache: false,
success: function(html)
{
*********I HAVE PROBLEM HERE**************
$('how to get the id of the div from var id of button above?').html(html);
}
});
});
});
Div:
Downloaded:<div id="<?php echo $id; ?>" ><?php echo $downloadcount;?></div>
Button:
<input type = "button" value="Download" class="button" id="<?php echo $id; ?>" name="dl">
If I get class It will update the whole divs I want to update just the div realted to the button
You cannot have the same id on both the button and the div, id values must be unique in a document.
What I'd probably do is put the div's id on the button as a data-divid attribute (all attributes with the prefix data- are valid on all elements as of HTML5, and harmless in earlier versions of HTML), like this:
<input type="button" value="Download" class="button" data-divid="<?php echo $id; ?>" name="dl">
Then change
var id=$(this).attr('id');
to
var id=$(this).attr('data-divid');
...and then use that id var in your success callback (as the callback is a closure created within the context where id is defined, and so the callback has access to id).
Here's a simple example: Live copy | source
HTML:
<div id="div1">This is div1</div>
<div id="div2">This is div2</div>
<div>
<input type="button" data-divid="div1" value="Update div1">
<input type="button" data-divid="div2" value="Update div2">
</div>
JavaScript:
jQuery(function($) {
$("input[type=button]").click(function() {
var id = $(this).attr("data-divid");
// I'll use setTimeout to emulate doing an ajax call
setTimeout(function() {
// This is your 'success' function
$("#" + id).html("Updated at " + new Date());
}, 10);
return false;
});
});
Use the id but prefix them then build the name up...
<div id="div_<?php echo $id; ?>" ><?php echo $downloadcount;?></div>
button:
<input type = "button" value="Download" class="button" id="<?php echo $id; ?>" name="dl">
Then in you're code you have the id used in the buttons already (and also it will be div_), so you can then in you're 'success' just do:
$("#div_"+id).html(html);
change your html to this:
Downloaded:<div id="<?php echo $id; ?>" class="downloaded" ><?php echo $downloadcount;?></div>
then do something like:
var element_id = $(".downloaded").prop("id");
if(element_id = this.id){
$("#"+element_id).html(/* ... */);
}
$(function() {
$(".button").click(function(){
var id=$(this).attr('id');
var dataString = 'id='+ id ;
$.ajax({
type: "POST",
url: "download_number.php",
data: dataString,
cache: false,
success: function(html)
{
$('.count-' + id).html(html); // for class
}
});
});
});
<div class="count-<?php echo $id; ?>" ><?php echo $downloadcount;?></div>
First of all avoid using same IDS.
Then you can use CSS selectors:
$('div.class') //div
$('input[type="button"].youridclass')
You cannot use the id attribute for that purpose, the id cannot be a number (valid html) and thereby id's needs to be unique. Use the data attrib instead.
Try something like:
$('.button').attr('id');
to get the id of the button, then to change it:
$('.button').attr('id',''); //delete previous id if existing
$('.button').attr('id','yourNewId'); //set new id
then to use the new id:
$("#yourNewId").doSomething();
First and foremost, ids should be unique, you'll run into problems, particularly when using jQuery, if you have elements with the same id.
Without seeing your markup it's hard to give you a working example. But you can get the id of the div which corresponds to the clicked button by traversing the DOM.
Example markup:
<div id="example-div">
<input type="button" value="Example" />
</div>
jquery
$('input[type="button"]').click(function() {
console.log($(this).parent('div').prop('id'));
});
// outputs 'example-div'
for your reference check the below link for the various ways that you can use to select the dom elements given the parent element.
jsperf.com/jquery-selectors-context/2

get text value from dynamic created object

I'm still searching solution for getting values from dynamic created object.
Follwing code generates dynamic object from zip2.php
$(document).ready(function() {
$("#submit").click(function(e) {
e.preventDefault();
var q = $("#k").val();
$.ajax({
type: "POST",
url: "zips.php",
data: "q="+ q,
dataType: "html",
success: function(res) {
$("#result").html(res); $('#result').trigger('create');
},
});
});
});
<div data-role="content">
<div id="result"></div>
</div>
It created object like this format.(contents of zips.php)
<? echo " <div><ul id='zips' data-role='listview' data-inset='true' data-theme='c'>";
while($row = mysql_fetch_array($result)) {
$out .= "
<li>
<a name='submit_button' href='#mainPage'><span class='zip1'>$zip1</span>-
<span class='zip2'>$zip2</span><br />
<span class='address'>$row[zp_sido] $row[zp_gugun] $row[zp_dong] $row[zp_bunji] </span></a>
</li> \n";
}
echo $out."</ul>";
?>
And this script get the text() value from dynamic object and insert it to form.
<script>
$(document).ready(function() {
$('a[name=submit_button]').click(function(){
var inputVal1 = $('.zip1, this).text();
var inputVal2 = $('.zip2', this).text();
var inputVal3 = $('.address', this).text();
$('div input[name=zip_code1]').val(inputVal1);
$('div input[name=zip_code2]').val(inputVal2);
$('div input[name=address1]').val(inputVal3);
</script>
<div>
<form>
<input type="text" id='zip_code1' name="zip_code1" > - <input type="text" id='zip_code2 name="zip_code2"><br />
<input type="text" id='address1' name="address1">
</form
</div>
The problem is that "var inputVal1 = $('.zip1, this).text();" gets null from dynamic objects class name "zip1".
Instead of
$('a[name=submit_button]').click(function(){..
use this:
$('#result').on('click', 'a[name=submit_button]', function(){..
As you a[name=submit_button] append to DOM after page load, dynamically via ajax request, so you need delegate event handler to that, ordinary event binding will not work here.
Read more about .on()
Note
For general binding syntax of .on() is like:
$(target).on(eventName, handlerFunction)
but for delegate event systax is
$(container).on(eventName, target, handlerFunction)
Here container is the Static-element that belongs to DOM at page load and contains target and both container and target are valid jQuery selector.

Jquery not considering new div that is added by Jquery + php + jquery

I have a php page where I add and delete items from database using Jquery + PHP + AJAX.
Now I am able to delete and add when that page loads for the first time.
Now if I first add an element; which in turn adds record to the DB and then updates the div that contains all the listing of divs.
Example:
<div id="all_items">
<div id= "item_1">
<a id="delete_link">...</a>
</div>
<div id= "item_2">
<a id="delete_link">...</a>
</div>
.... Upto Item n
</div>
Now I replace the div with id all_items.
Now I have jQuery at the bottom of the page which calls ajax on a tag of delete_link.
Situtation is:
When page is loaded I can delete any item from the list.
But if I page load i add new item first. (which will update all_items div) after that if I try to click on delete link. Jquery on click selector event is not fired and which in turn doesn't do delete ajax operation.
I couldn't figure out why this is happening.
Looking for some help here.
EDITED:
Sorry for not writing code earliar.
Following is the jQuery I am talking about.
<script type="text/javascript" >
var jQ = jQuery.noConflict();
jQ(function() {
jQ("#submit_store").click(function() {
var store_name = jQ("#store_name").val();
var dataString = 'store_name='+ store_name;
dataString += '&mode=insert';
if(store_name =='')
{
alert("Please Enter store Name");
}
else {
jQ.ajax({
type: "POST",
url: "<?php echo $mycom_url; ?>/store_insert.php",
data: dataString,
cache: false,
success: function(html){
jQ("#dvstoreslists").html(html);
document.getElementById('store_name').value='';
document.getElementById('store_name').focus();
}
});
}
return false;
});
jQ(".store_delete").click(function() {
var store_id = jQ(this).attr('id');
var id = store_id.split("_");
var dataString = 'store_id='+ id[2];
dataString += '&mode=delete';
var to_delete = "#store_list_" + id[2]
jQ.ajax({
type: "POST",
url: "<?php echo $mycom_url; ?>/store_insert.php",
data: dataString,
cache: false,
success: function(html){
jQ(to_delete).hide("slow");
}
});
return false;
});
});
</script>
So If on page load, I delete then delete on click jquery event is fired. But after adding new store and replacing div of stores with new div. then jQuery on click event is not fired.
My HTML is as below.
<div class="sbBox stores">
<form id="add_storefrm" name="add_storefrm" method="post" action="" >
<div class="dvAddStore">
<div class="dvName" id="store_list">
<input type="text" id="store_name" name="store_name">
<input type="hidden" value="addstore" id="mode" name="mode">
</div>
<div class="btnAddStore">
<input type="submit" name="submit_store" value="Add Store" id="submit_store">
</div>
</div>
<div id="dvstoreslists">
<?php
$query = "SELECT * FROM #__shoppingstore order by store_id desc;";
$db->setQuery($query);
$rows = $db->loadObjectList();
foreach($rows as $row)
{
echo "<div class=dvlist id=store_list_".$row->store_id ."><div class=dvStoreListLeft>";
echo "<div class='slname'><h3>" . $row->store_name . "</h3></div>";
?>
<div class="slDelBtn">
<p id = "p_store_<?php echo $row->store_id ; ?>">
<a id="store_delete_<?php echo $row->store_id ; ?>" class="store_delete" alt="Delete" onclick="DeleteStore(<?php echo $row->store_id ; ?>);" >
</a>
</p>
</div>
</div>
</div>
<?php } ?>
</div>
</form>
</div>
Sorry folks for not posting the code earliar.
the ID should always be unique so use class instead
in your case : <a id="delete_link">...</a> to <a class="delete_link">...</a>
When you replace the contents of #all_items any event handlers that were bound to any descendants will no longer exist. You can use event delegation, using the on method, to solve this:
$("#all_items").on("click", ".delete_link", function() {
//Do stuff
});
Notice that I'm using a class selector (.delete_link) instead of an ID selector for the links. It's invalid to have duplicate IDs in the same document.
Also note that the above will only work if you are using jQuery 1.7 or above. For older versions, use delegate instead:
$("#all_items").on(".delete_link", "click", function() {
//Do stuff
});
This works because DOM events bubble up the tree from their target. So a click on a link which is a descendant of #all_items will bubble up through all of its ancestors and can be captured when it reached #all_items.
use live() instead of .bind()
It seems you are trying to delete dynamically added delete_link so i think you should use
$('id or class').on(click,function(){});

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