AJAX Display Images - php

I have a page that shows whether a user has paid or not. If they haven't paid I need to show them an image of a big red X and display a payment button, and if they have paid display a big green check. I know how to do the code for the php script, lets call it pay.php, but I need to iron out the logic for the main page's ajax. So I'm thinking something like this:
<div id="payment">
<div id="image"></div>
<div id="pay_text></div>
</div>
<script>
$(document).ready(function(e) {
if(<?php echo $is_logged_in; ?>) {
$('#payment').load(function() {
$.ajax({
data: $this.serialize(), // get the form data
type: "POST", // GET or POST
url: "Scripts/pay.php", // the file to call
complete: function(data) {
if(data=="Yes") {
$('#image') //do some jquery to make the correct image display here
$('#pay_text').text("Yah you paid");
} else {
$('#image') //do some jquery to make the correct image display here
$('#pay_text').text("Sorry you didn't pay");
}
}
});
}
}
});
</script>
So basically the script would echo back yes or no. And I only want to evaluate this load after the user has logged in (i need to see if that specific user paid). So is my logic write or am I way off?

You probably should'nt use load that way, and there really is no need for it.
Your PHP variable $is_logged_in would of course have to be true before the ajax function will run, and returning true or false is usually the way to go with code, not returning yes or no, and if data is either true or false you can stick it right in the if statement, no fuzz!
As for sending form data with the ajax function, what form? And what is $this?
You'll have to figure out if the user paid or not on the serverside, and you don't really need any data from the client to do that, all you need to do is check your database or whatever it is you're using to see if that user paid, and return true or false.
<script type="text/javascript">
$(document).ready(function() {
if(<?php echo $is_logged_in; ?>) {
$.ajax({
type: "POST",
url: "scripts/pay.php"
}).done(function(data) {
if (data) {
$('#image').css('background', 'url(/yes.png)');
$('#pay_text').text("Yah you paid");
}else{
$('#image').css('background', 'url(/no.png)');
$('#pay_text').text("Sorry you didn't pay");
}
});
}
});
</script>​​​​​​​​​

Related

PHP and AJAX: Echo during process

little issue over here.
I have a php function that is called via AJAX and looks like this:
function processActiveDirectory(){
$var = new GetLDAPUsers;
echo "Getting Users from Active Directory.... <br />";
$adusers = $var->getAllUsers();
echo "setting up images.... <br />";
// processing more stuff
echo "finished";
}
I'm trying to get a "live- log" echo. Meaning before every step the echo should output to a Log area, one step after another. So the user knows what's going on.
But the Problem is, that the log doesn't appear during the process, it just fills in at the whole text at the end of the process. Everything else works fine. The Log just doesn't appear at runtime, but after the function is finished it appears at the right position.
My AJAX call:
jQuery(document).ready(function($) {
$('#lii-form').submit(function() {
data = {
action: 'lii_map_images'
};
$.post(ajaxurl, data, function(response){
$('#lii_log').html(response);
});
return false;
});
});
This is how it's build:
Edit
Other than in this thread I'm already using an ajax call, to call the function. It's within the called function that I'm echoing stuff...
Edit 2
I'm using wordpress
Sorry I can't offer more informations, because of enterprise restrictments.
This is a short over-view on your need. Please develop further with this idea.
This uses two AJAX calling - one for the main process and other for progress:
Script:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
//Start the main process
$.ajax({
url: 'main.php',
success: function(data) {
}
});
function getProgress(){
$.ajax({
url: 'progress.php',
success: function(data) {
$("#progress").html(data);
if(data != "finished"){
getProgress();
}
}
});
}
//Start the progress section
getProgress();
</script>
<div id="progress"></div>
main.php
<?php
$arr = ['Getting Users from Active Directory....','setting up images....','finished'];
foreach($arr as $value) {
session_start();
$_SESSION["progress"]=$value;
session_write_close();
sleep(1);
}
progress.php
<?php
session_start();
sleep(1);
echo $_SESSION["progress"];
So your processActiveDirectory will come under Main.php and echo should be replaced with SESSION variable
I think there is no need in such thing as LOG process WITH AJAX. AJAX is too heavy thing and it could be a bad design if you want it. It's better to use web sockets or not use at all

how do i show a hovercard from a php page

I want to make a simple hovercard that shows me the number 1 coming from a php page: hover.php
<?php
$user='1';
echo json_encode($user);
?>
And show it to me when I hover a simple link on another page index.php using tooltiper function in hover.js
$(function() {
$('.tooltip').tooltipster({
content: 'Loading...',
functionBefore: function(origin, continueTooltip) {
// we'll make this function asynchronous and allow the tooltip to go ahead and show the loading notification while fetching our data
continueTooltip();
// next, we want to check if our data has already been cached
if (origin.data('ajax') !== 'cached') {
$.ajax({
url: '../hover.php',
success: function(data) {
// update our tooltip content with our returned data and cache it
origin.tooltipster('content', data).data('ajax', 'cached');
}
});
}
}
});
});
when I hover the link it just shows me "loading..."
why does the number 1 not show up?

Posting to a PHP script with Ajax (Jquery)

I have an application that I'm writing that, in one aspect of it, you click on a checkmark to complete a task, a popup window is displayed (using bootstrap), you enter your hours, and then that is sent to a PHP page to update the database. I'm using FF (firebug) to view the post. It's coming up red but not giving me an error. The only thing I'm doing is echoing out "sup" on the PHP page, and it's still showing errors, and I can't figure out why.
This is my initial click function:
$('.complete').on('click', function(event) {
var id = $(this).attr('data-id');
var tr = $(this).parent().parent();
var span = $(tr).children('td.task-name');
var r = (confirm('Are you sure you want to complete this task?'));
if (r){
addHours(id);
} else {
return false;
} // end else
});
That works fine, and it fires my next function which actually fires the bootstrap modal:
function addHours(id) {
var url = 'load/hours.php?id='+id;
$.get(url, function(data) {
$('<div class="modal hide fade in" id="completeTask">' + data + '</div>').modal()
.on('shown', function() {
pendingTask(id);
}); // end callback
}).success(function() {
$('input:text:visible:first').focus();
});
} // end function
This is also working, and the modal is displayed just fine. However, whenever I post the form to my logic page, it fails for no reason. This is the function to post the form to the logic page:
function pendingTask(id) {
$('.addHours').on('click', function(event) {
var formData = $('form#CompleteTask').serializeObject();
$.ajax({
url:'logic/complete-with-hours.php',
type: 'POST',
dataType: 'json',
data: formData,
success: function(data) {
if (data.status == 'error') {
$(this).attr('checked', false);
//location.reload();
} // end if
else {
$(this).attr('checked', true);
//location.reload();
} // end else
},
dataType: 'json'
});
}); // end click
} // end function
When this is fired, I see this in my Firebug console:
I know this is a lot of information, but I wanted to provide as much information as I could. Every other post function in the application is working fine. It's just this one. Any help would be appreciated.
Thanks in advance.
The jQuery.ajax data parameter takes a simple object of key value pairs. The problem could be that the object created by serializeObject() is too complex. If that's the case, you could either process the formData object to simplify it or try data: JSON.stringify(formData)
Does serializeObject() even exist in jQuery? is that a function you wrote yourself? Can you use jQuery functions like serialize() or serializeArray() to serialize the form data and see how it goes.
Usually the red indicates a 404 response error. We can't tell in this screen shot. Check your php code by directly calling the requested page and getting a proper response.
Also make sure your dataType is application/json which is the proper mime type header (though I don't think this is causing the error). You also should only have dataType once (you have it again at the bottom)
I figured it out. I changed the post type from the structure I entered above to a standard post:
$("#CompleteTask").validate({
submitHandler: function(form) {
var hours = $('#hours').val();
$.post('logic/complete-with-hours.php', {'hours': hours, 'id':id},
function(data){
if (data.status == 'success') {
$(checkmark).attr('checked', false);
$('.message').html(data.message).addClass('success').show();
} // end if
if (data.status == 'error') {
$('.message').html(data.message).addClass('error').show();
} // end else
},
"json"
); //end POST
} // end submit handler
}); // end validate
That seemed to do the trick

jQuery/JavaScript ajax call to pass variables onClick of div

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>

jquery ajax post - how to get data back?

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.

Categories