jQuery Load And Ajax Forms Not Working Together - javascript

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();
}
});
});
});

Related

Prevent a click from loading a website and load some other custom content instead?

I am working on a project where a user can click on a link to get some additional information about it. The website uses Bootstrap Framework if that is important., The extra information is stored in a file on the server. Here is the code that calls the function openModal:
$('a.modal-link').on('click', openModal);
This is the JavaScript code for this function:
function openModal() {
var link = $(this).attr("href");
var page = "url-of-current-page";
var text = $(this).text();
$.ajax({
type: "POST",
url: "path/to/getdata.php",
data: {
link: link,
page: page
},
success: function(content) {
$(".modal-body").html(content);
}
})
};
This is supposed to set the HTML of modal-body to the data I received back. But it loads up the actual link inside the modal after showing up my data briefly. How can I prevent that?
Let me know if I need to add more details before downvoting.
As you're clicking an anchor, you probably want to prevent it from redirecting, change the function to
function openModal(e) {
e.preventDefault();
var link = $(this).attr("href");
var page = "url-of-current-page";
var text = $(this).text();
$.ajax({
type: "POST",
url: "path/to/getdata.php",
data: {
link: link,
page: page
},
success: function(content) {
$(".modal-body").html(content);
}
});
}

Jquery/AJAX function not working

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,

Jquery ajax button click event firing twice?

I have a Employee page which shows list of employees with an edit option. On clicking the edit button jquery-ajax is used to fetch the data from the server.
The problem is when I click the edit button the event is firing twice.
I am using a seperate js file and is referring the file to the main page.The script was working fine until i moved it to the seperate js file.
The Jquery script is
//ajaxGet on edit button click
$(document).on('click', '.editRole', ajaxGet);
var ajaxGet = function (e) {
var spinner = $(this).parent('div').find('.spinner');
var href = $("#editMenuSettings").data("url");
var menuRoleId = $(this).data('id');
spinner.toggle(true);
var options = {
type: "GET",
url: href,
data: { menuRoleId: menuRoleId }
};
$.ajax(options).success(function (data) {
spinner.toggle(false);
$(".modal-body").html(data);
$(".modal").modal({
backdrop: 'static'
});
});
$.ajax(options).error(function (data) {
spinner.toggle(false);
toastr.error("Oops..Some thing gone wrong");
});
return false;
};
You call $.ajax twice.
At lines
$.ajax(options).success(function(data)...
$.ajax(options).error(function(data)...
you actually make two different AJAX calls - one with success callback only, another one with error callback.
In your case, your call should look like this:
var options = {
type: "GET",
url: href,
data: { menuRoleId: menuRoleId }
};
$.ajax(options)
.success(function (data) {
spinner.toggle(false);
$(".modal-body").html(data);
$(".modal").modal({
backdrop: 'static'
});
})
.error(function (data) {
spinner.toggle(false);
toastr.error("Oops..Some thing gone wrong");
});
return false;
It will set both callbacks to the single AJAX call and execute this one.

How can I prevent a click event from firing when I call "<element>.click()"? Or what's a better way to solve this issue?

$(function() {
$(".universeLink").click(function (e) {
e.preventDefault();
var link = this;
alert(link.id);
$.ajax({
type: 'GET',
url: "#Url.Action("IsUniverseCached", "Universes")" + "?universeId=" + (link.id),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (returnedData) {
if (returnedData === false) {
alert(returnedData);
$("#" + link.id).empty();
$("#" + link.id).html("<div class=\"alert alert-warning\"><strong>Not cached</strong> — this data will take a while to arrive!</div>");
}
$("#" + link.id).click();
},
error: function () {
alert("Error");
}
});
});
});
I am building some JQuery to make a request before the original request is followed.
At the end of the success block, $("#" + link.id).click(); is called and the event is fired again. I tried something similar with (element).submit() on a form, and the .submit() event did not fire again, so I assumed I could do the same trick with .click().
Here's the HTML elements.
<a id="10" href="/Universes/ViewUniverse?universeId=10&regionId=8" class="universeLink">1</a>
(the ID is dynamically assigned)
Just redirect the browser to the new location. I.e. instead of using .click, assign to window.location.href:
window.location.href = link.href;

Passing a Variable into jQuery AJAX

I'm stuck in a rut. I hope some one can help.
Basically, I am building an AJAX mobile web app with jQuery. I am able to parse a specific XML file just fine, but I want the option to parse other XML files based on the link they were clicked on and load them on the fly into the same DIV or UL.
So:
click on Link1, loads XML1
click on Link2, loads XML2
I would like to be able to do this all client side, so no PHP (or is that a bad idea?). This the jquery code I've been using:
$(document).ready(function() {
$("a.load_ajax").click(loadAjax());
function loadAjax() {
var fileID = get('?lineID=');
var dataID = "xml/" + fileID + ".xml"
$.ajax({
type: "GET",
url: dataID,
dataType: "xml",
success: parseXml
});
function parseXml(xml) {
$(xml).find("train").each(function() {
$("ul#ajax-output").append('<li>' + $(this).find("time").text() + '</li>');
});
}
}
});
Its just not working at all. I have been passing the variable using GET in the url. So the link in the HTML goes to /?lineID=SBD_to_Union and it should load the XML file called SBD_to_Union.xml
Making sense to anyone? I'd appreciate some help.
What you seem to be struggling with is obtaining the line from the url in the anchor. Use $(this) to get the href attribute of the clicked link. You could then use a regex, if the url is as described, to remove all but the line id to use in constructing the link for the XML. I presume that the XML is server side and relative to the current url. If not, then you'll need to adjust the path. I've taken the liberty to compress things a bit by putting the functions inline. Edit: and the click handler should return false to prevent the link from actually performing its default action.
$(function() {
$("a.load_ajax").click( function() {
var fileID = $(this).attr('href').replace(/.*?lineID=/,'');
var dataID = "xml/" + fileID + ".xml"
$.ajax({
type: "GET",
url: dataID,
dataType: "xml",
success: function(xml) {
$(xml).find("train").each(function() {
$("ul#ajax-output").append('<li>' + $(this).find("time").text() + '</li>');
});
}
});
return false;
});
});
Have you checked if the get function returns the correct data ?
add an alert(fileID); right after the get(..); line..
But why don't you create the urls to point directly to the xml files instead of parsing and creating urls on the fly ?
just make the link in the html to point to xml/SBD_to_Union.xml
On first glance, I think your ajax() syntax is a little off.
Are you using query strings for a particular reason? If no, I'd try giving the HTML links the absolute URL to the XML file you are trying to fetch:
Then try this:
$("a.load_ajax").click(function(e) {
e.preventDefault();
var url = $(this).attr('href');
$.ajax({
type: 'GET',
url: url,
dataType: 'xml',
success: function(response) {
$(response).find('train').each(function() {
$('ul#ajax-output').append('<li>' + $(this).find('time').text() + '</li>');
}
});
});
I haven't tested this, but it should do what you want.
Link1
Link2
You can do things depending on the id of the href (or another of its attributes or its href value).
$(function() {
$("a.load_ajax").click(loadAjax);
});
function loadAjax()
{
if ($(this).attr("id") == "link1")
{
alert("link1"); //load xml1
}
else
{
alert("link2"); //load xml2
};
}

Categories