Including javascript file along with ajax response - javascript

I've got a dropdown that runs AJAX each time an option is selected. The ajax call returns HTML markup (buttons and text boxes) and a script tag, which the HTML(buttons) uses to submit to a database via ajax.
<html>
<head>........</head>
<body>........</body>
<select class="chooseOption">
...
...
</select>
<div class="ajaxResult">
<!-- after successful ajax -->
<!-- HTML Markup here -->
<!-- I'm having to include main.js here again so that HTML matkup can use AJAX -->
</div>
....
....
....
<footer> //include main.js </footer>
This arrangement seems to work fine only that, there's an exponential call to main.js each time an option is selected.
Doing something like this(below) doesn't seem to work, I'm guessing because AJAX is injected into the page and isn't aware of what scripts that are already available on the page?
<script>
var len = $('script').filter(function () {
return ($(this).attr('src') == 'main.js');
}).length;
//if there are no scripts that match, the load it
if (len === 0) {
var url = "main.js";
$.getScript(url);
}
</script>
Is there a simple way around this? To make sure that main.js works across all AJAX requests without having to include it with each request?
Sample main.js content.
Ajax snippet that populates the HTML Markup (buttons and textboxes)
$("#students").on("change", function (e) {
e.preventDefault();
var supervise = this.value;
var faculty = $("#faculty").val();
$.ajax({
method: "POST",
url: 'URL',
dataType: 'html',
data:
{
selectValue: supervise,
faculty: faculty
},
success: function (result) {
$("#ajaxResult").html(result);
}
})
});
When #statement_button from HTML markup returned from select dropdown is clicked
$('#statement_button').click(function (e) {
var student_statement = $("#student_statement").val();
if (student_statement == '') {
alert('Please enter your statement');
return false;
}
var student = $("#student").val();
var statement_button = $(this).attr("value");
$.ajax({
type: "POST",
url: formsUrl,
dataType: 'text',
data:
{
student_statement: student_statement,
student: studentusername,
statement_button: statement_button
},
success: function (result) {
$("#result").text(result);
$("textarea#student_statement").val('');
}
})
});

From the code you posted it looks like you can just delegate the button handling to the .ajaxResult element which is always present in the html (from the initial load).
So just changing how you bind your button handlers should be enough
$("#students").on("change", function (e) {
to
$('.ajaxResult').on('change', '#students', function (e) {
$('#statement_button').click(function (e) {
to
$('.ajaxResult').on('click', '#statement_button', function (e) {
etc..
So the script with the above code is run once in the initial load of the page (in a $(document).ready(..))

Related

Onload Page load extern page

i use this AJAX script to load an extern page (mpt_planningen_overzicht.php) into a div op the mainpage (mainpage.php) when people select or unselect a checkbox.
But i also want to load the data from the extern page in the div when mainpage.php is opened.
How can i do this?
Script:
<script type="text/javascript">
$(document).ready(function(){
$('input[type="checkbox"]').on('click', function(){
var formData = $(":input,:hidden").serialize();
$.ajax({
type: "POST",
url: "mpt_planningen_overzicht.update.php",
data: formData,
success: function(result){ /* GET THE TO BE RETURNED DATA */
$("#resultaat").html(result); /* THE RETURNED DATA WILL BE SHOWN IN THIS DIV */
}
});
});
});
</script>
I thought something like this:
function onLoadSubmit() {
document.nameofForm.submit();
}
But the Ajax script that checks if a selectbox is checked/unchecked is already on mainpage.php, so when i add the script above, it will continue reloading.
If I understood the question correctly, you can try something like this:
<script type="text/javascript">
//separationg the function that loads the page in order to use it multiple times
var loadSepratePage = function(){
var formData = $(":input,:hidden").serialize();
$.ajax({
type: "POST",
url: "mpt_planningen_overzicht.update.php",
data: formData,
success: function(result){ /* GET THE TO BE RETURNED DATA */
$("#resultaat").html(result); /* THE RETURNED DATA WILL BE SHOWN IN THIS DIV */
}
});
}
$(document).ready(function(){
$('input[type="checkbox"]').on('click', loadSepratePage); // without paranthesis () to pass the function as a parameter
loadSepratePage() // with paranthesis () to actually call the function
});
</script>
If this is not what you mean feel free to leave comment

search function in laravel wont work

I have this search bar inside navigation file and it's an enter submit input tag.
I include this file in many pages. but when I enter(submit) it doesn't go to searchResults.blade.php
MY HTML
<input class="searchkey" id="searchkey" type="search" required onkeydown="search(this)">
My JS
$('.searchkey').keydown(function(event) {
var getKeyword = document.getElementById("searchkey").value;
if (event.keyCode == 13) {
$.ajax({
url: "search",
type: "POST",
data:{
getKeyword : getKeyword
},
success: function() {}
});
}
});
MY CONTROLLER
public function multiSearch()
{
$searchKey = Input::get('getKeyword');
$getResults = array();
$getResults = DB::select("SELECT title FROM books WHERE title LIKE '%$searchKey%'");
return View::make('content.searchResults',array('getResults'=>$getResults));
}
MY ROUTES
Route::post('search', 'UserController#multiSearch');
First of all in your ajax callback you should put the view results in some container on the page, i.e.: <div id="search-result"></div> by adding this callback function:
success: function(data) {
$('#search-reasult').html(data);
}
You also have to render the view in your controller like this:
return View::make('content.searchResults',array('getResults'=>$getResults))
->render();

How To implement the Javascript to elements which has been added to head section of HTML By Jquery prepend()?

I have this in my head section.
<script type="text/javascript" src="post.js"></script>
I want this post.js to be also be implemented to the newly created elements.My another js file which is named as main.js have a code that get data from another php file and prepend it in a div with id display.Previous Loaded Div works great with the post.js file but as new elements are prepended, it does not work for new ones. Here is my main.js code which get data from php file and prepend it:
var auto_refresh8 = setInterval(function() {
var id = "id="+$(".ally:first").attr("id");
$.ajax({
type: "POST",
url: "get_post.php",
data: id,
cache: false,
success:function(html){
$('#display').prepend(html);
}
});
},2000);
this jquery ajax request get data from get_post.php file and prepend it to the div display. but the code in post.js doesn't work with this.The data returned by jquery ajax request contains a div with class comm which have to submitted when keypress function acts.
following is the code of post.js :
$(document).ready( function() {
$(".comm").keypress(function(e) {
if(e.which == 13) {
var id = $(this).attr("id");
var data = 'id=' + id;
var post = $(this).val();
var data1 = 'comment='+post;
var wholedata = data+'&'+data1;
$(this).blur();
$.ajax({
type: "POST",
url: "c_insert.php",
data: wholedata,
cache: false,
success:function(html){
$('.class_all'+id).append(html);
}
});
return false;
}
});
});
Use a delegate to handle the event in post.js file instead. See the jQuery documentation for more information.
Something like this should do it:
$('#display').on('keypress', '.comm', function (e) {
if(e.which == 13) {
// Do code on event
}
});
Note that the "on" function should only be used if you are using jQuery version 1.7 or later. Previous versions uses the function "delegate".
edit Changed $(document).on(...) to $('#display').on(...) since all '.comm'-elements are children of '#display'.

submit a form with jQuery function

i have a html page, which contains a form and i want when the form is successfully submited, show the below div:
<div class="response" style="display: none;">
<p>you can download ithere</p>
</div>
i also have a jquery function:
<script type="text/javascript">
$(function() {
$('#sendButton').click(function(e) {
e.preventDefault();
var temp = $("#backupSubmit").serialize();
validateForm();
$.ajax({
type: "POST",
data: temp,
url: 'backup/',
success: function(data) {
$(".response").show();
}
});
});
});
</script>
and in my views.py (code behind) i create a link and pass it to html page. i have:
def backup(request):
if request.is_ajax():
if request.method=='POST':
//create a link that user can download a file from it. (link)
variables = RequestContext(request,{'link':link})
return render_to_response('backup.html',variables)
else:
return render_to_response('backup.html')
else:
return render_to_response("show.html", {
'str': "bad Request! :(",
}, context_instance=RequestContext(request))
backup = login_required(backup)
my problem: it seems that my view doesn't execute. it doesn't show me the link that i send to this page. it seems that only jQuery function is executed. i'm confused. how can i make both of them to execute(i mean jQuery function and then the url i set in this function which make my view to be executed.)
i don't know how to use serialize function. whenever i searched, they wrote that:
The .serialize() method creates a text string in standard URL-encoded notation and produces query string like "a=1&b=2&c=3&d=4&e=5.
i don't know when i have to use it, while i can access to my form field in request.Post["field name"]. and i don't know what should be the data which is in success: function(data) in my situation.
thank very much for your help.
You have to get and display the data from your ajax post function, where data is the response you render through your DJango server, for example:
t = Template("{{ link }}")
c = Context({"link": link})
t.render(c):
Your JS / jQuery should become something like this:
<script type="text/javascript">
$(function() {
$('#sendButton').click(function(e) {
e.preventDefault();
var temp = $("#backupSubmit").serialize();
validateForm();
$.ajax({
type: "POST",
data: temp,
url: 'backup/',
success: function(data) {
// 'data' is the response from your server
// (=the link you want to generate from the server)
// Append the resulting link 'data' to your DIV '.response'
$(".response").html('<p>you can download ithere</p>');
$(".response").show();
}
});
});
});
</script>
Hope this helps.

live(), delegate(), and on() stop working after few ajax requests using jQuery

I have html elements with class "ajaxem" that are ment to be used in my jquery below. I also have the same for any form elements. For the first few ajax requests the jquery is attached and triggered and work properly. However, after a user logs in or registers, the returned links (which also have class="ajaxem") are not caught by jquery and not triggered.
I have tried all three implementations. and also tried to reapply them AFTER each ajax request. but none have worked.
<script type="text/javascript">
function updateajaxem() {
$(document).on("click", "a.ajaxem", function (e) {
e.preventDefault();
var action = $(this).attr('href');
//alert(action);
if (action.indexOf('register') > 0) {
$("div#logininfo").load("http://localhost/testrun/auth/register/").fadeIn();
} else if (action.indexOf('password') > 0) {
$("div#logininfo").load("http://localhost/testrun/auth/forgot_password/").fadeIn();
}
}); //end
}
</script>
<script type="text/javascript">
updateajaxem();
//$("a.ajaxem").live("click", function(e){
$(document).on("click", "input:submit", function (e) {
e.preventDefault();
var formaction = $(this).closest('form').attr('action');
var dataString = $(this).closest('form').serialize();
alert(dataString);
//$("div#logininfo").load(formaction,data);
$.ajax({
type: "POST",
url: formaction,
data: dataString,
// dataType: "json",
success: function (data) {
alert(data);
$("div#logininfo").html(data);
updateajaxem();
} // end of success
});
});
</script>
the outputted html at which the scripts stop working is below:
<div id="container">
<h1>Welcome to CodeIgniter!</h1>
Logout Home
<div id="body">
<p>The page you are looking at is being generated dynamically by CodeIgniter.</p>
<p>If you would like to edit this page you'll find it located at:</p>
<code>application/views/welcome_message.php</code>
<p>The corresponding controller for this page is found at:</p>
<code>application/controllers/welcome.php</code>
<p>If you are exploring CodeIgniter for the very first time, you should start by reading the User Guide.</p>
</div>
<p class="footer">Page rendered in <strong>1.0343</strong> seconds</p>
<div id="logininfo">You have successfully registered. Login</div>
</div>
which makes no sense since it includes the class "ajaxem" which should be caught by jquery but is not.
Since the returned link's href does not contain the words 'register' or 'password' neither of the following conditions are met:
if (action.indexOf('register') > 0) {
$("div#logininfo").load("http://localhost/testrun/auth/register/").fadeIn();
} else if (action.indexOf('password') > 0) {
$("div#logininfo").load("http://localhost/testrun/auth/forgot_password/").fadeIn();
}
so no ajax request happens.
You will probably need to account for the 'login' scenario, e.g.:
} else if (action.indexOf('login') > 0) {
$("div#logininfo").load("http://localhost/testrun/auth/login/").fadeIn();
}
...and why hard-code the URLs when they can be extracted from the clicked anchor?
if (action.indexOf('register') > 0) {
$("div#logininfo").load(this.href).fadeIn();
} else if (action.indexOf('password') > 0) {
$("div#logininfo").load(this.href).fadeIn();
} else if (action.indexOf('login') > 0) {
$("div#logininfo").load(this.href).fadeIn();
}

Categories