click me
I have to send abc.html into a table in my database when I click the link
There are different ways of achieving what you are trying to do.
I think though the "cleanest" would be to use jquery (javascript) to manipulate the event handler.
Something like this would work:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div>
click me
</div>
<script>
$(function() {
$("a").click(function (e) {
var url = $(this).attr("href"); // Here we retrieve the href of clicked link
var res = $.ajax({
type: "POST",
data: {
url: url // The left side is the request key ( so: $_POST['url'])
},
url: "https://url/to/handler.php",
async: false
}).responseText;
console.log(res);
if(res == "success") return true; // returning true lets the browser follow the link
else return false; /* so if it didn't work, the link will not be
followed. Of course you can do at these two
points whatever you like. */
})
});
</script>
Simply echo in PHP success if the insert was successful.
Note though that async:false for AJAX requests is deprecated.
Related
I'm trying to show a specific div depending on the result of a SQL query.
My issue is that I can't get the divs to switch asynchronously.
Right now the page needs to be refreshed for the div to get updated.
<?php
//SQL query
if (foo) {
?>
<div id="add<?php echo $uid ?>">
<h2>Add to list!</h2>
</div>
<?php
} else {
?>
<div id="remove<?php echo $uid ?>">
<h2>Delete!</h2>
</div>
<?php
}
<?
<script type="text/javascript">
//add to list
$(function() {
$(".plus").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "ajax_add.php",
data: info,
success: function(data){
$('#add'+I).hide();
$('#remove'+I).show();
}
});
return false;
});
});
</script>
<script type="text/javascript">
//remove
$(function() {
$(".minus").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "ajax_remove.php",
data: info,
success: function(data){
$('#remove'+I).hide();
$('#add'+I).show();
}
});
return false;
});
});
</script>
ajax_add.php and ajax_remove.php only contain some SQL queries.
What is missing for the div #follow and #remove to switch without having to refresh the page?
"I'm trying to show a specific div depending on the result of a SQL query"
Your code doesn't seem to do anything with the results of the SQL query. Which div you hide or show in your Ajax success callbacks depends only on which link was clicked, not on the results of the query.
Anyway, your click handler is trying to retrieve the id attribute from an element that doesn't have one. You have:
$(".plus").click(function(){
var element = $(this);
var I = element.attr("id");
...where .plus is the anchor element which doesn't have an id. It is the anchor's containing div that has an id defined. You could use element.closest("div").attr("id") to get the id from the div, but I think you intended to define an id on the anchor, because you currently have an incomplete bit of PHP in your html:
<a href="#" class="plus" ?>">
^-- was this supposed to be the id?
Try this:
<a href="#" class="plus" data-id="<?php echo $uid ?>">
And then:
var I = element.attr("data-id");
Note also that you don't need two separate script elements and two document ready handlers, you can bind both click handlers from within the same document ready. And in your case since your two click functions do almost the same thing you can combine them into a single handler:
<script type="text/javascript">
$(function() {
$(".plus,.minus").click(function(){
var element = $(this);
var I = element.attr("data-id");
var isPlus = element.hasClass("plus");
$.ajax({
type: "POST",
url: isPlus ? "ajax_add.php" : "ajax_remove.php",
data: 'id=' + I,
success: function(data){
$('#add'+I).toggle(!isPlus);
$('#remove'+I).toggle(isPlus);
}
});
return false;
});
});
</script>
The way i like to do Ajax Reloading is by using 2 files.
The first: the main file where you have all your data posted.
The second: the ajax file where the tasks with the db are made.
Than it works like this:
in the Main file the user lets say clicks on a button.
and the button is activating a jQuery ajax function.
than the ajax file gets the request and post out (with "echo" or equivalent).
at this point the Main file gets a success and than a response that contains the results.
and than i use the response to change the entire HTML content of the certain div.
for example:
The jQuery ajax function:
$.ajax({
type: 'POST', // Type of request (can be POST or GET).
url: 'ajax.php', // The link to the Ajax file.
data: {
'action':'eliran_update_demo', // action name, used when one ajax file handles many functions of ajax.
'userId':uId, // Simple variable "uId" is a JS var.
'postId':pId // Simple variable "pId" is a JS var.
},
success:function(data) {
$("#div_name").html(data); // Update the contents of the div
},
error: function(errorThrown){
console.log(errorThrown); // If there was an error it can be seen through the console log.
}
});
The PHP ajax function:
if (isset($_POST['action']) ) {
$userId = $_POST['userId']; // Simple php variable
$postId = $_POST['postId']; // Simple php variable
$action = $_POST['action']; // Simple php variable
switch ($action) // switch: in case you have more than one function to handle with ajax.
{
case "eliran_update_demo":
if($userId == 2){
echo 'yes';
}
else{
echo 'no';
}
break;
}
}
in that php function you can do whatever you just might want to !
Just NEVER forget that you can do anything on this base.
Hope this helped you :)
if you have any questions just ask ! :)
I have a PHP populated table from Mysql and I am using JQuery to listen if a button is clicked and if clicked it will grab notes on the associated name that they clicked. It all works wonderful, there is just one problem. Sometimes when you click it and the dialog(JQuery UI) window opens, there in the text area there is nothing. If you are to click it again it will pop back up. So it seems sometimes, maybe the value is getting thrown out? I am not to sure and could use a hand.
Code:
$(document).ready(function () {
$(".NotesAccessor").click(function () {
notes_name = $(this).parent().parent().find(".user_table");
run();
});
});
function run(){
var url = '/pcg/popups/grabnotes.php';
showUrlInDialog(url);
sendUserfNotes();
}
function showUrlInDialog(url)
{
var tag = $("#dialog-container");
$.ajax({
url: url,
success: function(data) {
tag.html(data).dialog
({
width: '100%',
modal: true
}).dialog('open');
}
});
}
function sendUserfNotes()
{
$.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data:
{
'nameNotes': notes_name.text()
},
success: function(response) {
$('#notes_msg').text(response.the_notes)
}
});
}
function getNewnotes(){
new_notes = $('#notes_msg').val();
update(new_notes);
}
// if user updates notes
function update(new_notes)
{
$.ajax({
type: "POST",
//dataType: "json",
url: '/pcg/popups/updateNotes.php',
data:
{
'nameNotes': notes_name.text(),
'newNotes': new_notes
},
success: function(response) {
alert("Notes Updated.");
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
});
}
/******is user closes notes ******/
function closeNotes()
{
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
Let me know if you need anything else!
UPDATE:
The basic layout is
<div>
<div>
other stuff...
the table
</div>
</div>
Assuming that #notes_msg is located in #dialog-container, you would have to make sure that the actions happen in the correct order.
The best way to do that, is to wait for both ajax calls to finish and continue then. You can do that using the promises / jqXHR objects that the ajax calls return, see this section of the manual.
You code would look something like (you'd have to test it...):
function run(){
var url = '/pcg/popups/grabnotes.php';
var tag = $("#dialog-container");
var promise1 = showUrlInDialog(url);
var promise2 = sendUserfNotes();
$.when(promise1, promise2).done(function(data1, data2) {
// do something with the data returned from both functions:
// check to see what data1 and data2 contain, possibly the content is found
// in data1[2].responseText and data2[2].responseText
// stuff from first ajax call
tag.html(data1).dialog({
width: '100%',
modal: true
}).dialog('open');
// stuff from second ajax call, will not fail because we just added the correct html
$('#notes_msg').text(data2.the_notes)
});
}
The functions you are calling, should just return the result of the ajax call and do not do anything else:
function showUrlInDialog(url)
{
return $.ajax({
url: url
});
}
function sendUserfNotes()
{
return $.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data: {
'nameNotes': notes_name.text()
}
});
}
It's hard to tell from this, especially without the mark up, but both showUrlInDialog and sendUserfNotes are asynchronous actions. If showUrlInDialog finished after sendUserfNotes, then showUrlInDialog overwrites the contents of the dialog container with the data returned. This may or may not overwrite what sendUserfNotes put inside #notes_msg - depending on how the markup is laid out. If that is the case, then it would explains why the notes sometimes do not appear, seemingly randomly. It's a race condition.
There are several ways you can chain your ajax calls to keep sendUserOfNotes() from completing before ShowUrlInDialog(). Try using .ajaxComplete()
jQuery.ajaxComplete
Another ajax chaining technique you can use is to put the next call in the return of the first. The following snippet should get you on track:
function ShowUrlInDialog(url){
$.get(url,function(data){
tag.html(data).dialog({width: '100%',modal: true}).dialog('open');
sendUserOfNotes();
});
}
function sendUserOfNotes(){
$.post('/pcg/popups/getNotes.php',{'nameNotes': notes_name.text()},function(response){
$('#notes_msg').text(response.the_notes)
},"json");
}
James has it right. ShowUrlInDialog() sets the dialog's html and sendUserOfNotes() changes an element's content within the dialog. Everytime sendUserOfNotes() comes back first ShowUrlInDialog() wipes out the notes. The promise example by jeroen should work too.
this is an ajax method that inserts the data into a db and should supposedly display the new content.
<script type = "text/javascript">
$(document).ready(function() {
$('#submit').live('click', function(eve) {
eve.preventDefault() ;
var form_data = {
title: $('#title').val()
};
$.ajax({
url: "http://localhost/ci/index.php/chat/comment",
type: 'POST',
data: form_data,
success: function(msg) {
alert(msg);
}
});
});
});
</script>
However in my /chat/comment, i am loading the view again, i.e, user submits a comment, load the view again and the comment should be there. My response from server is the view's HTML. However the view comes with all the divs and there are many of them. I need to retrieve only part of the div, say, #commentspace from the ajax on success.
Look at the jQuery $.load() function?
Example
Inside "firstpage.html"
$('#content').load('secondpage.html #content');
I have a simple toggle button that the user can use to either subscribe or unsubscribe from a group they belong to. I have 2 forms that get the post and depending on which page the form posts to, the user is subscribed or unsubscribed. Here's my code and I'm looking for a better way to do this. Currently, my user can click to subscribe or unsubscribe but he or she will have to reload the page to change their setting. In other words, it works fine but there's no toggle...users can't click back and forth between subscribe and unsubscribe, as they have to refresh the page and resubmit. I also would love to fix the toggle function. Thanks for any help.
<script type="text/javascript">
//Capturing get parameter
var param1var = getQueryVariable("group_id");
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
}
var owner = getQueryVariable('group_id');
var dataString = "owner="+ owner;
$(function() {
$("#subscribe").click(function(){
$.ajax({
type: "POST",
url: "groupnotifications.php",
data: dataString,
success: function(){
$("#subscribe").removeClass("notifications_subsc");
$("#subscribe").addClass("not_subscribed_group");
}
});
});
});
</script>
<script type="text/javascript">
//Capturing get parameter
var param1var = getQueryVariable("group_id");
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
}
var owner = getQueryVariable('group_id');
var dataString = "owner="+ owner;
$(function() {
$("#notsubscribed").click(function(){
$.ajax({
type: "POST",
url: "groupnotificationsoff.php",
data: dataString,
success: function(){
$("#notsubscribed").removeClass("not_subscribed_group");
$("#notsubscribed").addClass("notifications_subsc");
}
});
});
});
</script>
There's no need to rely on parsing out the query string when server-side scripting is available. Instead, when the page is initially served, arrange for PHP to write the group_id value into (eg.) a hidden input field, which then becomes available client-side to be read into javascript/jQuery. (Other techniques are available)
It's also a good idea to arrange for your "groupnotifications.php" script to receive a $_POST['action'] instruction to either subscribe or unsubscribe. That way the client-side half of the application exercises control.
With those changes in place, the code will be something like this:
$(function() {
$("#subscribe").click(function(){
var $s = $(this).attr('disabled',true);//disable button until ajax response received to prevent user clicking again
var clss = ['not_subscribed_group','notifications_subsc'];//The two classnames that are to be toggled.
var dataOj = {
owner : $s.closest(".groupContainer").find('.group_id').val(),//relating to element <input class="group_id" type="hidden" value="..." />
action : ($s.hasClass(clss[0])) ? 1 : 0;//Instruction to 1:subscribe or 0:unsubscribe
};
$.ajax({
type: "POST",
url: "groupnotifications.php",
data: dataObj,
success: function(status) {//status = 1:subscribed or 0:unsubscribed
switch(Number(status)){
case 1:
$s.removeClass(clss[1]).addClass(clss[0]);
break;
case 0:
$s.removeClass(clss[0]).addClass(clss[1]);
break;
default:
//display error message to user
}
}
error: function(){
//display error message to user
}
complete: function(){
$s.attr('disabled',false);
}
});
});
});
untested
Note: The statement $s.closest(".groupContainer").find('.group_id').val() relies on the hidden input element having class="group_id" and allows for multiple groups, each with its own toggle action, on the same page. Just make sure each group is wrapped in an element (eg div or td) with class="groupContainer".
I have been researching for the last two days, and have found nothing.
structure:
index.php:
<head>
<script type="text/javascript" src="JS/jquery-1.6.2.js"></script>
<script type="text/javascript" src="function.js"></script>
</head>
<body>
<div>
<div>Show</div> *-->if I click this link data loads into DIV below by function.js without reloading*
<div id="producten"></div> *-->testpage.php loads here perfect,
the code of testpage.php makes by while loop other links.
Here I want to click on a link to load next data in div id=information
without reloading the index.php so the data in the first DIV stay visible
and I dont know how to do that*
<div id="information"></div> *-->testpage2.php have to load data from sql in this DIV*
</div>
</body>
function.js:
$(document).ready(function() {
$(".testcat").click(function() {
var testid = $(this).attr("id");
var datastring = 'id='+ testid ;
$.ajax({
type: "POST",
url: "testpage.php",
data: datastring,
cache: false,
success: function(res) {
$('#producten').html("<div class='loading'><img src='IMG/loading.gif' /></div>")
.hide()
.fadeIn(2000, function() {
$('#producten').html(res);
})
}
});
return false;
});
});
testpage.php and testpage2.php are PDO code for sql data.
You'll want to attach your click handlers with on so that dynamically added content still has the same ajax handlers available to them:
Add whatever information is needed to differentiate one click from the next, ie
<a href='...' data-resultdiv='production'
Then, cleaning up your handler a bit: I assume you want the ajax request to go to the href of the link, and that you want to show "loading" immediately (instead of waiting for the request to complete).
Finally, to cancel the anchor's default behavior of browsing to the page referenced by the href, you can return false;
$(document).on("click", "a", function() {
var href = $(this).attr("href");
var successDiv = $(this).data("resultdiv");
$('#' + successDiv).html("<div class='loading'><img src='IMG/loading.gif' /></div>");
$.ajax({
type: "POST",
url: href,
data: datastring,
cache: false,
success: function(res) {
$('#' + successDiv).hide().html(res).fadeIn(2000);
}
}
return false;
});
And of course if you only want this to run for certain anchors, you can put a selector on your call to on
$(document).on("click", "a.someClass", function() {