Jquery/AJAX function not working - javascript

I already asked some questions about ajax, but I still don't get it.
I took a script that I found on the internet and made some modifications, but it didn't work!
HTML:
<a data-toggle="team" id="times">TEAM</a>
ORIGINAL SCRIPT:
<script>
// THIS IS WHERE THE MAGIC HAPPENS
$(function() {
$('nav a').click(function(e) {
$("#loading").show();
href = $(this).attr("href");
loadContent(href);
// HISTORY.PUSHSTATE
history.pushState('', 'New URL: '+href, href);
e.preventDefault();
});
// THIS EVENT MAKES SURE THAT THE BACK/FORWARD BUTTONS WORK AS WELL
window.onpopstate = function(event) {
$("#loading").show();
console.log("pathname: "+location.pathname);
loadContent(location.pathname);
};
});
function loadContent(url){
// USES JQUERY TO LOAD THE CONTENT
$.getJSON("content.php", {cid: url, format: 'json'}, function(json) {
// THIS LOOP PUTS ALL THE CONTENT INTO THE RIGHT PLACES
$.each(json, function(key, value){
$(key).html(value);
});
$("#loading").hide();
});
// THESE TWO LINES JUST MAKE SURE THAT THE NAV BAR REFLECTS THE CURRENT URL
$('li').removeClass('current');
$('a[href="'+url+'"]').parent().addClass('current');
}
</script>
MODIFIED SCRIPT:
<script>
// THIS IS WHERE THE MAGIC HAPPENS
$(function() {
$('#times').click(function(e) {
$("#loading").show();
var href = $(this).attr("data-toggle");
loadContent(href);
// HISTORY.PUSHSTATE
history.pushState('', 'New URL: '+href, href);
e.preventDefault();
});
// THIS EVENT MAKES SURE THAT THE BACK/FORWARD BUTTONS WORK AS WELL
window.onpopstate = function(event) {
$("#loading").show();
console.log("pathname: "+location.pathname);
loadContent(location.pathname);
};
});
function loadContent(url){
$.ajax({
url: 'ajaxcontdent/ajax'+url,
type: 'GET',
error: function(){
// always good to have an error handler with AJAX
},
success: function(data){
$('#content').html(data);
}
// THESE TWO LINES JUST MAKE SURE THAT THE NAV BAR REFLECTS THE CURRENT URL
$('li').removeClass('current');
$('a[href="'+url+'"]').parent().addClass('current');
};
</script>
What is wrong with my script? Nothing happens. I click in my <a> link and nothing. I already tried to put the file location on a hrefattribute, but then e.preventDefault(); doesn't work and my website runs like there is no AJAX.
In the original code, the author use some content.php file. But I don't know JSON, so I have no idea what did he put in that file.
There are no errors in the console.
My ajaxcontent/ajaxteam.php file content:
<p style="color:#fafafa;">Team</p>
It's just one line indeed. Just a test.

I think that may be a cause syntax error, I have regenerate one of your function so please use below code.
function loadContent(url){
$.ajax({
url: 'ajaxcontdent/ajax'+url,
type: 'GET',
error: function(){
// always good to have an error handler with AJAX
},
success: function(data){
$('#content').html(data);
}
});
};
Then use your operation, whatever you want, in your success block of above function.
I hope thin will help you.
Thansk

In your code if I am not wrong
url: 'ajaxcontdent/ajax'+url,
this is the main culprit.
Try this one:
url: 'ajaxcontent/ajax'+url,

Related

jQuery Load And Ajax Forms Not Working Together

I've created a news system, where i should be able to edit articles dynamically without redirect, from a modal. Also, i should be able to delete and create articles.
When something is changed, jQuery Load is called, but the problem is when i have to edit the loaded content.
$("#toolbox-items").load('inc-toolbox');
The above code loads the articles (the file is called inc-toolbox on purpose and works fine).
$(function () {
$('form').on('submit', function(e) {
e.preventDefault();
var clicked = document.activeElement.getAttribute('name');
$.ajax({
type: 'post',
url: 'process-toolbox',
data: $(this).serialize() + "&" + clicked + "=success",
success: function (response) {
$("#toolbox-items").load('inc-toolbox');
$('.modal-backdrop').remove();
}
});
});
});
But, when ever something has to be edited or deleted, the whole page reloads and nothing changes, although i'm still able to add things.
The add-button is not loaded dynamically from the script, but is in there from the start.
What in the world might the problem be?
Try code like this
$(function () {
$(document).on('submit','form', function(e) {
e.preventDefault();
var clicked = document.activeElement.getAttribute('name');
$.ajax({
type: 'post',
url: 'process-toolbox',
data: $(this).serialize() + "&" + clicked + "=success",
success: function (response) {
$("#toolbox-items").load('inc-toolbox');
$('.modal-backdrop').remove();
}
});
});
});

Submit a link using javascript or jquery without refreshing a page

I have a link which invokes an API which saves a session. Suppose my API be present on http://www.example.net and my link is as below :
<a href="http://www.example.net" >Click here </a>
Now i don't want to refresh the page. Just use JQuery or Javascript to simply execute the link and give an alert like "Action Succesfull". I don't see the point of using AJAX as I don't require any database actions from my side. Thanks
The point of AJAX is not to do database actions, its to comunicate with the server without needing to reload the page. I think your description qualifies for the use of AJAX, since you do expect a answer from the server, and you do not want to reload the page.
You could also open a iframe, or a new window, but ajax might be the solution here.
Keep in mind you need to cancel that event when you click on the anchor.
So, with ajax you could so something like:
$('a').on('click', function(e) {
e.preventDefault;
var href = this.getAttribute('href');
$.ajax({
url: href,
success: function(text) {
alert(text);
}
});
});
You will need an ajax call. Something like this:
$.ajax({
cache: false,
type: "Post",
url: "http://www.example.net",
success: function () {
alert("Success");
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error");
},
finaly: function () {
alert("Finish");
}
});
You can simply use onclick event if you don't want to use AJAX
Click here
Try to use an ajax call when click on button submit or the link. Here is the code :
$("a").click(function(e){
$.ajax({
url: "http://www.example.net",
type: "POST",
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
},
success: function(data,textstatus,jqXHR)
{
alert("Success");
}
});
e.preventDefault();
});
you need to do something like this:
$('a').click( function(e) {
e.preventDefault();
var url = "your link";
$.ajax({
url: url,
success: function(data)
{
alert(data); // show response.
}
});
return false;
});

jQuery onclick event not working upon making multiple ajax requests

I am making few ajax requests in my jQuery file. On success of these jQuery requests, I wrote few on click events which are not working.
This is my code
$(document).ready(function (){
$.ajax ({
type: "POST",
url: 'myServlet',
async: false,
success: function (response) {
id = parseInt(response);
setOutputEvents();
}
});
function setOutputEvents() {
for (var queryNumber = 0; queryNumber <= id; queryNumber++) {
$.ajax({
type: "POST",
url: 'myOtherServlet',
data: {queryNumber: queryNumber},
success: success,
async: false
});
var success = function (response) {
//some code here
generateTable();
}
}
}
function generateTable () {
//some code here
pagination();
}
function pagination(){
$(".class").click(function(event) {
alert();
});
}
$("#me").on("click", function(){
alert("me is triggered");
});
});
I understand making multiple ajax requests is a bad programming practice but what could be the reason for on click events not getting triggered?
These are the onclick events which are not working.
function pagination(){
$(".class").click(function(event) {
alert();
});
}
$("#me").on("click", function(){
alert("me is triggered");
});
I am using Google Chrome Version 39.0.2171.95 on Windows 7.
Please do let me know if any further information is necessary.
Since you use ajax to load even the initial content it seems, .class / #me html elements likely do not exist on initial page load of the DOM. As you didn't post html, i'm guessing this is the case.
Thus, you need to use a delegated event click handler to respond to it
so, you would change
$("#me").on("click", function(){
to
$(document).on("click", "#me", function(){
and so forth to link it to the parent element that does exist, the document itself.
This would work:
$(".class").on("click", function(){
alert("me is triggered");
});
function generateTable () {
//some code here
pagination();
}
function pagination(){
$(".class").trigger("click");
}
Some notes:
Event handler must be registered before triggering click.
Triggered click selector must match the class which has the click event registered.
Functions must be defined before the usage.

Why doesn't work (pushstate)

I'm trying to use pushstate. But it doesn't work.
Actually, my "loadContent()" function doesn't work. It doesn't make any difference. I'll show u my codes.
Javascript:
$(function() {
$('a').click(function(e) {
$("#loading").show();
href = $(this).attr("href");
loadContent();
// HISTORY.PUSHSTATE
history.pushState('', 'New URL: '+href, href);
e.preventDefault();
});
// THIS EVENT MAKES SURE THAT THE BACK/FORWARD BUTTONS WORK AS WELL
window.onpopstate = function(event) {
$("#loading").show();
console.log("pathname: "+location.pathname);
loadContent();
};
});
function loadContent(){
// USES JQUERY TO LOAD THE CONTENT
$.ajax({
url: "tema/project/content.php",
success: function(e){
$(".main-div").empty();
$(".main-div").append(e);
}
});
}
Content.php:
echo "this is my example to show me it does work.";
and there's some simple html codes that doesn't necessary.
OK i don't understand that, while the turn is on loadContent, there's nothing happen. It doesn't empty the 'main-div' it doesn't put any content it and there ne issue in chrome.
But why? why doesn't it work?
Any help?

Why is the return false stopping the alert?

Why does the return false stop the alert() from working and how do I get around this? If I remove it, the alert will show up, and then it will load the page that the <a> tag pointed to.
<script type="text/javascript">
$("document").ready(function(){
$("a").click(function(){
if(!$(this).is('static')){
var href = $(this).attr('href');
$.getJSON(href, function(data) {
alert('hi');
});
}
return false;
});
});
</script>
My guess is that badly formed JSON is being sent to the client, which will prevent the callback from firing. The manual says:
If there is a syntax error in the JSON
file, the request will usually fail
silently. Avoid frequent hand-editing
of JSON data for this reason.
Can you show us a snapshot of the JSON that the server is generating?
Answer Update!
I have tested this thoroughly using the $.ajax functions, which is what actually gets called by $.getJSON.
$("document").ready(function(){
$("a").click(function(event){
if(!$(this).is('static')){
var href = $(this).attr('href');
$.ajax({
url: href,
dataType: 'text',
success: function(data) {
alert("hi");
}
});
}
return false;
});
});
With a correctly formatted JSON object, this works as expected. Here is the contents of my json.html test file:
{ "firstName" : "John",
"lastName" : "Doe",
"age" : 23 }
However, if the file contains HTML, or a badly formatted JSON object, the alert never gets called - in fact, by adding an error handler to the above example, you'll spot that it errors:
$("document").ready(function(){
$("a").click(function(event){
if(!$(this).is('static')){
var href = $(this).attr('href');
$.ajax({
url: href,
dataType: 'text',
success: function(data) {
alert("hi");
},
error: function() {
alert("NO!!!!");
}
});
}
return false;
});
});
As you are replacing hyperlinks in your code with this request, I'm guessing that you maybe want to use a $.get, rather than a $.getJSON. So to return to your original example:
<script type="text/javascript">
$("document").ready(function(){
$("a").click(function(){
if(!$(this).is('static')){
var href = $(this).attr('href');
$.get(href, function(data) {
alert('hi');
});
}
return false;
});
});
</script>
This seems to work in Firefox 3 and in Chrome, with both get and getJSON.
IE8 is another story (I presume the same goes for IE7). There, only get works; getJSON fails. Is the JSON being returned by the server not IE-friendly?

Categories