I'm trying to utilize jQuery/Ajax more in my web projects, as a test I have done:
HTML Code
<div id="main_content"></div>
<div class="panel panel-primary">
<div class="panel-heading">API Credits Left.</div>
<div class="panel-body">
<form id="frmAjax" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post" class="form-horizontal container-fluid" role="form">
<div class="row form-group">
<div class="col-sm-12 text-right">
<button type="submit" name="submit" class="btn btn-default">Check the API credits...</button>
</div>
</div>
</form>
</div>
<div class="panel-footer"><b>DomDetailer</b> & <b>SeoKicks</b> Api credits left.</div>
</div>
Script
$(function() {
$(document).ready(function(){
$('#frmAjax').submit(function() {
$("#main_content").load('ajax-credits.php');
});
});
});
The ajax-credits.php contents:
<?php
echo "Loading...";
// http://site1.com/api/checkBalance.php?apikey=QRUE8VTQMD5Fj6&app=
$json1 = file_get_contents('http://site1.net/api/checkBalance.php?apikey=QRUE8VTQMD5F6&app=');
$data1 = json_decode($json1, true);
$valu1 = $data1[1];
// seokicks
$json2 = file_get_contents('http://www.site2.net/V1/inlinkData?appid=p2hFacSWU0&output=json&details=api_credits');
$data2 = json_decode($json2);
$valu2 = $data2->Overview->credits->available;
// display
stdmsg("Site 1 has <b>".$valu1."</b> credits left and Site 2 has <b>".$valu2."</b> credits left.");
?>
Very basic code (or so I thought) can anyone see what I have done wrong? Nothing is being displayed in the div , is there any issue?
Try removing echo "Loading"; and replacing
stdmsg("Site 1 has <b>".$valu1."</b> credits left and Site 2 has <b>".$valu2."</b> credits left.");
by
echo "<p>Site 1 has <b>".$valu1."</b> credits left and Site 2 has <b>".$valu2."</b> credits left.</p>";
(Whatever you echo in the PHP script called by a jQuery AJAX function is what gets sent back to the AJAX function, so that is what will get loaded into your HTML div.)
Related
I have around 6 div on a page and only one of them needs to be visible at a time. During page load, I hide all the other divs except the first one.
Here's my HTML structure.
<div id="A1">
</div>
<div id="A2">
</div>
<div id="B1">
</div>
<div id="B2">
</div>
<div id="C1">
</div>
<div id="C1">
</div>
Here's what I do to hide them :-
$(document).ready(function(){
$("#A2").hide();
$("#B1").hide();
$("#B2").hide();
$("#C1").hide();
$("#C2").hide();
});
How would I get the ID of the visible div? I have tried :-
var current_div = $("div:visible");
current_div_id = current_div.attr('id');
Output :- Undefined
var current_div = $("div:visible");
current_div_id = current_div[0].id;
Output :- Blank
What am I getting wrong ?
Fixed it. Posting a solution to help future peeps.
It seems that jquery is unable to find the current div using my above code. What I did is, added a common class to all the divs. Like this :-
<div id="A1" class="divs">
</div>
<div id="A2" class="divs">
</div>
<div id="B1" class="divs">
</div>
<div id="B2" class="divs">
</div>
<div id="C1" class="divs">
</div>
<div id="C1" class="divs">
</div>
And now I modified my JS in this way :-
var current_div = $(".divs:visible");
current_div_id = current_div[0].id;
And it worked. So if you're in the same problem, remember to have a common class for all the divs.
Try this:
var current_div = $("div:visible").attr("id");
$( 'body' ).text( current_div );
http://jsfiddle.net/neowar2x/4/
well, your code is working actually, and I can get id using both methods. You're missing something else here, check console what else do you get.
just one issue, you won't get consistent results as you've duplicate id on your page C1, twice.
<div id="A1">
A1
</div>
<div id="A2">
A2
</div>
<div id="B1">
B1
</div>
<div id="B2">
B2
</div>
<div id="C1">
C1
</div>
<div id="C2">
C2
</div>
<p id = "one"></p>
<p id = "two"></p>
$(document).ready(function(){
$("#A1").hide();
$("#B1").hide();
$("#B2").hide();
$("#C1").hide();
$("#C2").hide();
});
var current_div = $("div:visible");
current_div_id = current_div[0].id;
$("#one").text("ID: "+current_div_id);
var current_div = $("div:visible");
current_div_id = current_div.attr('id');
$("#two").text("ID using second method: "+current_div_id);
Fiddle
I'm stuck again! So hopefully you awesome people can help me...
So far what I have is a search function that queries the database, and returns results, which works fine, and then the user can click one of the results, which takes them through to a new detailed page of what they clicked, for example a brand. Then on the detailed page, it returns all of that brands details (using $_GET['id']) and a new set of data, from a relational table, with a list of all the offers corresponding to that brand, which also works. But then I get stuck, I want the user to be able to click on each offer, and have the details of that offer load into a modal... I've tried using the $_GET['id'] for the offers id, but obviously, with it being on the same page (i presume), it passes the id of the brand / parent instead of the offer.
This is the code that calls back all the offers relating to the brand
$offers_sql = 'SELECT * FROM codes WHERE client_id LIKE :client_id AND CURDATE() between start AND expiry';
$offersq = $db->prepare($offers_sql);
$offers_params = array(':client_id' => $id);
$offersq->execute($offers_params);
$results = $offersq->fetchAll(PDO::FETCH_ASSOC);
if(count($results) < 1) {
$output = "<h4>no current offers available</h4>";
}
else {
foreach($results as $r) {
$title = $r['title'];
$code = $r['textcode'];
$offer_id = $r['id'];
$expiry = $r['expiry'];
$date = new DateTime($expiry);
$output .= '<h4>' . $title . '</h4><hr>';
}
}
} catch (PDOException $e) {
echo "failed to load offers";
}
?>
and this is the code i was using for the modal
require('inc/connect/config.php');
include('inc/result.php');
$page_title = "Title - " . $name . " Offers";
include('inc/style.php');
include('inc/header.php');
include('inc/offers.php');
?>
<!-- Intro Section -->
<section class="intro-section">
<div class="container">
<div class="row">
<div class="col-lg-12">
<h3 class="navbar-fixed-top">Latest Deals</h3>
<h1><?php echo $name; ?></h1>
</div>
</div>
</div>
</section>
<section class="offer-section">
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-6 col-sm-offset-3 col-md-6 col-md-offset-3 col-lg-6 col-lg-offset-3">
<?php echo $output; ?>
</div>
</div>
</div>
</section>
<div class="md-modal md-effect-flip" id="offer">
<div class="md-content">
<h4><?php $offer = (int) $_GET['id'];
echo $offer ?></h4>
<button type="submit" class="modal-btn md-close navbar-fixed-bottom" value="submit"><p>close</p></button>
</div>
</div>
<?php include('inc/footer.php'); ?>
The code that returns the details of the brand is on a separate page, but i can include that if necessary.
What am i doing wrong? Please go easy on me, I am relatively new to php.
Thanks in advance
Kaylee
Make Changes, Where Output is declared in else condition. (Changes Done)
$output='<h4><a class="OfferIdClass" data-OfferID="<?echo $offer_id;?>" href="#offer" data-modal="offer" data-toggle="modal">'.$title.'</a></h4>';
// Add This to footer.php (Changes Done)
<div class="md-modal md-effect-flip" id="offer">
<div class="md-content">
</div>
</div>
//Add this below in that page, where you are clicking Modal.
//Changes Done
<script>
$('.OfferIdClass').click(function(){
var OfferID=$(this).attr('data-OfferID');
$.ajax({url:"Open-Offer.php?OfferID="+OfferID,cache:false,success:function(result){
$(".md-content").html(result); //Here, Changes Done
}});
});
</script>
//Create one Open-Offer.php page. (Changes Done)
Open-Offer.php
<?
extract($_GET);
<h4><?php $offer = (int) $_GET['id'];
echo $offer ?></h4>
<button type="submit" class="modal-btn md-close navbar-fixed-bottom" value="submit"><p>close</p></button>
?>
In the following page, begins an element that enables user to crop and save an image. It only works for the first item in the loop however, for all the sql rows that follow, clicking the image doesn't open up the modal-dialog box.
I don't have any overlapping tags, I've checked thoroughly. I've moved around the js script tags and don't get any change either. Is there a common cause for this? where would be the first place to troubleshoot? Would using a different type of loop in PHP be preferable?
<?php
ob_start();
session_start();
require_once ('verify.php');
?>
<head>
<title>Edit Listings</title>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<link href="../css/cropper.min.css" rel="stylesheet">
<link href="../css/crop-avatar.css" rel="stylesheet">
</head>
<body>
<div id="container">
<div id="head">
<ul id="menu">
</ul>
</div>
<div id="area"></div>
<div id="main_listings">
<h1 align="left">Edit listings page</h1>
<?php
include ("../dbcon2.php");
$conn = new mysqli($servername, $username, $password, $dbname);
$sql="SELECT * FROM listings ORDER BY date_added DESC";
$result = $conn->query($sql);
?>
<?php while ($data=mysqli_fetch_assoc($result)):
$id = $data['id'];
$id = $data['title'];
$listing_img = $data['listing_img'];
?>
<div id="edit_listing">
<div id="edit_left">
<div class="container" id="crop-avatar">
<div class="avatar-view" title="Change the avatar"> <img src="<?php echo $listing_img; ?>" alt="<?php echo $title; ?>"> </div>
<div class="modal fade" id="avatar-modal" tabindex="-1" role="dialog" aria-labelledby="avatar-modal-label" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<form class="avatar-form" method="post" action="edit-avatar.php" enctype="multipart/form-data">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title" id="avatar-modal-label">Listing Main Image</h4>
</div>
<div class="modal-body">
<div class="avatar-body">
<div class="avatar-upload">
<input class="avatar-src" name="avatar_src" type="hidden">
<input class="avatar-data" name="avatar_data" type="hidden">
<input name="avatar_id" type="hidden" value="<?php echo $id; ?>">
<label for="avatarInput">Local upload</label>
<input class="avatar-input" id="avatarInput" name="avatar_file" type="file">
</div>
<div class="row">
<div class="col-md-9">
<div class="avatar-wrapper"></div>
</div>
<div class="col-md-3">
<div class="avatar-preview preview-lg"></div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-default" type="button" data-dismiss="modal">Close</button>
<button class="btn btn-primary avatar-save" type="submit">Save</button>
</div>
</form>
</div>
</div>
</div>
<div class="loading" tabindex="-1" role="img" aria-label="Loading"></div>
</div>
</div>
<div id="edit_right">
<form name="edit_date" action="edit_list.php" method="post" id="edit_list_data">
<input name="title" type="text" id="title" tabindex="1" value="<?php echo $title; ?>" size="60" maxlength="57"/>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="submit" formaction="edit_list.php" value="Submit" />
</form>
</div>
</div>
<?php endwhile;$conn->close();?>
<div class="spacer"></div>
</div>
</div>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="../js/cropper.min.js"></script>
<script src="../js/crop-avatar.js"></script>
</body>
</html><?php // Flush the buffered output.
ob_end_flush();
?>
js js
// Events
EVENT_MOUSE_DOWN = "mousedown touchstart",
EVENT_MOUSE_MOVE = "mousemove touchmove",
EVENT_MOUSE_UP = "mouseup mouseleave touchend touchleave touchcancel",
EVENT_WHEEL = "wheel mousewheel DOMMouseScroll",
EVENT_RESIZE = "resize" + CROPPER_NAMESPACE, // Bind to window with namespace
EVENT_DBLCLICK = "dblclick",
EVENT_BUILD = "build" + CROPPER_NAMESPACE,
EVENT_BUILT = "built" + CROPPER_NAMESPACE,
EVENT_DRAG_START = "dragstart" + CROPPER_NAMESPACE,
EVENT_DRAG_MOVE = "dragmove" + CROPPER_NAMESPACE,
EVENT_DRAG_END = "dragend" + CROPPER_NAMESPACE,
build: function () {
var $this = this.$element,
defaults = this.defaults,
buildEvent,
$cropper;
if (!this.ready) {
return;
}
if (this.built) {
this.unbuild();
}
$this.one(EVENT_BUILD, defaults.build); // Only trigger once
buildEvent = $.Event(EVENT_BUILD);
$this.trigger(buildEvent);
if (buildEvent.isDefaultPrevented()) {
return;
}
// Create cropper elements
this.$cropper = ($cropper = $(Cropper.TEMPLATE));
// Hide the original image
$this.addClass(CLASS_HIDDEN);
// Show and prepend the clone iamge to the cropper
this.$clone.removeClass(CLASS_INVISIBLE).prependTo($cropper);
// Save original image for rotation
if (!this.rotated) {
this.$original = this.$clone.clone();
// Append the image to document to avoid "NS_ERROR_NOT_AVAILABLE" error on Firefox when call the "drawImage" method.
this.$original.addClass(CLASS_INVISIBLE).prependTo(this.$cropper);
this.originalImage = $.extend({}, this.image);
}
this.$container = $this.parent();
this.$container.append($cropper);
this.$canvas = $cropper.find(".cropper-canvas");
this.$dragger = $cropper.find(".cropper-dragger");
this.$viewer = $cropper.find(".cropper-viewer");
defaults.autoCrop ? (this.cropped = TRUE) : this.$dragger.addClass(CLASS_HIDDEN);
defaults.dragCrop && this.setDragMode("crop");
defaults.modal && this.$canvas.addClass(CLASS_MODAL);
!defaults.dashed && this.$dragger.find(".cropper-dashed").addClass(CLASS_HIDDEN);
!defaults.movable && this.$dragger.find(".cropper-face").data(STRING_DIRECTIVE, "move");
!defaults.resizable && this.$dragger.find(".cropper-line, .cropper-point").addClass(CLASS_HIDDEN);
this.$scope = defaults.multiple ? this.$cropper : $document;
this.addListeners();
this.initPreview();
this.built = TRUE;
this.update();
$this.one(EVENT_BUILT, defaults.built); // Only trigger once
$this.trigger(EVENT_BUILT);
},
The root of your problem is two-fold (and there may be other issues behind this).
First, you have tons of duplicate id values in your HTML.
Here are some of the dups: edit_listing, container, edit_left, crop-avatar, avatar-modal, etc...
A given ID can only be used once in the entire HTML document. All of these id values need to be changed to class names (which can be used as many times as you want) and then any code or CSS that references them needs to be changed to refer to the class name, not the ID value.
This comes into play in your code when you do:
new CropAvatar($("#crop-avatar"));
Because this is an id reference, it will only select the first element in your page with that id. Thus, only the first listing is active. If you change the HTML to be:
<div class="container crop-avatar">
then, you can select all of them with a class selector .crop-avatar.
Second, your CropAvatar() constructor is only ever called once, but it's written as if it is only going to be operating on a single avatar. So, either you need to call CropAvatar() separately for each listing OR you need to rewrite CropAvatar() and it's event handlers to work for all the listings instead of just one.
You could probably make the existing CropAvatar() constructor work if you fix all the duplicate ID values and then change this:
var example = new CropAvatar($("#crop-avatar"));
to this:
$(".crop-avatar").each(function() {
new CropAvatar($(this));
});
This will call the CropAvatar() constructor for each listing.
These are the first two main issues I see. I cannot promise that there are not other things to fix also, but those issues can't be seen until these first two are fixed.
I have the following code in .php (code is edited for easier understanding).
while($row = mysql_fetch_array($biznis)){
<div id='listItem'>
<div id='listPic'>
<img src='../../social/images/avatar/empty_avatar_full.jpg'></img>
</div>
<div id='listCont'>
<span>abcde<i>(request pending)</i></span>
</div>
<div id="listInfo">
<span id='info'>More info</span>
</div>
<div style='clear:both;'></div>
<div id='moreInfo'>
<span>Invitation sent: xx-yy-zzzz</span>
</div>
</div>
<div style='clear:both;'></div>
}
So the code is nothing special, I just get all records from the table lined up.
So now, here is the problem, as you can see, I use the same ids for the same elements.
Jquery code
$(document).ready(function () {
$("#moreInfo").hide();
$("#info").click(function(){
$("#moreInfo").slideToggle();
});
});
OK so here are now the problems. Only first div (#moreinfo) is hidden, all the others are shown. And only first span (#info) is toggling the slider.
I tried with putting the counter for ids, and jquery each function, but nothing realy worked as i imagined.
Ty, Sebastian
Element IDs should be unique identifiers for that element. Use classnames for generic selectors:
<? while($row = mysql_fetch_array($biznis)): ?>
<div class="listItem">
<div class="listPic">
<img src="../../social/images/avatar/empty_avatar_full.jpg"></img>
</div>
<div class="listCont">
<span>abcde<i>(request pending)</i></span>
</div>
<div class="listInfo">
<span class="info">More info</span>
</div>
<div style="clear:both;"></div>
<div class="moreInfo">
<span>Invitation sent: xx-yy-zzzz</span>
</div>
</div>
<div style="clear:both;"></div>
<? endwhile; ?>
And change your jQuery to:
$(function() {
$('.moreInfo').hide();
$('.info').click(function() {
$('.moreInfo').slideToggle();
});
});
Edit
$('.info').click(function() {
$(this).parent().siblings('.moreInfo').slideToggle();
});
use class and not ids because you're in a while loop. An id exists only once.
And update your JS.
I have a single page website, I have the insert working correctly, but I cannot seem to update the #results div after submit. The values are being inserted into the database just fine and if I hard refresh they are appearing. But not with the jQuery AJAX refresh. I am new to Ajax, so any help would be really appreciated, and any comments on code structure or bad habits, please comment as I am trying to learn the proper way to program.
Here is my code:
$(document).ready(function(){
$("form#addTodo").submit(function(){
alert('hello world'); // ensure function is running
var post_title = $('input#post_title').val(); // take values from inputs
var post_content = $('input#post_content').val();
$.ajax({
type: "POST",
url: "add.php",
data: "post_title=" + post_title + "&post_content=" + post_content,
success: function() {
// alert('success'); // ensure success
$('#results').fadeOut('slow').load('include/results.php').fadeIn('slow');
}
});
$('input#post_title').val(''); // clear form fields
$('input#post_content').val('');
return false;
});
});
Here is the results.php file:
<?php
$sql = $db->query('SELECT id, post_title, post_content FROM posts ORDER BY post_title ASC');
$results = $sql->fetchALL(PDO::FETCH_OBJ);
$count_posts = count($results);
?>
<?php if ( have_posts() == true) : ?>
<div class="accordion" id="accordion_main">
<?php foreach($results as $entry): ?>
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion_main" href="#collapse-<?php echo $entry->id; ?>">
<?php echo $entry->post_title; ?>
</a>
</div>
<div id="collapse-<?php echo $entry->id; ?>" class="accordion-body collapse">
<div class="accordion-inner">
<p class="target"><?php echo $entry->post_content; ?></p>
<p>Edit Delete</p>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
<?php else: ?>
<h3>There are no posts to display at this time.</h3>
<?php endif; ?>
This works fine when it is included by the index.php, I just can't get it to refresh after posting the data to the DB.
<?php
require_once 'includes/db.php';
require_once 'includes/functions.php';
?>
<?php get_header(); ?>
<div id="results">
<?php include_once 'includes/results.php'; ?>
</div>
<hr />
<p>Add New Post</p>
<form id="addTodo" action="">
<div>
<label for="post_title">Post Title</label>
<input id="post_title" name="post_title">
</div>
<div>
<label for="post_content">Post Content</label>
<input id="post_content" name="post_content">
</div>
<div>
<button id="submit" type="submit">
Save
</button>
</div>
</form>
<?php get_footer(); ?>
I should mention that I haven't put in form validation yet. Any help is greatly appreciated, thanks.
Why not just return the data from success? and use that to make your html input
success:function(returnedData) {
if (returnedData.status = 'successful') {
//use javascript to append the data for example like
//returnedData.message to make html and insert into your current html
}
}
Note: returnedData has to be pushed out by your php in an json format.
you can find a similar answer to your request if you read this thread that I had recently answered : Jquery Mobile Post to PHP (same page)
But you must make some adaptation for you context ;-) !!
I think that is the unique solution if you're using unique file script
To insert data returned from php file just use $("element id or class").html() function to insert the data or html to specific area of your document