Other Ajax calls not working after the first - javascript

just working on a small blogging system and using multiple ajax calls for updating information without page reloads.
However, after one ajax call the others dont work and instead the form goes to the php page itself.
The ajax calls all follow a similar pattern of:
$(document).ready(function(){
$('.addpost').one("submit",function(e){
$.ajax({
type: "POST",
url: "process/addnewpost.php",
data: $targetForm.serialize(),
dataType: "json",
success: function(response){
if (response.databaseSuccess) {
$("#container").load("#container");
} else {
$ckEditor.after('<div class="error">Something went wrong!</div>');
}
}
});
});
});
On my page, these scripts are loaded like so:
<script src="http://buildsanctuary.com/js/addcomment.js"></script>
I had the same issue with some button events, but got around the issue using .on() however sometimes this doesnt even work so my solution was to put the even in the ajax success response.
Cant find any answers around about how to bind / delegate a whole script?

You use $('.addpost').one("submit",function(e){ to bind the submit event to do your ajax therefore it will ony execute one time, use on instead.
$('.addpost').on("submit",function(e){

Related

How to execute JavaScript after dropdown data is inserted via Ajax?

I have a form that loads some of its Data dynamically via Ajax, where, apart of a lot of other stuff, I fill a dropdown list. When selecting an item it will load the corresponding data into a table.
That all works fine, but now I want to be able to, by default, load the data of the first element once the page loads.
But since the dropdown populates over Ajax, it is filled slightly after $(document).ready(), so that doesn't work.
One way it might work would be to just wait for a second or two, since then it should all be loaded, but that really isn't something I fancy doing.
Any idea how I could achieve that?
I already tried it with onloadeddata="loadData($(this)[0].selectedOptions[0].value)" on the select tag, but that doesn't seem to do anything.
EDIT:
And I don't want to execute this in the ajax success function as data might also be loaded in other ways. It should really be the dropdown field or something that watches the dropdown, that executes this.
JQuery Ajax provides a callback for successful request.
$.ajax({
url : 'stackoverflow.com/api',
type: 'GET',
success : successMethod
})
function successMethod(){
// foo
}
Once the request receives a response successMethod will be called.
jquery ajax have a success function in which you can do such kind of functionality. To do so you can try:
success: function(response) {
// fill the form value with 'response'
$('#dropdown_id').val('any_value'); // this will set the dropdown to specific value
}
$.ajax({
url: "test.html",
...
}).done(function(data) {
// do something with your data in here
});

Ajax Call Confusion

before we start apologies for the wording and lack of understanding - I am completely new to this.
I am hoping to run a php script using Ajax - I don't need to send any data to the php script, I simply need it to run on button press, after the script is run I need to refresh the body of the page. What I have so far:
HMTL Button with on click:
<font color = "white">Next Question</font>
JS Ajax call:
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'php',
success:function(content,code)
{
alert(code);
$('body').html(content);
}
});
}
this runs the php script but doesn't stay on the current page or refresh the body - has anyone got any ideas - apologies if this is completely wrong I'm learning - slowly.
Many thanks in advance.
**As a small edit - I don't want a user to navigate away from the page during the process
How about using load instead of the typical ajax function?
function AjaxCall() {
$(body).load('increment.php');
}
Additionally, if you were to use the ajax function, php is not a valid type. The type option specifies whether you are using GET or POST to post the request.
As far as the dataType option (which is what I think you mean), The Ajax doesn't care what technology the called process is using (like ASP or PHP), it only care about the format of the returned data, so appropriate types are html, json, etc...
Read More: http://api.jquery.com/jquery.ajax/
Furthermore, if you are replacing the entire body content, why don't you just refresh the page?
your ajax should be
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'post',
success:function(data)
{
console.log(data);
$('body').html(data);
}
});
}
if you want to learn ajax then you should refer this link
and if you just want to load that page then you can use .load() method as "Dutchie432" described.
If you are going to fire a javascript event in this way there are two ways to go about it and keep it from actually trying to follow the link:
<font color = "white">Next Question</font>
Note the return false;. This stops the following of the link. The other method would be:
<font color = "white">Next Question</font>
Note how this actually modifies the href to be a javascript call.
You can study about js and ajax here http://www.w3schools.com/ajax/default.asp will help a lot. Of course all js functions if called from internal js script should be inside <script></script> and if called from external you call the js gile like <script src"somejs.js"></script> and inside js there is no need for <script> tags again. Now all those function do not work by simply declaring them. So this:
function sayHello(){
alert("Happy coding");
}
doesn't work because it is just declared and not called into action. So in jQuery that you use after we declare some functions as the sayHello above we use:
jQuery(document).ready(function($){
sayHello();
});
Doing this we say that when everything is fully loaded so our DOM has its final shape then let the games begin, make some DOM manipulations etc
Above also you don't specify the type of your call meaning POST or GET. Those verbs are the alpha and omega of http requests. Typically we use GET to bring data like in your case here and POST to send some data for storage to the server. A very common GET request is this:
$.ajax({
type : 'GET',
url : someURL,
data : mydata, //optional if you want to send sth to the server like a user's id and get only that specific user's info
success : function(data) {
console.log("Ajax rocks");
},
error: function(){
console.log("Ajax failed");
}
});
Try this;
<script type="text/javascript">
function AjaxCall() {
window.location.reload();
}
</script>
<body>
<font color = "white">Next Question</font>
</body>

Calling a javascript function from a link generated from a ajax call

I have a javascript function.
I'm making a AJAX call, and in that recieved content there is a link that I want to call the javascript function with.
MyJavascriptFunction(bla){
alert (bla);
}
Result from ajax = "Click
Do I have to do anything special with the result from AJAX to get this to work or should it just work.
I have tried it like this but with no success with clicking the link.
The AJAX call:
function doSearch() {
var form = $('form');
$.ajax({
url: "doSearch.php",
type: "GET",
data: form.serialize(),
success: function(result){
document.getElementById("result").innerHTML=result;
}
});
}
In the php I'm printing out
Click
First of all, try it. But yes you have to do something with the AJAX result. It has to be put somewhere in the DOM or the user won't be able to click on it.
Plus, make sure that the javascript function is a top level. I would suggest you use event handlers instead though.
Change your <a> tag to:
Click
You are mixing jQuery and DOM. that is not pretty
try this - assuming you do not have more than one link in the html
success: function(result){
$("#result").html(result).find("a").on("click",function() {
MyJavascriptFunction(bla);
return false;
};
}

Execute unobtrusive Javascript after Ajax call

I want to use John Resig's pretty date for replacing my ugly time stamps with some nice-to-read time specification.
So I thought about using the following unobtrusive html markup:
<span data-type="prettyDate">25.04.2012 10:16:37</span>
Acording to that I use following Javascript/jQuery to prettify the date:
$(function() {
$('[data-type="prettyDate"]').prettyDate();
}
My problem is that I don't know how to deal with markup that is loaded using ajax because that would not be caught since it does not yet exist when the DOM ready event fires. Reacting to events on "ajaxed" elements is pretty easy using the on handler. But this is not an event.
You have to call .prettyDate() after each Ajax response is added to the DOM. A simple way to do that is to set a global complete handler with ajaxComplete.
You can use jQuery to target dynamic content before it's actually been inserted into the document, something like:
success: function(html) {
var $html = $(html);
$html.find('[data-type="prettyDate"]').prettyDate();
$(somewhere in document).append($html);
}
What you want to do to get the best performance out of this is have a function which get called on the data as it gets returned from the ajax callback. That way you can prettify your date before adding them to the DOM.
You don't want to call pretty date on element in the DOM every time as you will process date already done too.
So, something like this.
$.ajax({
url:'someurl',
success: function(data) {
var $content = $(data).find('[data-type="prettyDate"]').prettyDate();
$('#mycontainer').append($content);
}
});
or have an helper function which you call
function prettify(data) {
return $(data).find('[data-type="prettyDate"]').prettyDate();
}
or even better hook into the ajax call so that it is done for all html content
There have been a number of cases where I needed certain code to execute after every AJAX call. I'm not sure if it's considered the "correct" solution but I simply decided to create my own wrapper method and use that whenever I needed to make an AJAX request. It typically looks something like this:
AJAXLoadData: function (url, data, successCallBack) {
$.ajax({
type: "GET",
data: data,
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Code I want to execute with every AJAX call
// goes here.
// Then trigger the callback function.
if (successCallBack) successCallBack(msg);
},
error: function (msg) {
alert("Server error.");
}
});
}
In my case this made it particularly convenient to create a javascript caching system for static HTML files.
You could incorporate this code into your ajax success callback function. When the ajax is done and you update your page, also run the code to prettify the dates.
This is one of the things .on() is for. (In the olden days, .live() would have been used.)

Jquery Live Load - Load form via ajax

I am simply looking to call a function when a form is loaded via ajax. My current code looks like this:
$('form').live("load",function() {...}
My ajax call looks like this:
jQuery.ajax({
type: "get",
url: "../design_form.php",
data: "coll=App_Forms&form=Step_1_Company_Sign_Up",
dataType: "html",
success: function(html){
jQuery('#Right_Content').hide().html(html).fadeIn(1000);
}
})
I know that i could put my call inside the success portion of the ajax call but i am trying to minimize code and resuse other codes so i would really like to use the live feature.
I am loading a form via ajax and when that form is loaded i want to trigger a function using the jquery live. This works fine when i set it to "click"
$('form').live("click",function() {...}
but it is unnecessary to run this function on every click, i just need it to run once on the form load so that is why i want to use the load listener not the click.
Thank you.
Edit: I think you wanted to have custom code inside success callback which will be used in different pages so you don't want to duplicate the same ajax call in different pages. If so, then you should call a function inside that success callback and implement different version of that in different page.
jQuery.ajax({
type: "get",
url: "../design_form.php",
data: "coll=App_Forms&form=Step_1_Company_Sign_Up",
dataType: "html",
success: function(html){
jQuery('#Right_Content').hide().html(html).fadeIn(1000);
afterFormLoad(); //Implement this function
}
});
function afterFormLoad() { } //dummy function defined in the common code
And in your specific page,
function afterFormLoad () {
//this is from page 1
}
Below just shows you about .live/.die and .one incase if you want to understand how to unbind it using .die.
You can unbind .live inside the click handler using .die,
DEMO
$('form').live("click",function(e) {
alert('clicked');
$('form').die('click'); // This removes the .live() functionality
});
You can use .one if you are using jQuery 1.7. See below code,
DEMO
$(document).one('click', 'form', function() {
alert('clicked');
});
There isn't a dom insert event.
Although, in javascript you can trigger anything
success: function(html){
jQuery('#Right_Content').hide().html(html).fadeIn(1000)
.trigger('ajax-load');
}
Then you can listen to event using
jQuery('#Right_Content').on('ajax-load', callback);
Triggering the event manually might be helpful for use in a couple of pages, but if you need it to use across entire application, you'll be better using a plugin such as provided by Oscar Jara
There is no load to trigger with jQuery live, try to read the API documentation: http://api.jquery.com/live/
On the other hand, you can use a plugin called livequery and do something like this:
$(selector).livequery(function() {
});
Use as reference:
https://plugins.jquery.com/livequery
https://github.com/brandonaaron/livequery
You may want to consider load() method which is a convenience method of $.ajax
http://api.jquery.com/load/
var data= "coll=App_Forms&form=Step_1_Company_Sign_Up"
jQuery('#Right_Content').hide().load("../design_form.php", data,function(){
/* this is the success callback of $.ajax*/
jQuery(this).fadeIn(1000);
});

Categories

Resources