jQuery+AJAX delete anchor not working - php

Hi I'm using jQuery and Codeigniter. I'm creating a simple todo list that can add delete entries using ajax.
The problem is whenever I click on my delete anchor, it won't delete the entry. The adding of the entry feature works BTW.
Here's my code:
todo_view.php
<html>
<head>Todo List</head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function() {
var msg = $('#message').val();
$.post("<?= site_url('todo/add') ?>", {message: msg}, function() {
$('#content').load("<?= site_url('todo/view/ajax') ?>");
$('#message').val('');
});
});
$('a.delete').click(function() {
var id = $('input', this).val();
$.post("<?= site_url('todo/delete') ?>", {todoid: id}, function() {
$('#content').load("<?= site_url('todo/view/ajax') ?>");
});
});
});
</script>
<body>
<div id="form">
<input type="text" name="message" id="message" />
<input type="submit" name="submit" id="submit" value="Add todo" />
</div>
<div id="content">
<?php $this->load->view('message_list'); ?>
</div>
</body>
</html>
message_list.php
<ol>
<?php foreach ($todolist as $todo): ?>
<li>
<?php echo $todo->todo; ?>
<input type="hidden" value="<?=$todo->todoid ?>" />delete</li>
<?php endforeach; ?>
</ol>
Why doesn't it work?

First and foremost - to track GET/POST headers and values you should start using Firebug (an extension for Firefox). Really makes your life easy to terms of debugging ajax calls and responses.
Next (somewhat on the lines of what alimango mentioned)... the most likely cause is that the message list is being loaded AFTER your main page's DOM has already loaded. jQuery won't automatically bind the click event to elements added later. Your click binding routine has to be called AFTER the message list has been added to the DOM. Now this isn't always possible... as your list is being fetched / altered dynamically.
One solution is to use the live() bind event function that has been introduced since jQuery 1.3. This helps binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events. Fore more information, see http://docs.jquery.com/Events/live#typefn
Second solution is to use, LiveQuery - a jQuery plugin which "utilizes the power of jQuery selectors by binding events or firing callbacks for matched elements auto-magically, even after the page has been loaded and the DOM updated." You can grab it from http://plugins.jquery.com/project/livequery
Cheers,
miCRoSCoPiC^eaRthLinG

Related

How to dynamically load a PHP page inside another PHP page's <DIV>?

I currently have two PHP pages: test1.php and test2.php. Inside test1 are 2 DIVs: one named "SubmitDiv", and one named "DisplayDiv". Inside SubmitDiv is a Submit button. When the user clicks on the Submit button, it should load test2.php inside DisplayDiv. Currently test2.php will only display "Hello World". I want it to load test2.php inside the DisplayDiv so that the test1.php page doesn't need to break stride or otherwise reload.
And this is where I am stuck. I am aware that I likely have to make use of AJAX in order for it to dynamically load the test2.php page inside DisplayDiv. How this is done, however, has bested me, and my attempts at it have so far failed. Using the below scripts, which I have pieced together from online searches of this issue, when I try to click on the Submit button - which should load test2.php inside DisplayDiv - instead it just refreshes the whole page and no test2.php is loaded.
test1.php:
<html>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
function loadSubmitResults() {
$(function() {
$('#DisplayDiv').load('test2.php');
});
}
</script>
<body>
<div id="page">
<form id="SubmitForm" method="post">
<div id="SubmitDiv" style="background-color:black;">
<button type="submit" form="SubmitForm" onclick="loadSubmitResults();">Submit</button>
</div>
</form>
<div id="DisplayDiv" style="background-color:red;">
<!-- This is where test2.php should be inserted -->
</div>
</div>
</body>
test2.php:
<html>
<meta charset="utf-8">
<body>
<div id="page" style="background-color:yellow;">
<?php
echo "Hello World.";
?>
</div>
</body>
</html>
If this were something I was working on, I'd change:
<button type="submit" form="QueryForm" onclick="loadQueryResults();">Submit Query</button>
to
<button type="submit" form="QueryForm" onclick="return loadQueryResults();">Submit Query</button>
Then I'd change your loadQueryResults function to:
function loadQueryResults() {
$('#DisplayDiv').load('test2.php');
return false;
}
What this is doing is then returning the value of false to the onclick of the button which as a type of "submit" will, by default, submit the form. Returning any false value on a form submit will cause the form to not submit. Returning false is a general rule when trying to prevent default events from running.
The structure here is a little strange:
function loadQueryResults() {
$(function() {
$('#DisplayDiv').load('test2.php');
});
}
You're declaring a function, but inside of that function you call the jQuery function and pass it a function with the code you want to run? Normally the latter is for running something when the document is ready. It shouldn't be needed here. My guess is that this inner code (the one line you want to run) never actually gets executed.
Does a simpler version like this work for you?:
function loadQueryResults() {
$('#DisplayDiv').load('test2.php');
}
This should just run the code you want when the function is called, without the various decorations of the jQuery function.
For good measure, you should also return false to try to prevent the default submit action:
function loadQueryResults() {
$('#DisplayDiv').load('test2.php');
return false;
}
You can further improve this by using a selector in the call to .load() to pick out only the parts of the DOM that you want. Things like html and body might be stripped out automatically, but explicitly doing things is better than guessing:
$('#DisplayDiv').load('test2.php #page');
Of course, now you're also in a situation where you may end up with multiple elements of the id page in the same DOM, which is invalid. You may want to consider changing some of your ids.
The best way to do this is with the code below:
test1.php:
<html>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
// Handler for .ready() called.
$('#SubmitForm').submit(function( event ) {
$.ajax({
url: 'test2.php',
type: 'POST',
dataType: 'html',
data: $('#SubmitForm').serialize(),
success: function(content)
{
$("#DisplayDiv").html(content);
}
});
event.preventDefault();
});
});
</script>
<body>
<div id="page">
<form id="SubmitForm" method="post">
<div id="SubmitDiv" style="background-color:black;">
<button type="submit" class="btnSubmit">Submit</button>
</div>
</form>
<div id="DisplayDiv" style="background-color:red;">
<!-- This is where test2.php should be inserted -->
</div>
</div>
</body>
test2.php:
<div id="page" style="background-color:yellow;">
<?php
echo "Hello World.";
?>
</div>

submit form using Jquery Ajax Form Plugin and php?

this a simple example in how to submit form using the Jquery form plugins and retrieving data using html format
html Code
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
// prepare the form when the DOM is ready
$(document).ready(function() {
// bind form using ajaxForm
$('#htmlForm').ajaxForm({
// target identifies the element(s) to update with the server response
target: '#htmlExampleTarget',
// success identifies the function to invoke when the server response
// has been received; here we apply a fade-in effect to the new content
success: function() {
$('#htmlExampleTarget').fadeIn('slow');
}
});
});
</script>
</head>
<body>
<form id="htmlForm" action="post.php" method="post">
Message: <input type="text" name="message" value="Hello HTML" />
<input type="submit" value="Echo as HTML" />
</form>
<div id="htmlExampleTarget"></div>
</body>
</html>
PHP Code
<?php
echo '<div style="background-color:#ffa; padding:20px">' . $_POST['message'] . '</div>';
?>
this just work fine
what i need to know if what if i need to Serialize the form fields so how to pass this option through the JS function
also i want show a loading message while form processed
how should i do that too
thank you
To serailize and post that to a php page, you need only jQuery in your page. no other plugin needed
$("#htmlForm").submit(function(){
var serializedData= $("#htmlForm").serialize();
$.post("post.php", { dat: serializedData}, function(data) {
//do whatever with the response here
});
});
If you want to show a loading message, you can do that before you start the post call.
Assuming you have div with id "divProgress" present in your page
HTML
<div id="divProgress" style="display:none;"></div>
Script
$(function(){
$("#htmlForm").submit(function(){
$("#divProgress").html("Please wait...").fadeIn(400,function(){
var serializedData= $("#htmlForm").serialize();
$.post("post.php", { dat: serializedData},function(data) {
//do whatever with the response here
});
});
});
});
The answer posted by Shyju should work just fine. I think the 'dat' should be given in quotes.
$.post("post.php", { 'dat': serializedData},function(data) {
...
}
OR simply,
$.post("post.php", serializedData, function(data) {
...
}
and access the data using $_POST in PHP.
NOTE: Sorry, I have not tested the code, but it should work.
Phery library does this behind the scenes for you, just create the form with and it will submit your inputs in form automatically. http://phery-php-ajax.net/
<?php
Phery::instance()->set(array(
'remote-function' => function($data){
return PheryResponse::factory('#htmlExampleTarget')->fadeIn('slow');
}
))->process();
?>
<?php echo Phery::form_for('remote-function', 'post.php', array('id' => ''); ?> //outputs <form data-remote="remote-function">
Message: <input type="text" name="message" value="Hello HTML" />
<input type="submit" value="Echo as HTML" />
</form>
<div id="htmlExampleTarget"></div>
</body>
</html>

Simple PHP/AJAX question

Ok, so I am fairly new to webdeveloping, so probably a silly question:
I have this search form which does autocomplete for fooditems (gets values from a database column) and that works. Now when I press the submit button I want to load a block of code that displays the food-items' calories etc (also in the database on the same row as the food-item).
How can I accomplish such a thing. I kno this is a fairly broad question, but what i am really asking is, how can I make a small part of my website reload when pressing the submit button and using the input given in the text field as a parameter of some kind.
I don't need whole answers, just any tips getting to the right path would be greatly appreciated!
here my code for the input and button:
in head
<script type="text/javascript" src="jquery.js"></script>
<script>
function ok(){
$.post("test.php", { name: "John", time: "2pm" }, function(data){ alert("Data Loaded: " + data); });
}
</script>
in body:
<form autocomplete="off">
<p>
Food <label>:</label>
<input type="text" name="food" id="food" / >
</p>
<input type="submit" id="submit" value="Submit" onclick="ok()" />
</form>
or:
head:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.js"></script>
<script>
$("input[type='submit']").bind("click", function (event) {
event.preventDefault(); // Stop a form from submitting
$.post("/path/to/call", { /* data? */ }, function (data) {
// Process return data here
});
});
</script>
body:
<form autocomplete="off">
<p>
Food <label>:</label>
<input type="text" name="food" id="food" / >
</p>
<input type="submit" id="submit" value="Submit" />
</form>
jQuery and Ajax.
Change that input to a button
<button id="submit">Save</button>
For this I would do something like:
$("button#submit]").bind("click", function (event) {
event.preventDefault(); // Stop a form from submitting
$.post("/path/to/call", { /* data? */ }, function (data) {
// Process return data here
});
});
You need to first catch the click event .bind("click"). Then initiate an ajax call $.post which you will send data to. This data is received on the server via the POST array.
Like Josh said, jQuery is the way to go here.
You'll want to do 3 things:
Attach a click handler to a button like "onclick='doSomething();'"
In that function,use jQuery to do an async post to a script like
$.post("test.php", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
When this comes back, you can do something with that data(instead of the alert above), like $('#listnode').append... which would stick the HTML into your list
This is the general pattern, but you'll have to fit it to your scenario.
It is hard to answer your question from what little you have given us, but I will assume little knowledge.
Your input fields have to be inside a form tag. The form tag includes an action and a method. The method must be "POST" to send the data. The action can be any URL.
You simply have to name the URL of your php script that will handle the results.
It will find the data in $_POST['food'] etc. It has to build the reply page - the whole screen, with the food and data and the search form for the next submit if you want.
If you want to use AJAX to replace part of the screen, then you have a whole nother level of problems. The trick is to replace the content of a div tag with the requested data.

PHP & JQuery Question?

Is there a way to hide a form from my users until they click a link and then the form drops down for the user to fill out, by using PHP or JQuery if so how? Is there a tutorial that will teach me how to do this?
Yes, you can do so, you hide the form initially either with jquery or css and the slideDown it down like this:
$(function(){
$('a#link_id').click(function(){
$('form-selector').slideDown('slow');
// prevent default action
return false;
});
});
and to hide it back, you can use the slideUp function:
$(function(){
$('a#link_id_2').click(function(){
$('form-selector').slideUp('slow');
// prevent default action
return false;
});
});
If you want to show and hide using same link, use the slideToggle instead:
$(function(){
$('a#link_id').click(function(){
$('form-selector').slideToggle('slow');
// prevent default action
return false;
});
});
Here is the prototype for your html:
<a id="form_show_hide">Show/Hide Form</a>
<div id="form_container">
<form>
...form elements...
</form>
</div>
and jquery for that:
$(function(){
$('a#form_show_hide').click(function(){
$('#form_container').slideToggle('slow');
// prevent default action
return false;
});
});
and finally here the demo for that
try adjusting the display property of the form using hide and show:
jQuery:
$('#formId').hide();
Yes, there are a number of ways to implement something like this. An Ultra Basic implementation:
<form action="" method="post" id="login_form" style="display: none;">
<label for="username">Username</label> <input type="text" name="username" /><br />
<label for="password">Password</label> <input type="password" name="password" />
</form>
Show Form
You could use any number of jquery plugins and methods for showing the form, including show()/hide(), fadeIn()/fadeOut(), slideUp(), slideDown() (as above) etc. You could use something like FancyBox (or Facybox) to display the form in a 'popup' type window.
Note - For compatibility, I'd suggest not using jquery in the onclick event.
Simple:
http://docs.jquery.com/Show
With effects:
http://jqueryui.com/demos/show/
You can do this with jQuery. You need a click target, then an event bound to the click target and a container for the form. Something like:
<span id="ClickTarget">Click Me!</span>
<div id="FormContainer"> <!-- fill in the form here --> </div>
<script type=text/javascript language=javascript>
$('#ClickTarget').click(function () {
$('#FormContainer').show();
});
</script>

jquery/ajax doesnot work

For some reason this does not work. I have copy/paste the code, but it goes to the html-echo.php rather than displaying the result in the htmlExampleTarget
What am I doing wrong here.
Thanks
Dave
edit: sorry guys - here is the url - http://jquery.malsup.com/form/#html
<script src="js/jquery-1.3.2.js" type="text/javascript" language="javascript"></script>
<script type="text/javascript">
// prepare the form when the DOM is ready
$(document).ready(function() {
// bind form using ajaxForm
$('#htmlForm').ajaxForm({
// target identifies the element(s) to update with the server response
target: '#htmlExampleTarget',
// success identifies the function to invoke when the server response
// has been received; here we apply a fade-in effect to the new content
success: function() {
$('#htmlExampleTarget').fadeIn('slow');
}
});
});
</script>
<div style="position:absolute; top:129px; left: 400px; width:500px; border:#000000 thin solid;">
<form id="htmlForm" action="submit_form.php" method="post">
Message: <input type="text" name="message" value="Hello HTML" />
<input type="submit" value="Echo as HTML" />
</form>
Reply: <div id="htmlExampleTarget"></div>
</div>
and on the submit-form.php page
echo '<div style="background-color:#ffa; padding:20px">' . $_POST['message'] . '</div>';
You have two <script> elements. One of them loads jQuery, the other runs ajaxForm. You haven't loaded the .js file that contains the ajaxForm code.
See the documentation:
Include jQuery and the Form Plugin external script files and a short script to initialize the form
Since you haven't, the script errors when trying to run the function, so it doesn't prevent the default action. The code to make the Ajax request is missing (so that doesn't happen), and the default action runs (for the browser goes to the URI in the action attribute).

Categories