I need to know how can I add data from the database without refreshing the field ? I mean just like the working of Add Contacts in the Email. If I click the 'Add' button, I need to open a small window and contacts within it. If I check one or two contacts and press insert, it should be inserted in the 'To' field without refreshing the parent page..!!
How can I do that in php or JavaScript ? Please help me :)
You'll need to use ajax to do so. Ajaxform is great plugin for dynamically adding data to a page from a form. You can use $.ajax from jquery as well. http://jquery.malsup.com/form/#ajaxForm
$(document).ready(function() {
var options = {
target: '#output1', // target element(s) to be updated with server response
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback
// other available options:
//url: url // override for form's 'action' attribute
//type: type // 'get' or 'post', override for form's 'method' attribute
//dataType: null // 'xml', 'script', or 'json' (expected server response type)
//clearForm: true // clear all form fields after successful submit
//resetForm: true // reset the form after successful submit
// $.ajax options can be used here too, for example:
//timeout: 3000
};
// bind form using 'ajaxForm'
$('#myForm1').ajaxForm(options);
});
or regular ajax
$.ajax({
url : url,
data : {name : name}
dataType : 'json',
success : function(data) {}
});
You have to use AJAX, which today stands mostly for Asynchronous JavaScript And JSON. Since you seem to be new to this, I would strongly suggest using a good AJAX library like jQuery, YUI, Dojo, Prototype, etc. It will make your code much easier than doing it all by yourself, and probably also much more portable across browsers. Search for tutorials related to jQuery, AJAX and PHP. I've seen a good talk by John Resig some time ago who was demonstrating pretty much what you are trying to do with jQuery and PHP using very little code. Unfortunately I can't remember the title or link right now but you should be able to find it with no problems.
I can not quite understand your problem, but I think the dom operation can solve this.
Just take a look this example: http://jsfiddle.net/cyhello/Yfhrp/
Hope it helpful. Good luck!
Related
So here I am posting my first PHP function that I am proud of but I just recently learned about AJAX and wanted to test it out. Unfortunately I can't get it to work.
My experience: PHP (3 weeks). CSS3, HTML, Basic Javascript.
My Problem: Getting AJAX to work. I want ajax to get my data from the php file which gets the votes from my test server (Xampp) database. So each time the user clicks on good or bad AJAX should display the new results without refreshing the page. The issue is however that: A) My if statements work by checking isset($_POST) which wont work anymore if I call by AJAX. B) Preventing refresh. C) Making AJAX update after every click. I know im nearly there, im just missing something and I dont know exactly what it is to be honest.
What I tried: Checked my database connection. Checked if my php code worked without ajax and it does perfectly fine (I am just displaying half of the functionality here, a lite version, for the sake of simplicity). Tried to change submit to button. Cache clearing. Jquery is in the head of my document and the path is correct. Watched tutorials and read the documentation but I am just not heading anywhere, probably due to lack of experience.
Edit: Sessions and everything php works fine. I my session start and database connection are included on the very top.
Summary: How do I fix this ajax so that it always updates my numbers?
Let me know if you want me to explain parts of my php code. Im willing to comment the parts if neccesary.
JQUERY / AJAX CODE
function vote() {
var request = $.ajax({
url: "php/core/voting_system.php",
type: "POST",
dataType: 'html'
});
request.done(function(vote_sum) {
$("#votes").html(vote_sum);
});
}
HTML CODE:
<div id='votes'></div>
<form id="good" action="" method="post">
<input type="submit" name="good" onclick="vote()" value="+">
</form>
<form id="bad" action="" method="post">
<input type="submit" name="bad" onclick="vote()" value="-">
</form>
In HTML you don't need <form>, you are doing it with AJAX, right?
<div id='votes'></div>
<button onclick="vote('good');">+</button>
<button onclick="vote('bad');">-</button>
In JavaScript, it is easier to use post rather than ajax function
function vote(gb) {
$.post("php/core/voting_system.php", { vote: gb }, function(vote_sum) {
$("#votes").html(vote_sum);
});
}
In PHP, extract the vote and use it as needed (add validation/sanitation):
$vote = $_POST['vote']; // either 'good', or 'bad'
// do what you need with it
TL;DR version:
You didn't include a data field inside your $.ajax call. Also, your script isn't checking which button was pressed.
The long version
When you're performing your $.ajax call, you fail to attach any data to the request. This can be done easily like so:
$.ajax({
method: 'POST',
dataType: 'json',
data: ...someJSONData...
});
Usually, you're going to want to pass JSON to anything, because it can contain complex object structures that you would usually want to communicate between the client and the server. You're clearly not in this example, but if you're trying to learn this stuff, it's better to start off the right way.
Both javascript and php make using the JSON format extremely easy: JS JSON.stringify() and JSON.parse(), PHP json_encode() and json_decode().
function vote(e) {
// e.target.id stores the id of the button that was clicked
var data = {vote: e.target.id}
$.ajax({
method: 'POST',
dataType: 'json',
data: JSON.stringify(data),
... callbacks and other properties ...
});
}
document.getElementById("good").addEventListener("click", vote);
document.getElementById("bad").addEventListener("click", vote);
This would be a simple example of how you could solve your problem. If you did a simple var_dump in your php script after running the data through json_decode() you would get a nice associative array:
[
'data' => 'good',
]
I hope this illustrates how easy it is to pass data around in this format.
Also notice I defined the event handlers in the javascript. This is generally better, because you keep all your javascript in one place and it makes things cleaner and easier to debug.
Like Jay said you're not sending POST data through the AJAX. You also need to echo your results from PHP.
function vote(event) {
event.preventDefault();
$.ajax({
url: "php/core/voting_system.php",
type: "POST",
dataType: 'html',
data: 'bad='+$('input[name="bad"]').val()+'&good='+$('input[name="good"]').val(),
success: function(data){
var votes = $("#votes").val().empty();
$("#votes").html(data+votes);
}
]);
}
I hope I am missing something simple here. I have a CakePHP web site I am using jQuery mobile with. I think CakePHP might have something to do with it, but I am not sure.
Anyway, I have a form I've created on my view page for adding comments. The Ajax call is working as expected on the first page that loads, but navigating to any other page prevents the data from being submitted. The console still logs 'data' each time I press the button (after using 'pagebeforeshow' as recommended somewhere else), however it seems to be the data from the original loaded page (I know this because I am currently debugging $this->request->data on the Form action page).
Clearly, I must need to "reset" the form somehow when moving across pages, but I am not sure if this is possible without refreshing the page. I do know about "data-ajax"="false" and "rel"="external" which can be used as a last resort, but I want to avoid refreshing the page if I can.
Any suggestions? Thank you.
Here is the JS I am using for the Ajax call
//<![CDATA[
$(document).on('pagebeforeshow', function(){
$(document).off('click', '#comment_add').on('click', '#comment_add',function(e) {
$.ajax({
async:true,
data:$("#sCommentViewForm").serialize(),
dataType:"html",
success:function (data, textStatus) {
//$('#comments').remove();
//$('<div id="comments"></div>').appendTo('#comments_container');
$("#comments").html(data).trigger('create');
//$('#comments_box').remove();
//$('<div id="comments_box"></div>').appendTo('#comments_container');
console.log(data);
},
type:"POST",
url:"commentsUsers/comment_add/<? echo $template['Template']['id']; ?>"});
return false;
});
});
//]]>
</script>
It was my basic lack of understanding. After lots of searching this simple post was most helpful:
Jquery Mobile Javascript not working on ajax load
Basically, I was using IDs for everything - when I switched to class names it was smooth sailing.
On the following page: http://christianselig.com/contact.html I want to have it so when they click Send Message, it will send the message using PHP and keep them on the same page, perhaps changing the submit button to a success message.
Is this possible with PHP and jQuery?
Yes. Use Ajax and event.preventDefault() to submit the form and then use DOM manipulating functionality to update your page.
Look at using ajax to submit the page
$.ajax({
cache: true,
type: 'post',
data: { name: $('#Name').val(), email: $('#email').val(), message: $('#Message').val() },
url: "/controller/sendMessage",
success: function (msg) {
//do something
}
});
Make sure your controller doesn't respond with a response, just pass a Json wrapped Success message back
Yes it is possible, one of two ways in my experience.
You can of course use AJAX, which will make it a lot more smooth for the user, but of course is a little harder.
If you don't mind the user reloading the page, then you would add a action="./contact.html?submit=true, which would simply reload the page, and then you make the form check if the submit variable is set in the $_GET global variable.
Hope this helps. :) (Sorry if this belongs in the comments, I can't actually post in the comments of the main page for some reason.)
I apologize upfront for my lack of jquery knowledge. In this website I am building, a user is presented with a number of thumbnail images representing plants. When a thumbnail is clicked, a jquery popup is initiated. What I would like to be able to do is pass a php variable that has the ID of the plant over to the jquery popup to display the prper information. Any help would be greatly appreciated. Thank you.
EDIT: http://www.plantcombos.com/header/main_index.php?display=random_mix
Im pretty sure you dont need to query PHP each time ... something like this would work :
<img class-"imgclick" src="/small-plant.jpg" data-id="123" />
This would be the output from your server side (php if thats what your using) - it stores the ID of the image in the data attribute
JavaScript :
$(document).ready(function() {
$('.imglink').click(function(event) {
event.preventDefault();
$('dialogid')
.data('image_id', $(this).data('id'))
.dialog('open');
})
})
the image id from the data attribute is then passed to the data attribute of the dialog. This attribute can be accessed using $(this).data('image_id') form within the dialog then
Use the jQuery AJAX method to gather data from a PHP file and display it on the page. It is very easy and you can pass any variables (parameters) you like to the page.
http://api.jquery.com/jQuery.ajax/
For example:
// This will send a request to a PHP page
$.ajax({
url: "http://example.com/test.php",
dataType: "html",
success: function(data){
// Place the returned data into your content
$('#image').html(data);
}
});
I'd like to add a simple functionality to my pages, where a user will see a "follow" button and by clicking it a db record will be created (userID and pageID). I'll handle query on the backend, I suppose. I think I need to do it in AJAX, but I havebn't done much with AJAX. I was also thinking that updating the button status from FOLLOW to FOLLOWING (or something similar) I could do with jQuery, with some sort of toggle, while the request is being processed on the background.
Am I on the right track with this?
You're on the right track.
I've created an example which uses a button like <input type="image" class="follow">. When I user clicks on it it sends a request to the server (url). On success it updates the button image.
$('input[type=image].follow').click(function() {
var button = $(this);
var current_img = $(button).attr('src');
var current_alt = $(button).attr('alt');
$(button).attr('src', '/style/icons/ajax-loader.gif');
$(button).attr('alt', 'Requesting data from the server...');
$.ajax({
url: url of script the processes stuff (like db update),
type: 'POST',
data: {},
dataType: "json",
error: function(req, resulttype, exc)
{
$(button).attr('src', '/style/error.png');
$(button).attr('alt', 'Error while updating!');
window.setTimeout(function() {
$(button).attr('src', current_img);
$(button).attr('alt', current_alt);
}, 3000);
},
success: function(data)
{
$(button).attr('src', '/style/followed.png');
$(button).attr('alt', 'Followed');
}
});
return false;
});
Above is just some example code. Change it at your will. Have fun with it.
AJAX is right, jQuery makes ajax easy.
//Post with jQuery (call test.php):
$.post('test.php', function(data) {
//Do something with result data
});
It sounds like you are on the right track here. If you're working with a smaller application then using an AJAX request and creating your record would be easiest using a Java servlet and putting for example some JDBC code in your doGet or doPost method to perform the database operations.
At the same time your onSuccess method for your AJAX request can call the jQuery code necessary to update your button. Good Luck!