How to keep consistency between two js files? - javascript

I have two html files (for add and edit) which contains js codes. These two files are identical except few js lines in its functions. Actually I don't like to have common code for both files. Is there a good way to handle this kind of situations ?
Example:
(file one)
<html>
<title>title goes here</title>
<javascript>
$('#button1').click(function () {
$.ajax({
type: "POST",
url: '/admin/test/checkcode',
data: {code:code, id:id}, // in here there is an id
async: false,
success: function(data){
}
});
}
</script>
<body>
</body>
</html>
(file two)
<html>
<title>title goes here</title>
<javascript>
$('#button1').click(function () {
$.ajax({
type: "POST",
url: '/admin/test/checkcode',
data: {code:code}, // in here there is no id
async: false,
success: function(data){
}
});
}
</script>
<body>
</body>
</html>

You may want to try putting that JavaScript code into a separate file. That way, you can just include the single JavaScript file into each of those pages... and only have to make changes to that one JavaScript file.
For reference, here is a way to include a JavaScript file:
<script type="text/javascript" src="javascript_file_here.js"></script>
Inside of that JavaScript file, there could be some type of basic function that takes parameters for that data value that is used in the $.ajax() call. For example, something like:
function example(data1, data2) {
// your code here
// then just check for data1 and data2 (etc.)
// to see what to include in the `data:`
}

Related

How can I include the content of PHP files in output generated by JavaScript?

I have a JS script that scrapes a bit of data and outputs the result to the screen. That works fine. What I now need to do is wrap that output in some pre and post content php files for formatting purposes, and I can't seem to get it to work.
Here's where the script stands now:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" name="viewport">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/main.css">
</head>
<body>
<img id="loading-gif">
<script>
$('#loading-gif').hide();
$(document).ready(function () {
$('#loading-gif').show();
$.ajax({
url: "https://aajumpseat.com/dev/include/pre.content.php'); ?>",
type: 'GET',
dataType:"json",
success: function(data) {
pre = JSON.parse(data);
document.write(pre);
}
});
$.ajax({url: "https://aajumpseat.com/dev/scrape/getSegments.php"}).done(function (data) {
$('#loading-gif').hide();
output = JSON.parse(data);
document.write(output);
});
$.ajax({
url: "https://aajumpseat.com/dev/include/post.content.php'); ?>",
type: 'GET',
dataType:"json",
success: function(data) {
post = JSON.parse(data);
document.write(post);
}
});
});
</script>
</body>
</html>
The second ajax call works perfectly and outputs the result to the screen, which is what I want. What I would like to do is place the contents of pre.content.php before the result and the contents of post.content.php after the result so that the result is properly formatted.
There is some php being executed in 'pre.content.php is addition to the formatting html, while 'post.content.php contains only the closing body and html tags.
If need be, I can hardcode the required html into the above script, but if someone has an elegant, or not so elegant, solution on how to include these two files I'd appreciate it.
Thanks.
There's a function specifically for this called $.load(). It's always better to have a <div> with id and then use .innerHTML instead of using document.write().
$(function () {
$("#stuff").load("/path/to/api/call");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="stuff"></div>
If you have got multiple calls, that's fine too. Just have multiple containers.
$(function () {
$("#stuff").load("/path/to/api/call");
$("#pre").load("/path/to/api/code");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="stuff"></div>
<pre id="code"></pre>
One thing to note is that, $.load() fires an AJAX GET request.
place the contents of pre.content.php before the result and the contents of post.content.php
Don't use document.write. It gives you no control over where in the document you write anything. Instead, define the elements where you want to write your output:
<div id="pre-output"></div>
<div id="main-output"></div>
<div id="post-output"></div>
Then write your output to those specific locations:
pre = JSON.parse(data);
$('#pre-output').html(pre);
(Or maybe .text(pre)? It's strange to me that you're outputting raw JSON...)
******* SOLUTION *******
My main php has multiple tasks, so for this particular task the PHP is:
$output = " <div id='loading-gif'><img src='images/loading3.gif';></div>
<div id='main-output'></div>
<script>
$('#loading-gif').hide();
$(document).ready(function () {
$('#loading-gif').show();
$.ajax({url: 'https://aajumpseat.com/dev/scrape/getSegments.php'}).done(function (data) {
$('#loading-gif').hide();
output = JSON.parse(data);
//document.write(output);
$('#main-output').html(output);
});
});
</script>
<div class='bottom-border'></div>
";
and further down the page I have:
include('include/pre.content.php');
echo $output;
include('include/post.content.php');
And it is perfect.

PHP & JS - append html and scripts on page

I'm using an ajax call to append a MVC partial view with some styles sheets and script files to my php page.
However it is not appending de <script> tags. I already checked my HTTP request on the network and it really brings those tags.
My code:
$.ajax({
type: 'POST',
url: 'http://localhost:63322/MyController/MyAction', //external url project
data: JSON.stringify(parameters),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
crossDomain: true,
processdata: true,
headers: {
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Headers": "*"
},
success: function(result){
$(".pageContainer").html(result);
},
error: function(er){ alert('Error'); }
});
On ajax success function I already tried:
to use $(".pageContainer").empty().append(result)
to separate the script tags and add to <head> like this:
var elems = $(result);
var scripts = $.grep(elems, function(e){
try{
return e.tagName.toLowerCase() == "script";
}catch(er){ return false; }
});
var remainElems = $.grep(elems, function(e){
try{
return e.tagName.toLowerCase() != "script";
}catch(er){ return false; }
});
$.each(scripts, function(){ $('head')[0].appendChild(this); });
$(".pageContainer").append(remainElems);
to give some time before appending with setTimeout(function(){ $(".pageContainer").html(result); }, 1000);
to change <script> tags to <link type="text/javascript" src="http://someurl.com" rel="tag"/> and it was appended but the code wasn't executed
But nothing works.
What is wrong? What I'm missing?
My PHP page uses jquery-1.8.3 and jquery-ui-1.9.2.custom. This is the problem?
NOTE:
My question is very different from that on: Executing inside retrieved by AJAX
If you read both you will see they are very different. I already readed what and noticed that.
Solved. I don't know why but seems jquery-1.8.3 don't performs the insertion of the <script> tags to the html code dynamically.
I changed
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
to
<script type="text/javascript" src="js/jquery-1.10.2.js"></script>
and now it works.

load json data into js

I am learning how to load json data into .js file. I have created a employee.json file. I saved my js and json file and on the desktop. What I trying to do is to put all the id in json files into an array in the js. I do not know what could be wrong. Hope someone could help me out. Thank you in advance.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSON with jQuery</title>
</head>
<body>
<p id="demo"></p>
<h1><h2>
<script src = "<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
var res = [];
$.ajax({
url: 'employee.json',
dataType: 'json',
type: 'get',
cache: false,
success: function(data) {
$(data.people).each(function(index, value) {
res.push(value.id);
});
}
});
document.getElementById("demo").innerHTML = res.toString();
</script>
</body>
</html>
{
"person": [
{
"id" : 1,
"firstName" : "Lokesh"
},
{
"id" : 2,
"firstName" : "bryant"
}
{
"id" : 3,
"firstName" : "kobe"
}
]
}
Error 1: Typing error. <script src = "<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>. You mistyped the src of the script, accidentally adding another another <script> start tag.
Error 2: Misplaced statement. document.getElementById("demo").innerHTML = res.toString(); should be placed in the success callback function, so it will be executed only after the server responds. If it executes prematurely, res will still be [].
Error 3: type: 'GET' should be method: 'GET', according to the docs (though 'GET' is default so you don't need to explicitly write this).
Use this:
<p id="demo"></p>
<h1><h2>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
var res = [];
$.ajax({
url: 'employee.json',
dataType: 'json',
method: 'get',
cache: false,
success: function(data) {
$(data.people).each(function(index, value) {
res.push(value.id);
});
document.getElementById("demo").innerHTML = res.toString();
}
});
</script>
You can't use the local json to read. it gives cross origin request failure. so deploy both the files (html and json) into a we server and execute. or place the json data onto some web url(http://somesite/myjson) and then request that url and see.
First of all, the JSON shouldn't be existed as in physical "file". It has to be generated by a backend language / web service etc. The JSON tags inside a manually created "file" have high chance of data invalidity upon parsing.
Solution
Use a Web Service to generate valid JSON output. And from Javascript end, use:
JSON.stringify( data );

javascript(ajax) and php working together?

I have a problem that my Js file is not recognizing a php variable built by ajax.
Here is an example:
index.php:
<script src="js.js">
</script>
<?
include('build.php');
<div id="brand">
<?
echo $brandinput;
?>
</div>
//....more code
?>
build.php:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
crossOrigin: true,
dataType: "jsonp",
type: "GET",
url: "getBrand.php",
data: info,
success: function(data){
$("#result").html(data);
}
});
</script>
<?php $brandinput='<div id="result"></div>';
?>
js.js:
$(document).ready(function(){
//dosomething with div's in index.php
}
So, I'll try to explain this in the easiest way. My index.php includes a build.php which as you can see calls ajax to retrieve data from another server. This data is located in a php variable ($brandinput) which will contain many <div>,<input>,... etc. Then index.php echo $brandinput, showing all the content of the variable. But I have a js.js which change appearances in div's, input's, etc.. and is this js which is not recognizing the content of the variable $brandinput.
I'd like to know if you have more ideas or what am I doing wrong...
All the code is working well, I tested many times (except for what I said before)
The ajax call work well and Index.php displays $braninput correctly.
p.s. $brandinput is something like this:
<div id='BlackBerry'><img src='..\/images\/supporteddevices\/blackberry-logo.jpg' alt='blackberry-logo' width='75'><br><input class='adjustRadio' type='radio'
and yeah it works well too.
Actually this is how it supposed to be working, what you need to do is to wait for the ajax request to finish first before executing the functions in js.js
try this way
// in build.php
$(document).ready(function () {
var promise = $.ajax({
crossOrigin: true,
dataType: "jsonp",
type: "GET",
url: "getBrand.php",
data: info,
success: function (data) {
$("#result").html(data);
//dosomething with div's in index.php
}
});
});
or (assuming js.js is loaded after the script within build.php, or js.js has to be loaded after it)
// in build.php
$(document).ready(function () {
var promise = $.ajax({
crossOrigin: true,
dataType: "jsonp",
type: "GET",
url: "getBrand.php",
data: info,
success: function (data) {
$("#result").html(data);
}
});
});
// in js.js
$(document).ready(function () {
promise.then(function (data) {
//dosomething with div's in index.php
});
});
P.S
$brandinput just hold the string whatever assigned to, and will never be changed with ajax request, where ajax success handler just manipulate the rendered DOM directly in the client side.
You can try moving your <script> tag to after your php codes like this:
<? include('build.php'); ?>
<div id="brand">
<? echo $brandinput; ?>
</div>
<script src="js.js"></script>
//....more code
On a slightly different note, you should consider avoid embedding/intermixing PHP codes with HTML and Javascript. Take a look at this post for better ways way "passing data from PHP to Javascript".

How to get plain xml from file

I search for a method to get plain xml(with tags ect.) from a file and save it so the localStorage.
I found a few opportunities, but every one of them returns the xml without tags. I prefer jQuery to do this...
I tried $.get, $("").load() and AJAX but I don't get it. I just want to save the whole xml as string into the localStorage and read it out later (and work with it).
Does anyone have a idea?
Regards
You can use:
$.ajax({
url: 'http://example.com',
dataType: 'text',
success: function (data) {
localStorage.setItem('xml-content', data);
}
});
This will provide you the XML document as plain text and save it to the localStorage.
Here is a full solution:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<pre id="output">
</pre>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function setXML() {
$.ajax({
url: 'test.xml',
dataType: 'text',
success: function (data) {
localStorage.setItem('xml-content', data);
getXML();
}
});
}
function getXML() {
var xml = localStorage.getItem('xml-content');
$('#output').text(xml);
}
setXML();
</script>
</body>
</html>

Categories