JS not working on echoed PHP - 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
}
// ......
});

Related

Jquery Mobile: Show new data without refresh after adding it to DB

I'm displaying data from DB like this:
<?php foreach ($r as $k => $v):?>
<div data-role="collapsible" data-mini="true" class="collapsible">
Name: <?=$v['name']?>
</div>
<?php endforeach; ?>
Now when I add new data to DB and the form is submitted, my script redirects back to this page. How do I show the new data immediately without manually refreshing the browser? I usually don't have this issue if I'm not using Jquery Mobile.
You could send the form with jquery ajax
$('form[name="myform"]').submit(function(evt){
evt.preventDefault();
$.post('/my_form_handler.php', $(this).serialize())
.done(function(data){
//Populate dom elements here with new data
}).fail(function(data){
//Handle failed ajax post.
});
});
And then on successful post change the content of the dom-elements.
Not 100% sure i got the right syntax for it but i think it should give you a general idea on how to do it.
The problem here is that the data is hard coded into the page's HTML. After your form submission it's jQueryMobile that's changing the page/view, and no refresh of the page takes place so you're still seeing the same data.
You should refactor to create the loop with JSON data (loaded via AJAX). If the data is cached in a local variable, you can either add to it with the form's data, or make a fresh AJAX call to the server (recommended if you need sorting or filtering).
After reloading the data, the rendering code can be called, showing the new list.
it is easy.
you can send the request to the server using ajax.
and on the server side, you have to make the function to return the data added.
the ajax function will get the success or fail function.
the success function will run if it works.
on the success function , you have to add the content using javascript jquery with the returned data.
Thanks

Validating forms returned by ajax

If i have a page which has an ajax link and that the code returns a that form needs validating, where do i put the validation code please. Say my form had this validation using the jquery validation plugin
jQuery(document).ready(function() {
$("#basicForm").validate({
showErrors: function(errorMap, errorList) {
// Clean up any tooltips for valid elements
$.each(this.validElements(), function(index, element) {
var $element = $(element);
$element.data("title", "") // Clear the title - there is no error associated anymore
.removeClass("error")
.tooltip("destroy");
});
// Create new tooltips for invalid elements
$.each(errorList, function(index, error) {
var $element = $(error.element);
$element.tooltip("destroy") // Destroy any pre-existing tooltip so we can repopulate with new tooltip content
.data("title", error.message)
.addClass("error")
.tooltip(); // Create a new tooltip based on the error messsage we just set in the title
});
},
submitHandler: function(form) {
var myselect = $('select[name=ddCustomers]');
//alert(myselect.val());
window.location.replace("customer.php?customer_id=" + myselect.val());
}
});
$("#basicForm").removeAttr("novalidate");
});
where do i put it as the document.ready where i would normally out this code has already been called
I hope this makes sense
Could i have it on the page in the initial page load ready for when the form is returned
I've read i coud have the validation in the document.on function but dont really understand. Would i post something like this back with my ajax response for the validation
$(document.body).on('click', '#basicForm', function(){
$("#basicForm").validate({
submitHandler: function() {
// do whatever you need here
}
});
});
Thanks for your help. Its confusing and I cant find a decent example on google
EDIT
I know how to write the validation code for the dynamically generated forms so thanks for those answers but I am alright on that. The question is WHERE that code should i put it in the ajax return?
Perhaps i have a misconception but i am using jquery validate module (base assistance( and i have only ever seen the `form validate method called in doc. ready on the first page - never an ajax postback
document.ready
Options
1) Hard coded in page already writing for when form injected by ajax? not dynamic enough - the injected form is created dynamically so the validation may need to
be
2) Add validation code to
document.on
when i do ajax postback for the new form? Is this even possible? Im not a client side programmer.
I am bemused that such a common scenario doesnt have a design pattern. Though i have read postng back forms via ajax is bad practice as it can confuse the browser and now what ajax whs written for so perhaps that why i cant find a solution
thanks
I've coded and developed many web apps just with jquery, php being the server side script. The way I formed was to have the jquery code and html on the same page since jquery needs to check the html element and respond with the proper error message and sanitize all the data fields before I submit to the "form-process.php" for an example if that was the name of your server side script.
Have:
$(document.body).on('click', '#basicForm', function(){
$("#basicForm").validate({
submitHandler: function() {
// do whatever you need here
}
});
});
code as the same page as say: create-username.html or create-username.php page
html elements. Some prefer to have jquery on the bottom, depends on how you have your
page structured, but I like to put the js on top from old practices although sometimes it doesn't apply to jquery.
include your tooltips code in the same block. I don't like to have jquery all over the place; incase of errors or if you need to modify in future reference it wouldn't be hard to pinpoint to edit, add or fix code. I hope this helps.
You need to initialize the validation plugin first and set up the rules you want. Then when a user submits the form, prevent the default form submission behavior and if all is validated successfully based on the criteria of the rules you set, you manually submit the form to the server using ajax.
$('#basicForm').validate({ // initialize the plugin
rules: {
field1: {
required: true,
email: true
},
field2: {
required: true,
minlength: 5
}
}
});
$('document').on('submit', '#basicForm', function(e){
if($(this).valid()){
//client side is valid, make ajax call
}
e.preventDefault();
});

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

PHP contact form needs to call Javascript to show a hidden div on main .html page

I have a one page website in the works that has a contact form where its contact error and contact thank you messages are placed further down the page as hidden divs.
The contact form calls an external php file that calls the anchor links of the error and thank you message divs in the index.html file.
www.photograsurfer.com/test/index.html
www.photograsurfer.com/test/code/contact-panel.php
Everything works successfully as long as the divs are not hidden. So now I need to use the following javascript to get the hidden divs to display when needed.
<script type="text/javascript">
function showContactPanelError() {
document.getElementById('contact-panel-error').style.display = "block";
}
</script>
My problem, besides being a complete PHP beginner, is that I don't know how to get the PHP file to reference the Javascript code to display the hidden divs properly on the main page.
Any help is appreciated.
Thanks.
Use jQuery forms (http://malsup.com/jquery/form/) to submit your form via AJAX, then show/hide divs depending on values you return from PHP scripts.
you could assign php variable to javascript as
var error="<?php echo $_GET['error']; ?>";
the $error is the data passed along with the url like wwww.example.com/test.php?error=1
Now you could check var error and call your function showContactPanelError().
I ended up going with a mixture of the 2 methods on these pages.
http://trevordavis.net/blog/ajax-forms-with-jquery
https://spruce.it/noise/simple-ajax-contact-form/#contact
Ditched the div idea since the Ajax method allowed me to not reload the page and enter error and thank you messages within the contact form itself. Seemed like an easier approach.
Thanks for all of the suggestions, as I never would have looked at using Ajax otherwise.
You can add a onclick event on submit button. On clicking it will create an ajax call send data to the required external PHP file and then on success will display the hidden division properly on the main page.
here's a sample code just for an explanation
**
* Description : Function that will trigger the AJAX request.
* #param none
*/
function CategorySubscriber_Unsubscribe(){
var data = {
'data-1': data-1,
'data-2': data-2,
// as per your need you can put any number of data
};
var url = // your url
jQuery.post(url, data, function(response){
jQuery.show("#your-div-id");
});
}
function(response) will be executed when ajax call will be in success status.
You can learn it from these links
http://www.w3schools.com/jquery/ajax_post.asp
http://api.jquery.com/jQuery.post/

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