Entry level user here. I've seen countless AJAX\PHP examples with data being passed via POST or GET and modified one of their examples. When clicking the button (id="clickMe) I want it to execute advertise.php and nothing more (no variables need to be passed) without refreshing the page and a notification that says success. When I click the button with my current code nothing happens.
<button type="button" id="clickMe">CLICK ME TO RUN PHP</button>
<script type="text/javascript">
$(document).ready(function(){
$('#clickMe').click(function(event){ // capture the event
event.preventDefault(); // handle the event
$.ajax({
url: 'advertise.php',
data: {
'ajax': true
},
success: function(data) {
$('#data').text(data);
}
});
});
});
</script>
Updated, but still isn't executing.
Here is your editted version code:
$(document).ready(function(){
$('#clickMe').click(function(){
$.post("PHP_FILE.php",{ajax: true},function(data, status){
alert(data);
});
});
});
2 things - you need a document ready handler and to prevent the default click action.
$(document).ready(function() {
$('#clickMe').click(function(event){ // capture the event
event.preventDefault(); // handle the event
$.ajax({ // remainder of code...
});
When loading jQuery scripts at the top of the page you need to make sure they do not run until the DOM has loaded, that is what the document ready handler is for. The you capture the click event by including it as an argument for your click's callback function and handle the click with the preventDefault() method.
Since this request is "simple" you may want to consider using one of the shorthand methods, like $.post()
Related
I am showing 3 code-snippets.
Approach 1 and 2 do NOT work
The 3rd code IS WORKING.
********* not working1 start **************
<script>
$(document).ready(function() {
$('#sending').click(function(){
// just 4 testing:
//var txtBoxVal = $('#TextBox1').val();
// alert(txtBoxVal); ==> ok: showing the value I want to send & INSERT into database via PDOinsertpost.php
$.ajax({
type: "POST",
url: "./PDOinsertpost.php",
data: 'postVal1=' + $('#TextBox1').val(),
success: function(msg){
$('#reshow').html(msg);
}
}); // end Ajax Call
// now trigger a reload via the click-function:
window.location.reload();
}); //end event handler .click function
}); //end document.ready
</script>
********* not working1 end **************
now the approach with the variable inside the $.ajax (not working as well):
********* not working2 start **************
<script>
$(document).ready(function() {
$('#sending').click(function(){
var txtBoxVal = $('#TextBox1').val();
// an alert - just 4 testing:
// alert(txtBoxVal); // ok: showing the value I want to send & INSERT into database via PDOinsertpost.php
$.ajax({
type: "POST",
url: "./PDOinsertpost.php",
data: 'postVal1=' + txtBoxVal,
success: function(msg){
$('#reshow').html(msg);
}
}); // end Ajax Call
// now trigger a reload via the click-function:
window.location.reload();
}); //end event handler .click function
}); //end document.ready
</script>
********* not working2 end **************
and now the "hardcoded", working version (?courious for me, that this one is working - but the others do not...)
********* the working1 start **************
<script>
var txtBoxVal = "some hardcoded string for testing";
$(document).ready(function() {
$('#sending').click(function(){
$.ajax({
type: "POST",
url: "./PDOinsertpost.php",
data: 'postVal1=' + txtBoxVal,
success: function(msg){
$('#reshow').html(msg);
}
}); // end Ajax Call
// now trigger a reload via the click-function:
window.location.reload();
}); //end event handler .click function
}); //end document.ready
</script>
********* the working1 end **************
Additional Info.: in the meantime I figured out, that an empty value is working with the two "not-working" code-snippets with $('#id').val(),
this means: a blank value is inserted in the database.
Am I searching at the wrong place?
Do I need to do some htmlentities - stuff or something within the .php file with the PDO-INSERT?
I hope, some useful information can be gathered by this post - for me, as well as for others.
Thanks in advance,
-Flow.
I see 2 big problems here:
You are reloading the page (in all your examples...) while the ajax request has not yet finished. That is a very risky and buggy approach as you cannot be sure that your php script will finish correctly. And if you reload any way, you don't need ajax.
You are not escaping your value so user input can break the query string. The easiest solution for that is to use an object so that jQuery encodes it correctly automatically:
data: { 'postVal1': $('#TextBox1').val() },
I also don't see you cancelling the default form submit, but as the third example works, I assume that the button / #sending element is not a submit button. If not, you would need to take care of that as well.
Edit: As you are using a submit button, you need to prevent the regular form submit:
$('#sending').click(function(event){
// prevent the default form submit
event.preventDefault();
...
without the "window.location.reload();" it seems to work!
#jeroen had probably the right explanation: the reload disturbed the process!
(but it didn't on my virtual home-server ... (may be, because of other processing-times... ))
I have the following code
<html>
<head>
//included all jquery related stuff ..not shown here
</head>
<body>
<button id = 'btn' />
<div id = 'ct'>
<?php echo file_get_contents('my_ajax_stuff.php'); ?>
</div>
</body>
<script>
$('.datepicker').datepicker({dateFormat: "dd-mm-yy"});
$('#btn').click(function() {
$.ajax({
type: "GET",
url: "my_ajax_stuff.php" ,
success: function(response) {
$('#ct').html(response);
/*added following line to solve this issue ..but not worked*/
//$( ".datepicker" ).datepicker({dateFormat: "dd-mm-yy"});
} ,
error: function () {
$('#ct').html("Some problem fetching data.Please try again");
}
});
});
</script>
</html>
The page
my_ajax_stuff.php
contains a jquery ui datepicker with class = 'datepicker'.On the first load the datepicker works.But when I click on the button to reload it again , the contents are replaced with new contents.But the datepicker is not working.I have tried initialising the datepicker inside the ajax success handler ,as you see.But it also failed.What is the issue.How can it be solved???
You need to reinitialize the date picker in Ajax success
$('.datepicker').datepicker({dateFormat: "dd-mm-yy"});
$('#btn').click(function() {
$.ajax({
type: "GET",
url: "my_ajax_stuff.php" ,
success: function(response) {
$('#ct').html(response);
$( "#datepicker" ).datepicker();
/*added following line to solve this issue ..but not worked*/
//$( ".datepicker" ).datepicker({dateFormat: "dd-mm-yy"});
} ,
error: function () {
$('#ct').html("Some problem fetching data.Please try again");
}
});
});
The answer you are looking for may be similar to this question:
jQuery datepicker won't work on a AJAX added html element
You're replacing the datepicker element in the DOM with the ajax response.
The reason this works for the first time is that PHP renders the my_ajax_stuff.php on first load already in the HTML so it becomes available to jQuery in the DOM.
// do this once the DOM's available...
$(function(){
// this line will add an event handler to the selected inputs, both
// current and future, whenever they are clicked...
// this is delegation at work, and you can use any containing element
// you like - I just used the "body" tag for convenience...
$("body").on("click", ".datepicker", function(){
$(this).datepicker();
$(this).datepicker("show");
});
});
I came across this question because I was having the same problem as OP.
Mooed Farooqui's recommendation to reinitialize in Ajax success worked, but not initially.
Ended up that I was also calling the datepicker function in my equivalent of my_ajax_stuff.php. After I took that out it worked perfectly on button reload and postbacks. Hope this helps someone that stumbles upon this old question...
Call your picker inside .ajaxComplete function.
$(document).ready(function () {
// setup picker here...
});
$(document).ajaxComplete(function() {
// setup picker here...
});
Here is a link
This may be a primitive solution, but I found that If I have in my main document a function MakeDatePicker and I used it in the OnChange portion of my input, I was able to make any object, ajax, or otherwise, turn into a date picker before, and after an ajax call.
Here is the function and the call. (please note, I have ColdFusion # functions, as this is a return on a coldfusion query with a CFOutput.)
<td><input type="date" class="EstDeliveryDatePicker" chassis="#chassis#" value= "#DateFormat(EstDelivery,'mm/dd/yy')#" onclick="MakeDatePicker(this);"></input></td>
here is the function at the top of my page:
function MakeDatePicker(obj)
{
$(obj).datepicker({
changeMonth: true,
changeYear: true
});
$(obj).datepicker("show");
}
like I said, its crude, but it works.
I was having an issue with the way my tables would display their sorts. I have it so when you enter the page, you have 1 field that you can click on to select a date. If you click on one of the headers, it would sort SQL command, and re-display the table. This would break the .datepicker function. So I change it to not read off the class, but make the click, trigger the function. the problem with trying to get it to run on the .class was it would initialize after the table was redrawn and lose the scope of the DOM.
I have what I think is a fairly classical problem involving what looks to me like a callback race, but in spite of all my reading, I'm still stuck. You'll find the code pasted below.
It's a simple log in form and you can see that when a certain button is clicked, I'll send the form data "ajaxically" to an external php file. Once the php has run, I'm to receive the results back, and as a test here, to simply alert out the email address from the php file.
When I run this, the ajax callback doesn't execute. If I click the button fast and repeatedly, I get the right alert. I also get the right response if I put in an extra alert.
How do I get it to run without doing these other silly things?
Thanks in advance
RR
$('#'+this.loginForm[0].parentId+"logIn")
.on('click', function() {
var jax = $.ajax(
{
type: "POST",
url: "../sharedfunctions3/act-membership.php",
data: {email: document.getElementById(that.parentId+'email').value,
password: document.getElementById(that.parentId+'password').value,
path: that.path,
action: "logIn"
}
});
jax.done(function()
{
obj = JSON.parse($.trim(jax.responseText));
alert(obj.email);
});
jax.fail(function() { alert("error"); });
alert(1);
});
I had a hunch that when you clicked the button the browser was submitting synchronously and asynchronously.
The return false; tells the browser to not submit the form and to prevent default actions from there on.
When a button inside of a form tag is clicked, most browsers will submit the form even though it is not a submit input.
I have a div set up with a form inside and set to post using ajax and returning the results in the div like so
$(document).ready(function(){
$("#guestList").validate({
debug: false,
submitHandler: function(form) {
// do other stuff for a valid form
//$('form').attr('id', 'guestList1')
$.post('brides_Includes/guestlistDisplay1.php', $("#guestList").serialize(), function(data) {
$('#results').html(data)
$("form#guestList")[0].reset();
});
}
});
});
When the results come back it shows the correct changes and replaces the form. However when I post the form again. The relevent changes take place as they should but it then also refreshes the page and shows the posted info in the address bar
How can I post the form and replace it allowing it to post and call the script again without this happening?
the problem with returning forms using ajax is that any JavaScrip code already on the page will not see/take advantage of the new form. The best way to get around this is to pass the JavaScrip and the HTML back using ajax.
Basically you pass the below code back each time you pass a new form back. You'll need to update the IDs and links (brides_Includes/guestlistDisplay1.php). You will need to replace your code on the main page with this code as well because this is needed to execute any JavaScrip passed back.
<script type="text/javascript">
$(document).ready(function(){
$("#guestList").validate({
debug: false,
submitHandler: function(form) {
// do other stuff for a valid form
//$('form').attr('id', 'guestList1')
$.post('brides_Includes/guestlistDisplay1.php', $("#guestList").serialize(), function(data) {
$('#results').html(data);
//This executes the JavaScript passed back by the ajax.
$("#results").find("script").each(function(i) {
eval($(this).text());
});
$("form#guestList")[0].reset();
});
}
});
});
</script>
I'm trying to add a link to delete a row from a mysql database using jquery and ajax. The data is currently displayed in a table. For some reason, the Click event isn't triggering.
Here's my AJAX call:
<script>
$(document).ready(function() {
/* load table with page load*/
$("#sort tbody").load("inc/index_table.php");
/* row deletion */
$(".deletelink").click(function(){
var id = $(this).attr("id");
$.ajax({
beforeSend: function (request) {
var answer = confirm("Are you SURE you want to delete this?/nThis action is NOT reversible.")
if (answer){ return(true); }
else { return(false); }
},
type: "POST",
url: location.href,
data: "delete="+id,
error: function() {
console.log("Theres an error with AJAX deletion");
},
success: function(){ //a.td.tr.remove just that row rather than the whole table
$this.parent().parent().remove();
console.log("Deleted.");
}
});
});
});
</script>
And the relevant HTML:
this is part of a while loop that prints a table from my database:
<td><a class="deletelink" id="'.$row["id"].'"><img src="images/delete.png" alt="Delete"></a></td>';
My code specifies <a class="deletelink"> but it's not registering with $(".deletelink").click(function(){ });
Does anyone see what could be wrong here or have an alternate method to suggest?
Looks like you are loading the elements dynamically. You can only bind to elements which currently exist in the DOM. To bind to elements which you are about to add, you must attach the event to a static element, the closer it is to the dynamic content, the better.
Try using on() with a delegate.
$("#sort tbody").load("inc/index_table.php");
/* row deletion */
$("#sort tbody").on("click", ".deletelink", function(){
//...rest of code the same
});
on() was added in jQuery 1.7. If you are using a previous version, but higher than 1.4.2 you can use delegate() instead.
$("#sort tbody").load("inc/index_table.php");
$("#sort tbody").delegate(".deletelink", "click", function(){
//...rest of code the same
});
If #sort or tbody of $("#sort tbody") is also dynamic then $("document").on("click", "#sort tbody .deletelink", function(){...}) would work as well, though anything closer than document is better off course.
Edit
I'm just looking at your code again, the delegate binding should work, however, using load()'s success callback should work with your existing code too.
The callback is executed ones load has successfully completed. I'm not 100% certain but I'm assuming that when success is called that the elements already have been loaded into the DOM and as such the normal bindings should work.
If that doesn't work the dynamic bindings mentioned above should.
$("#sort tbody").load("inc/index_table.php", function(){
/* row deletion */
$(".deletelink").click(function(){
// .. your code as before.
});
});
to make sure the table is fully loaded, try to declare the click function, in the callback of .load() like,
$("#sort tbody").load("inc/index_table.php", function() {
/* row deletion */
$(".deletelink").click(function(){ ....
});
});
Try using .on() to bind the events to the elements
$(".deletelink").on('click',function(e){
e.preventDefault();
Also make sure to add preventDefault to stop the default functioning of the link
The problem is that your delete link appears after the table loads. So when page was loaded and DOM tree was built, it wasn't there. So you can't attach a click to it.
You can try live(). This can be used as
$(".deletelink").live('click',function(){
// ajax call handling code here
});
This function attaches event after the element has been introduced in the DOM. However, this function is a bit greedy as it keeps on scanning entire DOM tree on any DOM change. So use with caution