I am trying to pass two variables (below) to a php/MySQL "update $table SET...." without refreshing the page.
I want the div on click to pass the following variables
$read=0;
$user=$userNumber;
the div Basically shows a message has been read so should then change color.
What is the best way to do this please?
here's some code to post to a page using jquery and handle the json response. You'll have to create a PHP page that will receive the post request and return whatever you want it to do.
$(document).ready(function () {
$.post("/yourpath/page.php", { read: "value1", user: $userNumber}, function (data) {
if (data.success) {
//do something with the returned json
} else {
//do something if return is not successful
} //if
}, "json"); //post
});
create a php/jsp/.net page that takes two arguments
mywebsite.com/ajax.php?user=XXX&secondParam=ZZZZ
attache onClick event to DIV
$.get("ajax.php?user=XXX&secondParam=ZZZZ". function(data){
// here you can process your response and change DIV color if the request succeed
});
I'm not sure I understand.
See $.load();
Make a new php file with the update code, then just return a json saying if it worked or not. You can make it with the $.getJSON jQuery function.
To select an element from the DOM based on it's ID in jQuery, just do this:
$("#TheIdOfYourElement")
or in your case
$("#messageMenuUnread")
now, to listen for when it's been clicked,
$("#messageMenuUnread").click(function(){
//DO SOMETHING
}
Now, for the AJAX fun. You can read the documentation at http://api.jquery.com/category/ajax/ for more technical details, but this is what it boils down to
$("#TheIdOfYourImage").click(function(){
$.ajax({
type: "POST", // If you want to send information to the PHP file your calling, do you want it to be POST or GET. Just get rid of this if your not sending data to the file
url: "some.php", // The location of the PHP file your calling
data: "name=John&location=Boston", // The information your passing in the variable1=value1&variable2=value2 pattern
success: function(result){ alert(result) } // When you get the information, what to do with it. In this case, an alert
});
}
As for the color changing, you can change the CSS using the.css() method
$("#TheIdOfAnotherElement").css("background-color","red")
use jQuery.ajax()
your code would look like
<!DOCTYPE html>
<head>
</head>
<body>
<!-- your button -->
<div id="messageMenuUnread"></div>
<!-- place to display result -->
<div id="frame1" style="display:block;"></div>
<!-- load jquery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
//attach a function to messageMenuUnread div
$('#messageMenuUnread').click (messageMenuUnread);
//the messageMenuUnread function
function messageMenuUnread() {
$.ajax({
type: "POST",
//change the URL to what you need
url: "some.php",
data: { read: "0", user: "$userNumber" }
}).done(function( msg ) {
//output the response to frame1
$("#frame1").html("Done!<br/>" + msg);
});
}
}
</script>
</body>
Related
I am trying to directly load a page using ajax. Here are the details:
HTML:
<div id="feedback"> </div>
<script type="text/javascript" src="script.js"></script>
script.js:
$(document).ready(function() {
$.ajax({
url: 'do.php',
success: function(data){
$('#feedback').html(data);
});
});
do.php:
<?php
//Do whatever...
echo "Done!";
?>
What I am seeing is: the page first loads, and there is a delay before the "feedback" div gets written. How can I solve this?
As far as I know of course it will have that delay. Suppose your page containing <div id="feedback">[…]</div> is loaded at 0th second now:
$(document).ready(function() {
$.ajax({
url: 'do.php',
success: function(data){
$('#feedback').html(data);
});
});
Is called as apparently it’s visible when document loads. So suppose its called at 3rd second when the document is ready—you can refer to this page for details—now you will be seeing that feedback div blank for 3 seconds.
I can suggest 2 things:
You can place a loader image by default inside the div so your code will change to <div id="feedback"><img src='loader.gif'></div> (Assume you have the loader.gif in the same directory of the page). By doing this you will make the user visually understand that some processing is going on and will load data.
Instead if you can place file_get_contents() or include() so it will look something like this <div id="feedback"><?php file_get_contents('do.php');?></div> or <div id="feedback"><?php include('do.php');?></div> As far as I know file_get_contents will execute the page and then load while include will load and then execute hence in include() you have the variables in the page available whereas in file_get_contents are not available but CSS would work in both cases.
You could start loading immediately and then add the data when everything has completed.
var _data = null;
var _ready = false;
$.ajax({
url: 'do.php',
success: function(data){
_data = data;
tryAddData();
}
});
$(document).ready(function() {
_ready = true;
tryAddData();
});
function tryAddData(){
if(_ready && _data !== null){
$('#feedback').html(_data);
}
}
I have a link that looks like this:
<p class="half_text">
<?php echo $upvotes; ?>
<strong><a class="vote_up" style="color: #295B7B; font-weight:bold;" href="#">Vote Up</a></strong> |
<?php echo $downvotes; ?>
<strong><a class="vote_down" style="color: #295B7B; font-weight:bold;" href="#">Vote Down</a></strong>
</p>
and I have the jQuery code that looks like this:
<script type="text/javascript">
$(document).ready(function()
{
$('.vote_up').click(function()
{
alert("up");
alert ( "test: " + $(this).attr("problem_id") );
// $(this).attr("data-problemID").
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(json)
{
// ? :)
}
});
//Return false to prevent page navigation
return false;
});
$('.vote_down').click(function()
{
alert("down");
//Return false to prevent page navigation
return false;
});
});
</script>
How can I get the parameter value which is problem_id ? If I add a url in the href parameter, I think the browser will just go to the url, no? Otherwise - how can I pack parameter values into the jQuery?
Thanks!
Because your $.ajax is defined in the same scope of the variable, you can use problem_id to obtain the variable value.
An overview of your current code:
var problem_id = "something"; //Defining problem_id
...
$.ajax(
...
success: function(){
...
//problem_id can also be accessed from here, because it has previously been
// defined in the same scope
...
}, ...)
....
If what you're trying to figure out is how to embed the problem ID in the link from your PHP so that you can fetch it when the link it clicked on, then you can put it a couple different places. You can put an href on the link and fetch the problem ID from the href. If you just do a return(false) from your click handler, then the link will not be followed upon click.
You can also put it as a custom attribute on the link tag like this:
<a class="vote_up" data-problemID="12" style="color: #295B7B; font-weight:bold;" href="#">Vote Up</a>
And, then in your jQuery click handler, you can retrieve it with this:
$(this).attr("data-problemID").
do you mean, getting variables from the php page posted?
or to post?
anyway here's a snippet to replace the $.ajax
$.post('/problems/vote.php', {problem_id: problem_id, action: 'up'}, function(data) {
// data here is json, from the php page try logging or..
// console.log(data);
// alert(data.title);
}, 'json');
{problem_id: problem_id, action: 'up'} are the variables posted... use $_POST['problem_id'] and $_POST['action'] to process..
use simple variables names with jQuery.data and make sure you have latest jQuery..
let me try to round it up..
up
down
<script type="text/javascript">
$('.votelink').click(function() {
$.post('/problems/vote.php', {problem_id: $(this).data('problemid'), action: $(this).data('action')}, function(data) {
// data here is json, from the php page try logging or..
// console.log(data);
// alert(data.title);
}, 'json');
});
</script>
I feel like this is something that I should have learned by now, and I'm sure it's something small I'm missing, but I could use clarification to make sure my approach is correct.
I'm using AJAX to post data to self which is a file that contains php and html. I can write the php fine, but after a successful ajax post, how do I only return the data that is processed via php and not the remaining html? Is it better to just post to a separate script?
If you have the PHP handling the POST request in the beginning of the file, you can just do something like this:
<?php
if (isset($_POST['somevar'])) {
/* do something */
exit(0);
}
?>
exit() will stop the loading of the page at that line.
I, for one, think it's better to be utilizing a separate script to deal with dynamic AJAX requests.
You can scrape changed parts of the resulting document and insert them into the original page. This way you can also make your page work for a user with JavaScript disabled not doing anything specially.
Example:
<html><title>Unobtrusive AJAX Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script><script type="text/javascript">
$("form.ajax[id]").live('submit', function() {
$(this).find("input[type='submit']").attr("disabled", true);
$.ajax({
type: $(this).attr('method') || 'POST',
url: $(this).attr('action') || window.location.pathname,
data: $(this).serialize(),
context: $(this),
success: function(data) {
$(this).html(
$(data).find("#" + $(this).attr("id")).html()
);
}
});
return false;
});
</script>
</head><body>
<div><form method="post" class="ajax" id="main">
<p><?php echo date('H:i:s'); ?></p>
<p><input type="submit"></p>
</form></div>
<!-- keep the div: you got to have at least one div to make it work -->
</body></html>
It always depends on what are your needs, but if using the same script is enough for you then do it.
If you want the script not to send anything more than your answer to an XML HTTP Request, after sending the data, use an exit(); in PHP, which will make the script finish at that point.
Put to the of the script:
if($_POST['id']) {
$data = array('return'=>'returnValue');
$data = json_encode($data);
exit($data); }
Javascript:
$.ajax({
url: 'frmSelf.php',
data: $("#frmSelf").serialize(),
dataType: 'json',
type : 'post',
success : function(returnData) {
console.log(returnData);
}
});
I want to use $.post function of jquery to do a div refresh, only if the content returned in the json data from the php script is modified. I know that ajax calls with $.post are never cached. Please help me with $.post, or $.ajax if it is not possible with $.postor any other method with which this is possible.
Thanks
Why don't you cache the response of the call?
var cacheData;
$.post({.....
success: function(data){
if (data !== cacheData){
//data has changed (or it's the first call), save new cache data and update div
cacheData = data;
$('#yourdiv').html(data);
}else{
//do nothing, data hasan't changed
This is just an example, you should adapt it to suit your needs (and the structure of data returned)
var result;
$.post({
url: 'post.php'
data: {new:'data'}
success: function(r){
if (result && result != r){
//changed
}
result = r;
}
});
Your question isn't exactly clear, but how about something like this...
<script type="text/javascript">
$(document).ready(function(){
$("#refresh").click(function(){
info = "";
$.getJSON('<URL TO JSON SOURCE>', function(data){
if(info!=data){
info = data;
$("#content").html(data);
}
});
});
});
</script>
<div id="content"></div>
<input id="refresh" type="submit" value="Refresh" />
I think you should use .getJSON() like I used it there, it's compact, and offers all the functionality you need.
var div = $('my_div_selector');
function refreshDiv(data){
// refresh the div and populate it with some data passed as arg
div.data('content',data);
// do whatever you want here
}
function shouldRefreshDiv(callback){
// determines if the data from the php script is modified
// and executes a callback function if it is changed
$.post('my_php_script',function(data){
if(data != div.data('content'))
callback(data);
});
}
then you can call shouldRefreshDiv(refreshDiv) on an interval or you can attach it to an event-handler
I have a profile page that contains a series of images. I want to use jQuery to allow the user to delete an image from the server and have the page update without reloading the entire page. When it's successful, it will remove the image's containing div from the page. My delete function is PHP; fairly simple:
delete.php
<?php
if (isset($_POST['id'])) {
if (unlink($_POST['id'])) {
echo "success";
}
else {
echo "failure";
}
}
?>
(There's already user authentication in place just to get them to the page that calls delete.php.)
Here's the html of one displayed image - there can be up to 5 of these chunks one after another:
<div class="box">
<img src="uploads/t_10DOT_22C_1111_1300370702_3.jpg" />
<h5><a rel="external" href="uploads/10DOT_22C_1111_1300370702_3.jpg">See full version</a></h5>
<a href="#" id="10DOT_22C_1111_1300370702_3.jpg" class="delete" onclick="return ConfirmDelete();" >x</a>
<div class="clear"></div>
</div>
My jQuery so far looks like this:
$(document).ready(function() {
$('#load').hide();
});
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
type: "POST",
url: "delete.php",
data: string,
cache: false,
success: function(data){
commentContainer.slideUp('slow', function() {$(this).remove();});
$('#load').fadeOut();
}
});
return false;
});
});
The part I'm concerned with is the ajax post. How does the success part actually work? What do I need to do in my php file so that ajax knows whether the delete was a success or failure?
Once an ajax post request has finished executing the file you sent the request to, if there was no error, the code you add in the "success" section is executed, in this case
success: function(data){
/*The code you need*/
});
The previous part if where the code is executed, the "data" variable contains anything you return from your php file, it can be data, it can be a simple "true" or "false", you choose what to send to let your jQuery know if it was successful.
Hope this helps a bit.
Edit Note:
function(applyData){
if ( applyData.toString() == 'invalid' ){
$('#pollError').html('Global styles cannot be modified.');
$('#pollNotice').html('');
}
else{
$('#pollNotice').html('The changes to the style have been applied.');
}
});
The previous example is a live example of what you can do inside the function in the "success" event. There I handle an "invalid" status and otherwise it's successful, after that I refresh a couple DIVs in case of invalid or update a single DIV in case of success.
This is the php that executes:
if ( !$db->isGlobal($id_css)){
$data['id_poll'] = $id_poll;
$data['id_css'] = $id_css;
$data['css'] = $css;
$db->applyCssChanges($data);
}
else{
echo 'invalid';
}
You've two obvious options I can think of:
Your returned text should appear in the data parameter supplied to your success callback function - however you'll probably also need to make sure it's in a format compatible with the MIME Content-Type returned by your PHP, or jQuery might complain that it can't parse it, or:
Send back a 5xx Failure type message from your PHP using the header() function if the delete didn't work. That should then trigger an AJAX error callback, which you'll need to supply.
From delete.php return whether the delete succeeded or not. In the success even check for that data and handle it appropriately.
HTH.