php Ajax and jquery form loading then submission not working - php

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.

Related

Php echo button onclick get id

I hava a dynamic list, loading from database in my php page.This list also have a delete button. When i click this button i need to get id of this button and delete from database that line with php code.
$dbh = new PDO("sqlite:database.sdb");
$sql ="SELECT * FROM clip";
foreach ($dbh->query($sql) as $row)
{
print 'Id: '. $row['id'] .'<br />';
echo '<input type="submit" id="'.$row['id'].'" value="delete" name="del">';
}
also this is my final code for button click;
$dbh->exec("delete clip where id='in here should be button id'");
How can i connect with this two code. Thanks already.
Given the level of your question I am assuming you are unfamiliar with jQuery and AJAX, but you should research both.
For a simple solution not using these you could do as follows:
Change the output to be <input type="button" id="'.$row['id'].'" value="Delete" onclick="do_delete(this.id)">;
Then you need a php script on the server side to handle the delete function, e.g. yourhandler.php
<?
//connect to DB here
if ($_POST['id']) {
$sql = "delete from clip where id=:delete_id";
$stmt = $dbh->prepare($sql);
$stmt->execute([':delete_id'=>$_POST['id']]);
}
?>
Then on the client side you need a form which submits when the button is clicked. Here is an example form code:
<form action="yourhandler.php" method="post" id="myform">
<!--Your PHP script which creates buttons-->
<input type="hidden" value="" name="id" id="delete_id">
</form>
<script>
function do_delete(which) {
var x = document.getElementById('delete_id');
x.value=which;
document.getElementById('myform').submit();
}
</script>
You can use this working jquery template for your task. It binds to all inputs that has a name="del".
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
$(document).ready(function() {
$('input[name="del"]').on('click', function() {
alert('button id is '+$(this).attr('id'));
var button_id = $(this).attr('id');
$.ajax({
method: 'post',
url: "delete.php",
data: {'did':button_id},
dataType: "html",
success: function(result) {
alert(result);
}
});
});
});
</script>
In your PHP delete file, you can retrieve the delete id via $_POST['did'].

transfer jQuery script to external file

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.

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

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

Jquery Ajax selectors

Im trying to make something like this http://demos.99points.info/facebook_wallpost_system/ which is a comment system. I have the ajax code below except i don't know how to uniqely select textareas. The challenge is that the number of posts is variable so all of the posts need to be uniquely identified so that when the data is put into the database i know which post it relates to.
JQUERY:
<script type='text/javascript'>
$('document').ready(function(){
$('.commentContainer').load('../writecomment.php');
//commentContainer is a class so it applies to all of the textareas, but i need this selector to be unique
$('.submitCommentBox').click(function(){
//these are the selectors that i can't get to work right
var comment = $('').val();
var postid = $('').val();
$.post('../comment.php',
{
comment: comment,
postid: postid,
},
function(response){
$('#commentContainer').load('../writecomment.php');
$('.commentBox').val('');
}
}
return false;
}):
});
</script>
HTML/PHP
<?php while ($row=mysql_fetch_assoc($query)){
echo"
<p name='singlePost'>$post[$f]</p>
<div id='commentContainer'></div>
<textarea class='commentBox'></textarea>
<input type='button' value='submit' class='submitCommentBox'>";
}
basically the HTML/PHP generates for each post on the page as to create a textarea and subimt button for each post. therefore the user can comment on each post.
Using the markup in the link you provided, I would do something like:
var container = $(this).closest('.friends_area');
var comment = $(container).find('.commentbox').val();
var questionid = $(container).find('#hidden').val();
var answerid = $(container).find('').val();
A more correct solution would be something like:
HTML
<div id="posting">
<form method="post" action="">
<input type="hidden" name="record_id" value="123" />
<textarea name="comment"></textarea>
<button type="submit">Comment</button>
</form>
...
</div>
JS
$('#posting').on('submit', 'form', function(e) {
e.preventDefault();
var form = $(this).closest('form');
$.post($(form).attr('action'), $(form).serialize(), function() {
$('#commentContainer').load('../writecomment.php');
$('.commentBox').val('');
});
});

Categories