AJAX call successful, but not replacing div as expected - php

After much Googling, I'm on the cusp of success (I think).
I have a fairly large page, overview.php that contains the following snippets:
<script>
function getSummary(id)
{
$.ajax({
type: "GET",
url: '_table_category.php',
data: "catid=" + id,
success: function(data) {
$('#summary').html(data);
alert('Successfully called');
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
}
</script>
Down the page, I iterate over an array and populate a table. The first column is as follow:
<td> <a onclick="getSummary('<?php echo $expenses[$k]['categoryid']; ?>')"> <?php echo $expenses[$k]['shortdesc']; ?> </a> </td>
And then further down on the page, there is a div that will contain the details:
<div class="box">
<div class="box-header"> <h3 class="box-title"> Details </h3> </div>
<div class="box-body">
<div id="#summary"> Select a category to see the details. </div>
</div>
</div>
No errors upon loading the page, nor by clicking on the 'link'. If I click on the link, it pops up with the 'Successfully called' alert as expected.
Looking in the Network tab of the developer tools in Chrome, it calls the _table_category.php page (with a value for catid), and if I click on the link it lists (for example _table_category.php?catid=35), the HTML in the preview pane is correctly formatted HTML.
If I then paste the HTML inside the div manually, it looks exactly as hoped.
This makes me think I am missing something fairly obvious and I am just not actually replacing the div with the result?

Your div has a bad ID.
<div id="#summary">
It should just be:
<div id="summary">
The # is just there in the selector (it's used to specify "select by ID").

Related

How can I send the value of the id through ajax and PHP

I want to pass value of the id of the product to cart.php by using AJAX and display it in a div.cart in index.php but I have no idea how. please help.
Product
Product Description
Add to Cart
$('a').on('click', function(e){
$.ajax({
url:
data:
})
e.preventDefault();
});
Of course you can :) !
So first, let's get things straight. You're showing a list of products as <div class="thumbnail"> form, right ? So your PHP/HTML should look a bit like this in reality :
<?php
foreach($database_recordset as $row) {
echo '
<div class="thumbnail>
<img src="'.$row['img_src'].'" alt="'.$row['img_alt'].'" />
<div class="caption">
<h4>'.$row['product_name'].'</h4>
<p>'.$row['product_description'].'</p>
<a id="p-'.$row['id'].'" onclick="addCart(this)">Add to Cart</a>
</div> <!-- You were missing a /div here if I guessed right the structure -->
</div>';
}
?>
so I simply labelled the link p-#ID where #ID is the id of the product from the database and added an onclick event with this as the argument. Now you need a function addCart that will contain the AJAX request.
<script type="text/javacscript">
function addCart(elm) {
// First we need the clean ID of the product
var id = elm.id.split('-')[1]; // We split with '-' as separator and take the second element of the resulting array
$.ajax({
url: "cart.php",
type: "POST", // or GET whatever but POST is usually better
data: { id: id },
success: function(response) {
if (response.status == 'OK') { // You should always test the response of an ajax request
// show a message, update the cart icon or whatever
}
}
});
}
</script>
you need to modify you code something like this. Href need to be removed else it will redirect you on that page. Give below is a sample of your code
<div class="thumbnail>
<img src="" alt="" />
<div class="caption">
<h4>Product</h4>
<p>Product Description</p>
<a id="id=(id from table products)">Add to Cart</a>
</div>
$('a').on('click', function(e){
$.ajax({
url: cart.php
data:{id:$(this).attr("id")}
})
e.preventDefault();
});
You need to stop the browser following the link, then make an ajax request and insert the response into the target div.
You can use jquerys load method to acheive that in a single call:
$('a.clickme').click(function(ev){
ev.preventDefault();
$('div.cart').load($(this).attr('href'));
});
Note i added a class to the link, else your code would capture all link clicks including site navigation etc
Add to Cart

Load contents of page depending on linked selected

I am writing an admin dashboard in PHP at the moment.
To simplify things, as far as I think it simplifies, the page I structured has the typical areas Header, Aside with menu and MainContent page. The main content page should change when I click a different page in the aside menu.
So I created the page index.php which will hold the whole framework of the page.
<?php include('../includes/overall/overallHeader.php'); ?>
<section class="content-header">
<h1>Einsatzliste</h1>
</section>
<script type="text/javascript">
$('#pageIncidents').click(function(){
$('#mainContent').load('incidents.php');
});
</script>
<section class="content">
<div id="mainContent">
</div>
</section>
<?php include('../includes/overall/overallFooter.php'); ?>
Within this I created the section content, and gave the div inside the id mainContent. My idea was to load different subpages into this div, when I click a menu item in the aside menu:
aside menu
<div class="navbar-default sidebar" role="navigation">
<div class="sidebar-nav navbar-collapse">
<ul class="nav in" id="side-menu">
<li><div id="pageIncidents">Einsatzliste</div></li>
<li>Testseite 1</li>
</ul>
</div>
</div>
There I put the link inside a div with a unique ID which I want to use in jQuery to load the specific contents.
jQuery script
<script type="text/javascript">
$('#pageIncidents').click(function(){
$('#mainContent').load('incidents.php');
});
</script>
The script is supposed to load the page incidents.php into the div mainContent in the index.php page.
It totally does not work... Do you have a hint where to look for? I think the logic seems right I guess. Could it be a problem, that the id "pageIncidents" is not directly visible in the code but included by the php include overallHeader at the top of the page?
You can try doing it with ajax and make up the ajax response in html (string), onclick start ajax request.
$(document).on("click", ".delete-asset", function() {
var link = $(this).attr('[data-page]');
$.ajax({
type:'GET',
url:'http://www.example.com/index.php',
dataType: "json",
data: {
action: 'incidents',
data: { 'incidents': 'incidents' }
},
success:function(data) {
$('#mainContent').html("[your data]");
}
});
});

Use jquery mouseover to show status from callback

Is it possible to use jquery to use a callback in a div and show the full text in another div? Currently I have in the right div:
$(document).ready(function(){
setInterval(function(){
$.post("status.php?_="+ $.now(), {day : "<?php echo $day;?>"}, function(upcoming){
$(".ticker").html(upcoming);
}),
"html"
}, 45000);
});
And I need something like:
$(".view").hover(function(){
$("#left").load("a.php");
});
<div id="left">
<div class="show">
</div>
</div>
<div id="right">
<div class="ticker">
</div>
</div>
My php spits back html: EventID
What I want to do is hover over the hyper link and have the full status shown in .show
I know I'll have to do a query with the event number, but my search in doing this comes up empty. As always, any help is appreciated
$("body").on("hover", ".view", function(){
$("#left").load("a.php");
});
As you're adding .view to DOM after page load i.e dynamically so, you need delegate event handler for dynamic element using .on().
And instead of body you can use any parent selector of .view which is static-element.

Jquery AJAX custom form not returning results from PHP

I don't like the look of normal dropdown selectors in forms, so I've decided to create my own version of them with some Jquery as a little learning project for myself.
The objective of the following code is to be able to submit the text inside the various "select" boxes, i.e. #cuisineSelect, #locationSelect and #priceSelect to "ajax.php" so that I can manipulate those variables further.
My problem is that for some strange reason ajax.php will not register the $_POST variable and it's telling me that I've got an "undefined index".
I did some debugging in IE9 with some developer tools and they show (at least I think so) that the variables are getting sent through to ajax.php, and ajax.php is returning a variable. Here are the screenshots.
On the real project, the user can click on the <li> options item and the text will transfer onto the selector - just like a dropdown selector.
Here is my code:
The HTML:
<div id="parentContainer" style="width:100%;">
<div class="container">
<div class="select" id="cuisineSelect">
Cuisine
</div>
<div class="option" id="cuisineOption">
<ul id="cuisineul">
<li>Asian</li>
<li>American</li>
<li>Indian</li>
<li>Fusion</li>
</ul>
</div>
</div>
<div class="container">
<div class="select" id="locationSelect">
Location
</div>
<div class="option" id="locationOption">
<ul id="locationul">
<li>Asian</li>
<li>American</li>
<li>Indian</li>
<li>Fusion</li>
</ul>
</div>
</div>
<div class="container">
<div class="select" id="priceSelect">
Price
</div>
<div class="option" id="priceOption">
<ul id="priceul">
<li>Price Range</li>
<li>Cheap ($5-$15)</li>
<li>Medium ($16 - $20)</li>
<li>Pricey ($21 - $35)</li>
<li>Fine Dining ($35+)</li>
</ul>
</div>
</div>
<div class="container">
<div class="select" id="searchButton" style="width:25px; height:20px;">
<center><img align="center" src="images/sml_search.png" width="17" height="18" /></center>
</div>
</div>
</div>
<div id="result" style="z-index:10;">
result=show;
<?php include "ajax.php"; ?>
</div>
The Jquery code (this has already been placed inside a $(document).ready function.)
$("#searchButton").click(function() {
/*var cuisine = $("#cuisineSelect").html();
var location = $("#locationSelect").attr('value');
var price = $("#priceSelect").attr('value');
$.ajax({
type: "POST",
url: "ajax.php",
data: "cuisine="+ cuisine +"& location="+ location +"& price="+ price,
success: function(){
$('#result').show();
}
});
return false; */
$.post('ajax.php', 'cuisine=' + $("#cuisineSelect").text(), function () {
$("#result").show();
});
});
The PHP page "ajax.php"
<?php
//Search information
//$cuisine = htmlspecialchars(trim($_GET['cuisine']));
//$location = htmlspecialchars(trim($_POST['location']));
//$price = htmlspecialchars(trim($_POST['price']));
//echo $location;
//echo $price;
//$addClient = "INSERT INTO clients (fname,lname) VALUES ('$fname','$lname')";
//mysql_query($addClient) or die(mysql_error());
//$value = $_POST['cuisine'];
//$value2 = $_POST['val'];
//echo "$value2";
$cuisine = $_POST['cuisine'];
echo $cuisine;
?>
Thanks very much for your help.
There is no need to write include the ajax.php file in #result div. Keep #result div empty and hidden.
Modify your ajax call as below:
$.post('ajax.php', 'cuisine=' + $("#cuisineSelect").html(), function (data) {
$("#result").html(data);
$("#result").show();
});
This will show the clicked text in #result 'div'. variable data is passed to callback function for further utilization.
To convert the < li > to a select box, you have to pass the values present in the div #cuisineOption to ajax.php so your PHP script can create the select box from these values.

Dynamic Listview to Details page (Jquery Mobile)

i have succeeded in listing my data from mysql database
in JQM.
i want to link the list item to its details.
Therefore when there is a click on a list, a new page with the data from the list is displayed.
I dont know how to do it
Heres what i have now : but the link i have isnt working, guess i am missing something.
heres the link on js fiddle http://jsfiddle.net/8WU39/16/
<script type= text/javascript>
$('#seyzListPage').live('pageshow', function(){
$.ajax({
url: "data.php",
dataType: 'json',
success: function(json_results){
listItems = $('#seyzList').find('ul');
$.each(json_results.rows, function(key) {
html = '<li <h3><a href="index1.html?id=' + [json_results.rows[key].airp_id] +'"rel="external">'+json_results.rows[key].airport_code+'</h3>';
html += '<p><br> Aiport name: '+json_results.rows[key].airport_name+'</p></a></li>';
listItems.append(html);
});
// Need to refresh list after AJAX call
$('#seyzList ul').listview('refresh');
$.mobile.pageLoading(true);
}
});
});
</script>
<div data-role="page" id="seyzListPage">
<div data-role="header" id="header">
<h1>Airports</h1>
</div>
<div data-role="content" id="seyzList">
<ul data-role="listview" data-inset="true" data-filter="true"></ul>
</div>
<div data-role="footer" data-postion="fixed">
<h3>Footer</h3>
</div>
</div>
What do i do to get the list linked to its data on another html page.
I had a very similar problem and found a fix with a simple plugin. It's called jqm.page.params.js and can be found here. Implementation was very easy. Added the plugin file to my root directory and then included it at the bottom of my index.html page.
In your js file, you then just want to place
if ($.mobile.pageData && $.mobile.pageData.color){
var color = $.mobile.pageData.color;
}
at the top of your beforepageshow event to capture the variables tacked on to the link. Replace 'color' with the variables you are looking for.

Categories