JQuery: Select an id generated by PHP - php

I generate through PHP an HTML input (id="newItem") and a HTML paragraph (id="newDesc") in the already existing HTML table (id=detailedTable). After trying to fire off a function by using $("#newItem").change(function()..., I found out that since it was generated dynamically I had to refer to it using the Jquery .on(). Now this part works.
My issue is on the return of the Ajax call, I try to change the #newDesc value, but it is not working. I suspect for the same reason that this ID was dynamically generated.
$("#detailedTable").on('change','#newItem',function(){
var value=$(this).val();
value=value.replace(/\,/,'.');
value="value="+value;
$.ajax({
url:'z-getDesc.php',
type:'POST',
dataType:'json',
data:(value),
success:function(values){
values=values['descriptionA'];
$("#newDesc").val(values);
},
fail: function(xhr, textStatus, errorThrown){
alert('Please try again later');
}
});
});
Up to that point everything works fine, the 'values' variable is returned, all is left is :
How can I refer to #newDesc id?
Thanks
Edit: To clear some things up:
1- The DOM is initially loaded, and users interact with it, bringing in some changes resulting in an array of data.
2- This arrays is loaded up in a table created via JQuery Datatables by an ajax call; in addition to populating the table with the array, I also generate a line for inline editing, line which contains the afore-mentioned #newItem and #newDesc.

You need to call $("#detailedTable").on after you generate the content. Javascript is executed when the page is loaded, so when the javascript executes, it can't find the chosen id and doesn't try again. Add some javascript to whatever user interaction that generates the content that calls .on and it should work.

Related

AJAX/PHP – callback after finished loading data

(Not sure if I missed an already similar answered question…)
On click of a button, I'm loading various images from a database via PHP/MySQL and appending it to the body (the actual images are of course not stored in the database, the correct selection of the images is based on a posted variable).
My goal is to display a loading indicator after pressing the button and hiding the indicator after all the image data has completely loaded and displayed. This may be an easy to solve callback issue but I'm just getting started with AJAX. :)
The following is the code I currently managed to come up with. I'm guessing the load() function is not really the right one here?
Thanks for your help!
$("#somebutton").click(function(){
alert("fetching…");
$.post('loadmore.php', {
somevariable: somevariable
},
function(data){
$("body").append(data);
$(window).load(function(){
alert("finished loading…");
});
});
});
The function you have with the finished loading... alert is a success callback, so it gets executed once the AJAX call has finished. This means you don't need to use $(window).load.
Also, you can use the html method on an element to change its contents and display a message.
Something like this would work fine:
$("#somebutton").click(function(){
$('#divID').html('Loading...');
$.post('loadmore.php', {
somevariable: somevariable
},
function(data){
$("body").append(data);
$('#divID').html('');
});
});
Read the docs http://api.jquery.com/jQuery.ajax/
Use the success callback to append the body and then the complete and error callbacks to clear things up correctly.
$("#somebutton").click(function(){
alert("fetching…");
$.post('loadmore.php', {
somevariable: somevariable
})
.success(function(data){$("body").append(data)})
.error(function(){alert("oh dear")})
.complete(function(){alert("finished loading…")});
});
Remember to always have a fallback for removing the loader - nothing worse than just having a loader and no way to remove it from the page and continue using the application / web site.
I managed to solve my problem by reading and tweaking the code in the following article.
The function load() with the equation containing the self-explanatory variables [imagesLoaded >= imageCount] did the trick.
Know when images are done loading in AJAX response

Updating the dynamic PHP in a jQuery Mobile site after updating the database

Let's say I have 2 pages in a jQuery Mobile website.
Page1 - shows data from a database using inline PHP.
Page2 - inserts new data into the database.
The problem is that page1 is not updated when going back, after page2 adds something to the database. I can get it updated by pressing F5, but how can I achieve the same update using jQuery?
I think you're showing data in Page 1 using the pageinit event. This will fire only once and won't update your data every time you add new data.
You need to use pagebeforeshow event of Page 1 to get data from database. This way, new data will be brought every time, which is what you need. Here's a syntax :
$(document).on("pagebeforeshow", "#page1", function() {
//call to server
});
If you're not using pageinit, you must be using document.ready event to get data. Well, thats the way thats done. You must not use ready with jquery mobile. DOM ready will initialize the whole document which will make the ajax page change feature of jQM pointless & useless.
It was late last night and I missed that I should just get my inline php content using Ajax.
So this is how I solved it:
Moved everything contain dynamic content using PHP in a separate file.
Add an Ajax call to the bottom of the page that loads the PHP file as follows:
$(document).on('pagebeforeshow', function(){
$.ajax({
type: "GET",
url: "includes/db/ajax_show_php_content.php",
success: function(html) {
$("#page1").html(html); //Insert PHP content
$("#page1").trigger('create'); //Apply jQuery Mobile style to it.
});
});
Thanks to #hungerpain and #anglinb for their help in figuring this out.
I'm not extremely familiar with jQuery Moblie but here's what I found:
function refreshPage()
{
jQuery.mobile.changePage(window.location.href, {
allowSamePageTransition: true,
transition: 'none',
reloadPage: true
});
}
I think the reloadPage to true should do the trick.
If that doesn't work, check out this answer: jQuery Mobile Page refresh mechanism
Hope this helps!

onclick -> mysql query -> javascript; same page

I need button to begin a mysql query to then insert the results into a javacript code block which is to be displayed on the same page that the button is on. mysql queries come from the values of drop-down menus.
Homepage.php contains
two drop down menus
div id='one' to hold the results javscript code block
a button to stimulate the mysql query to be displayed in div id ='one' through Javascript
flow of the process is as such
1. user chooses an option from each drop down
2. when ready, the user clicks a button
3. the onclick runs a mysql query with selections from the drop down menu.
4. send the results as array from the mysql query into the javascript code block
5. display the results in div id ='one'
all of this needs to happen on the same page!
The problem I am having is that as soon as the page is loaded, the javascipt is static. I am unable to push the mysql results into the javascript on the page which I need it to appear on. Having everything on the same page is causing trouble.
I'm not looking for the exact code laid out for me, just a correct flow of the process that should be used to accomplish this. Thank you in advance!
I've tried
using both dropdowns to call the same javascript function which used httprequest. The function was directed towards a php page which did the mysql processing. The results were then return back through the httprequest to the homepage.
I've tried to save the entire Javascript code block as a php variable with the mysql results already in it, then returning the variable into the home page through HTTPRequest, thinking I could create dynamic javascript code this way. Nothing has worked
You need to use a technology called AJAX. I'd recommend jQuery's .ajax() method. Trying to do raw XHR is painful at best.
Here is how you'll want to structure your code:
Load the page.
User chooses an option.
An onChange listener fires off an AJAX request
The server receives and processes the request
The server sends back a JSON array of options for the dependent select
The client side AJAX sender gets the response back
The client updates the select to have the values from the JSON array.
Basically, HTTP is stateless, so once the page is loaded, it's done. You'll have to make successive requests to the server for dynamic data.
Use AJAX,
example
$.ajax({
type: "POST",
url: "yourpage.php",
data: "{}",
success: function(result) {
if(result == "true") {
// do stuff you need like populate your div
$("#one").html(result);
} else {
alert("error");
}
}
});
For this purpose you need to learn ajax.This is used to make a request without reloading the page.so that you can make a background call to mysql
your code will be something like that
$("#submitbutton").live("click",function(){
$.ajax({url:"yourfile"},data:{$(this).data}).done(function(data){
//this data will in json form so decode this and use this in div 2
var x =$.parseJSON(data);
$("#div2").html(x.val());
})
})
and "yourfile" is the main file which connect to server and make a database request
here is how I used an onchange method to stimulate a MYSQL query and have the Highchart display the result. The major problem was that the returned JSON array was a string that needed to be converted into an INT. The resultArray variable is then used in the data: portion of the highChart.
$(function(){
$("#awayTeam").change(function(){
$.ajax({
type: "POST",
data: "away=" + $("#awayRunner").val(),
dataType: "json",
url: "/getCharts.php",
success: function(response){
var arrayLength = response.length;
var resultArray = [];
var i = 0;
while(i<arrayLength){
resultArray[i] = parseInt(response[i]);
i++;
}
In the PHP code, the array must be returned as JSON like this
echo json_encode($awayRunner);

JS not working on echoed PHP

So I have a form that is submitted via an Ajax POST request. After the send button is clicked, the form is removed and a processing graphic is put in its place. The form data is sent to my PHP script, validated, and a thank you message returns to replace the processing graphic if everything checks out. But if there is a validation error, I have a copy of the entire form echoed back to the div where the original form was at showing where the errors are in the form. This all works fine except when the copy of the form is echoed back, the JS for the form doesn't work? Neither the JS for the send button or for my focus/blur functions on the inputs. Thank you for any help.
When you remove the form from the DOM, the events are cancelled as well. You can have a function that sets these events and call it when there are errors in the response.
Did you try to just hide your form and display the processing graphic instead of removing the form ? And when you have an error, hide the graphic and display the form again.
With this solution, error handling will be a little more difficult, but you will not have your form at 2 places in your project !
When you insert HTML mixed Javascript into some node, eg a div, it isn't the same as serving it the first time as part of the whole document. It isn't considered a script when inserted as innerHTML or some textnode.
You have a few options:
** Switch visibility and encode the errorresponse (in JSON for example)
Create 2 divs, one holding the form, the other the PROCESSING image.
Switch display to none for the form when processing, and the image to block.
When you have processed the form and you have an error, encode it somehow (JSON, eg) and send that back, and let an EXISTING script on the page interpret the response.
You can for example create some structure that holds each formelementname, and the error associated with it, so you can easily highlight them in your form if you create an empty span next to each formelement where you can display the error.
When the answer arrives from the server, you can display the form again, and display:none the PROCESSING div.
** Interpret your response (WITH JAVASCRIPT)
This is more difficult, but also more elegant.
I once needed this (Javascript that returned from an XHR request), and Randy Webb helped me out with a smart approach.
It is too much to explain here.
Read this thread for a more detailed approach, and links to the script of Randy:
http://tinyurl.com/6pakdu
$.ajax({
url: 'mypage.html',
success: function(){
alert('success');
**<ADD YOUR CUSTOM CODE AFTER AJAX SUCCESS - JS CODE>**
},
error: function(){
alert('failure');
}
});
You can also ref.
http://docs.jquery.com/Ajax_Events
$.ajax({
beforeSend: function(){
// Handle the beforeSend event
},
complete: function(){
// Handle the complete event
}
// ......
});

Return results from a MySQL database using jQuery/AJAX and insert into a DIV

I am working on a project for reserving classrooms. One way of reserving a room is to select a room, see if the things it has (# of seats, # of computers, etc.) is ample for whatever the person needs it for, and then make a reservation.
I have a page that displays all of the available rooms as links in an HTML table, created dynamically in PHP/MySQL. My goal is when a user clicks on a room name, the AJAX request executes a query and returns the necessary data, and then displays it in a DIV on that same page.
Right now, I'm calling an external PHP file that gets the ID of the room that's clicked and executes the query. I'm still very much a novice at jQuery, and I'm pretty sure the problem is in my jQuery script:
<script type="text/javascript">
$(document).ready(function()
{
$('table.roomNums td a.rm-details').click(function()
{
var id = $(this).attr('id');
$.ajax(
{
type: 'POST',
url: 'roomInfo.php',
data: {
roomID: id
},
dataType: 'json',
cache: false,
success: function(result)
{
$('#room-details').empty();
$('#room-details').append("<ul>\n\t<li>Seats: " + result.numOfSeats + "</li>\n</ul>");
}
});
});
});
</script>
As of now, when I click on one of the room number links, nothing happens. I'm assuming that my problem resides in this script, but I'm not sure where or what. I've been reading into the ajax function in jQuery and I'm pretty sure I understand what's going on, but I'm having no luck at the moment.
You want to troubleshoot the following four things:
The HTTP Request Does the browser even issue an ajax request? If so, does it contain the form parameter you are trying to make it contain?
The HTTP Response Does your php script return the data you are expecting in JSON format so JQuery can automatically parse it for you? Copy and paste the response from the server into a test javascript file and see if it compiles as a valid JSON object in a javascript debugger.
AJAX success function Does your javascript error out? Can you step through each line of execution in a javascript debugger like firebug?
Click Event Handler Does your click handler properly return false so the page does not reload? Does your click event handler function fire at all upon click?
Somewhere in the above four things lies your issue. It looks to me like you just need to return false in your click handler so the page does not reload.

Categories