Ajax submit script global - javascript

I have this piece of code. this code has to be inside every new loaded ajax page. cause if its outside, it wont work.
example:
<div> Loaded form here , including the script </div> <- works
<div><div> Loaded form here , </div> script is here </div> <- do not work
Q: How can i make it able to work without the need to put this script on every of my ajax pages?
code:
<script>
$("form").on("submit",function(e) {
e.preventDefault();
var btn= $(this).find("input[type=submit]:focus");
$('<input>').attr({
type: 'hidden',
name: btn.attr('name'),
value: btn.val()
}).appendTo('form');
action = $("form").attr('action');
$.post(action, $(this).serialize(), function(data) {
$(".main_center").html(data);
});
return false; // prevent normal submit
});
</script>
if the script is in the loaded file, it will proccess correctly. but if it isnt, it will just refresh the page. cause the loaded file will not find the script that is ment to be used.

Is your script in the .main_center div?
If so then the returned data will replace it - hence you need to include your script in the data returned in your ajax call.
Putting the script into a common js file included in your footer works (I've done it myself) so the fault is almost certainly with the structure of your document and the way you are replacing content.
Will need to see a more of the actual code to properly advise you.
[Edit] Have you tried
<div class="main_center">
<div><form> ....</form></div>
</div>
<script>
$(document).on("submit","form", function(e){ ... });
</script>
This binds the script to the document and calls it whenever a form is submitted, including forms loaded after the page has been generated

Related

Dynamic Follow Up Page with Marketo Forms

We are using a script that allows us to to change the follow up URLS of a form dynamically so we can use the same form across multiple assets but have different follow up pages.
The issue is that script only works when it loads the form itself rather than bringing it in via the visual editor. If we adjust the code as per the instructions on the developer site to make it work with the visual editor, it stops working.
We need to bring the form in via the editor because we have another script that only works on forms that are loaded in that manner. This script opens the follow up page in the parent window rather than the iframe.
Can you provide any suggestions?
Here's the code for the script:
Dynamic follow up URL:
<script type="text/javascript">// <![CDATA[
MktoForms2.whenReady(function(form){
//Add an onSuccess handler
form.onSuccess(function(values, followUpUrl){
//Take the lead to a different page on successful submit, ignoring the form's configured followUpUrl.
location.href = "http://solutions.healthcaresource.com/2346-staff-assessment-thank-you.html";
//return false to prevent the submission handler continuing with its own processing
return false;
});
});// ]]>
Use document.getElementById('iframe_id').src (given an iframe with an id of 'iframe_id'):
location.href = "http://solutions.healthcaresource.com/2346-staff-assessment-thank-you.html";
To this
document.getElementById('iframe_id').src = "http://solutions.healthcaresource.com/2346-staff-assessment-thank-you.html";
You can add Marketo variable to be able to give dynamic followup link.
Add following meta for variable, and use it in script. Code will be like this in your landing page.
<meta class="mktoString" id="ThankyouPage" mktoName="Follow-up Page" default="Add dynamic followup page here" allowHtml="false">
<script>
MktoForms2.whenReady(function (form) {
form.onSuccess(function(values, followUpUrl) {
location.href = ${ThankyouPage};
return false;
});
});
</script>

Using $.getScript (jquery): code is not executed

I am working on updating my website, which now uses an AJAX engine. My engine works well, up-to-hand for some reason some pages do not execute javascript, let me explain: when the anchor change I use $.get for data recovery. The pages have this structure:
title
h1
script1.js,script2.js,etc.js
style1.css,style2.css,etc.css
<!--there's the page's content-->
It appears reload the page solves the problem, but i don't understand what is different. In the previous code, the engine runs successfully, reloaded or not:
$.getScript("script1.js");
$.getScript("script2.js");
$.getScript("etc.js");
In addition, a php generated script contains user's current state under an Object form:
$(function(){
user = new Object();
user.id = user.logged = <?php echo $user->getId();?>;
user.nick = "<?php echo $user->getNick();?>";
user.mail = "<?php echo $user->getMail();?>";
user.logout = function(){
};
});
The $.getScript request is successful, but the user object is not changed. The script, however, has yet been modified. And it don't works from console too.
The update is currently online at v2.wawolf.com, you'll find everything you need.
Hotlink: Engine's code
I just solved my problem: when all document is loaded, $(function(){}) will not work again, so calling a script which uses $(function(){}) will no get run. I removed it from all my secondary-called scripts and now all works perfectly!
it might just be a loading order issue.
try encapsulating the JS loading in an onload function
$(window).load(function(){
//get script loads here
}
or
$(document).ready(function() {
//get script loads here
}
Sometimes I use one inside the other for dynamic JS script that needs to be loaded last.

Add HTML/JS code to external web page after it has loaded

Is it possible to load an external web page like 'http://www.google.com' and then append my own HTML/JS code to the end of it (e.g. to run a function)?? Surely there is a way to load an external page then add a little bit of my own code after it? Something like this:
<html>
<script>
document.location.href="http://www.google.com/"; //Load external page
function myscript() {
...blahblah
}
</script>
<button onclick="myscript();">Click me</button>
</html>
I'd like that button to be at the bottom of the external page. Please do not suggest parsing methods in php. I've tried doing this by parsing the page first in php then appending my own script to it and echoing as I described here:
Append HTML to page after redirect
This works for simple pages where there are no re-directs or when the final external page can be parsed properly. The problem is that I can't properly parse the external page. The code that is parsed doesn't seem to function without the code from previous pages (before the re-directs). I need to do this without parsing/scraping/crawling.
Thanks!
EDIT: I've tried displaying the external page in an iframe as suggested by Amadan:
<script>
function myscript() {
...blahblah
}
</script>
<iframe src="http://www.google.com/"></iframe>
<button onclick="myscript();">Click me</button>
</html>
However, in firefox it just displays a blank box but in IE it says "This content cannot be displayed in a frame: To help protect the security of information you enter into this website, the publisher of this content does not allow it to be displayed in a frame."
Any way I can get around this?
EDIT 2:
I've included jquery and the cross domain script here (https://github.com/padolsey/jquery.fn/blob/master/cross-domain-ajax/jquery.xdomainajax.js). This is the code I'm using now to get the contents using ajax. How would I go from that to actually displaying the content in the webpage? Sorry I'm really bad with ajax/jquery!
function test () {
$.ajax({
url: 'http://www.google.com/',
type: 'GET',
success: function(res) {
var content = $(res.responseText).text();
alert(content);
}
});
}
You can't append anything to a page you don't control except by installing a browser extension (which then works only for the clients where your extension installed).
You can include the contents of a page you don't control inside your own page (in two main ways: client-side iframe and server-side pull), but you seem to be saying this is not what you want.
Try something like this:
var html = '';
$.ajax({
uri: 'http://ya.ru',
method: 'POST',
success: function(data){
htmlx = data;
}
});
About manipulating html inside an variable
var test = $("<div/>");
test.append(html);
test.find(".innertest");
// When I'm ready to append it..
$('#container').append(test);
If it doesn't work, you can use another page on your server for getting a remote page and use ajax to request it.

Dynamically loaded javascript doesn't work second time loaded

I am working on a webpage that uses a JQuery UI dialog (in modal mode) to display a form that is dynamically generated using Django. The basic flow is:
the user clicks a button
jquery (using AJAX) issues a get request that returns the html for the form which is then used to fill the dialog
The html contains a script tag that handles some UI on the form which loads fine and works as expected
the user than fills out the form and clicks "Done" and the form is submitted.
The issue comes in when the user makes an error on the form. The server responds to the post request (that submits the form) with the original form (including the script) modified to show the errors. This second time the script is loaded it gets a "Uncaught ReferenceError: $ is not defined (anonymous function)" The script is exactly the same as before when it worked fine. To be clear throughout this entire process the page is never refreshed.
Here is the gist of the javascript that takes care of the modal:
var add_container = $("#add_container");
add_container.dialog({...})
function show_form(form,response_func) {
add_container.html(form);
add_container.dialog("open");
$("#add_form").submit(function (event) {
return submit_form($(this),response_func);
});
}
function submit_form(form,response_func) {
add_container.append('<p>Adding...</p>');
//this is a trick to upload a file without reloading the page
form.attr('target','upload_target');
$('#upload_target').load(function() {
var response = $('#upload_target').contents().find('body').html();
add_container.dialog("close");
resp_obj = $(response)
if (resp_obj.is('form')) {
//***this is what reloads the form when there is an error
show_form(response,response_func);
} else {
response_func(resp_obj);
}
});
}
$('#add_link').click(add_link);
function add_link() {
$.get('/add_link', function(data) {
function add_response(response) {
//handle successful submission
}
show_form(data,add_response);
});
}
//...more stuff that is not important
This is the gist of the html returned from /add_link
<script type="text/javascript" src="/scripts/add_form.js" ></script>
<form id="add_form" enctype="multipart/form-data" action="/add_link/" method="post">
<!-- Dynamically generated form here !-->
</form>
The add_form.js is a pretty standard javascript file that uses jQuery. Its starts with $(document).ready(function () {...} ) and the first $ is where the ReferenceError occurs
The form needs to be dynamically generated based on what is clicked so I can't just put everything statically on the page. The script is not dynamically generated so it doesn't necessarily need to be dynamically loaded but I wasn't sure how to keep it in its own file, and also only have it run when the form is loaded. I am open to suggestions of alternative ways to accomplish the same effect.
Your form action is pointing to a different relative path to the one containing the jQuery framework script, etc.
<script type="text/javascript" src="/scripts/add_form.js" ></script>
<!-- src="/scripts" -->
<form id="add_form" enctype="multipart/form-data" action="/add_link/" method="post">
<!-- action="/add_link" -->
To make sure it's loading the framework after the form submission, just use something like the developer tools on your browser and check the head tag for the jQuery script src. Is it still there?
Thanks to MelanciaUK I realized that when I submitted my form to the iFrame the response was getting sent first to there where the script would run and error because the iFrame is treated as its own page and doesn't have access to jQuery loaded on the main page.
I decided to solve the problem by eliminating the dynamic loading of the add_form script and simply load it when the page loads just like all my other scripts. I created a custom jQuery event (using .trigger) in order to only have the script run when the add form is opened. This worked exactly the way I wanted it to.
Hope this helps anyone with a similar problem. If you have any questions feel free to ask!

How to realize screens / views with JavaScript / Jquery easily?

I'm sure I'm missing something pretty basic, but I have just started to get myself up to speed on jQuery and Javascript programming. Previously I was doing server side programming with PHP.
I'm now in the middle of creating a prototype for HTML5 webapp, where I would like to have different screens. Now with PHP that was pretty easy, I could just used server side templates like Smarty and be done with it.
However to make my app more webapp like, I would like to dynamically change between screens without having to reload the window.
I have looked into several options that might be anwsers to my question, but I'm not sure whether I'm on the right track.
I have checked for example JsRender, JsViews or even the pure jquery load command.
But what I'm not sure is whether these things would allow me to have something like this:
HEADER_PART
MAIN_CONTENT
FOOTER_PART (also contains links to common JS files that I use)
I would like to dynamically update the MAIN_CONTENT part. Currently my application is only one page, and all my custom logic that belongs to that page is in one JS file. In this JS file, I use a simple $(function() { ... to load my page, so whenever it gets loaded, parts of my page get updated asyncronously. This is fine, since all my blocks in this certain page would have to be loaded when that one page gets loaded.
But what if I have a link, like main.html#otherscreen, and when I click that screen, I would like to change my MAIN_CONTENT and also run another page load specific JS that handles blocks on that other screen, not the first page?
I know I could still use probably server side templating and load my pages using AJAX requrests, but again, not sure whether that is the right approach.
Could you please enlighten me? :)
Thanks & best regards,
Bence
Check out jQuery.load(). Using this function you can dynamically load content into a div on the page, which is what I think you want to do. Just find the div on the page you want to load content into and call
$('#mydiv').load(url, data, function(response){
//do something once it's done.
});
Per your comments...
This is actually very easy. .load() should replace the content in the div (I think. If not, just call .empty() first). Of course you could get fancy and add effects, like
function changePages(url) {
$('#mydiv').fadeOut('fast', function() {
$(this).load(url, function(response){
$('#mydiv').fadeIn('fast');
});
});
}
To handle things like the hash in the URL, in your click event you have to make sure you first call e.preventDefault():
$('#mylink').click(function(e){
e.preventDefault(); //e is a jquery event object
var link = $(this);
var hash = link.attr('href'); // get the hashtag if the href is '#something'
changePages(someUrl + hash);
});
For dynamic loading of data into the page without changing your header and footer you should use jQuery's AJAX function. It allows you to post requests to the server and receive data back without reloading the page. A simple example would be something like:
<html>
<head>
<title>Example</title>
<!-- Assuming jQuery is already referenced -->
<script type="text/javascript">
$('span.buttonish').click(function(){
$.ajax({
// The URL can be a file or a PHP script of your choosing
// it can also be pure HTML without the <html> tags as they
// are already in your file
url: 'path/to/the/file/that/return/data',
success: function(receivedData) {
// The received data is the content of the file or the return
// data of the script and you can use it as you would with any data
$('#content').html(receivedData);
}
});
});
</script>
</head>
<body>
<div id="header">
<!-- Something -->
</div>
<div id="content">
<span class="buttonish">Click me to change the text... </span>
</div>
</div id="footer">
<!-- Something -->
</div>
</body>
<html>

Categories

Resources