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.
Related
This api is api.php.
My web and api are in the one project.
I want to change page in jquery request success result.
But I don't know what to do.
Could you do me a really big favour?
Code in the here :
<pre>
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(".btn-primary").click(function(e){
e.preventDefault();
var account = $("input[name=account]").val();
var password = $("input[name=password]").val();
$.ajax({
type:'POST',
headers:{
Key: "xxx",
Version:"1.0.0",
},
url:'http://127.0.0.1:8000/api/Login',
data:{account:account, password:password},
success:function(data){
//I want to change page.
}
});
});
</script>
<code>
you can try to do like this
success:function(data){
$("html").html(data);
}
or
success:function(data){
$("body").html(data);
}
but i'm sure that javascript from those pages will not work so you will fetch only html
edit: also this will actually not change your page it will fetch html from ajax request and replace your current content with it
to make actual rederict you should use window.location.replace("https://faksesite.com/xxx.blade.php");
I'm using the HTML5 Neptune framework, to create SAPUI5 applications. At runtime my code gets inserted into the index.html file, mixed in between the code generated from the framework.
In a part of the code below the code area I control, the framework creates an ajax function I would like to modify. I would like to inject code into the jQuery AJAX success callback function. I this possible?
<html>
<head></head>
<body>
<form>
<div id="MobileContent"></div>
<input type="hidden" name="applid" value="XXX">
</form>
<script>
var JSONH, jsonh = JSONH = function(n, r) {
//Framework code
}(Array, JSON);
// framework code
...
// my code
...
// framework code
...
function getOnlineXxx(value) {
$.ajax({
type: "POST",
contentType: "application/json",
url: "neptune_ajax?ajax_id=xxx=" + value + "",
dataType: "json",
data: encodeURIComponent(modelXxx.getJSON(),
success: function(data) {
// framework code
// code I would like to execute!!!
}
});
}
....
jQuery(function() {
jQuery("form").submit(function(event) {
event.preventDefault();
return false;
});
});
</script>
</body>
</html>
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 );
I have two views main.php and details.php. In main.php there are numerous content and under each content there is a "view more" button. If somebody clicks view more an ajax call will dynamically load rest of the content from details.php which will fetch the data from database w.r.t the ID of the content. And it's a list style view in details.php.
In the header of main.php my main script file contains this code snippet to fetch data from details.php -
$('.view_more').click(function(e) {
$.ajax({
type: 'POST',
url: '/path/to/my/controller/method',
dataType: 'html',
success: function (html) {
$('#details_container').html(html);
}
});
});
Data is loading perfectly. But the problem is there is a add content button in details.php along with each content which has been loaded dynamically is not working. The content adding script is in my main.js added in main.php. But I have to add this particular jquery code snippet of adding the content in details.php, otherwise it's not working. So, whenever view more is being clicked it is returning html data along with a ....code for adding the content.... stick with it. Which is not at all desired.
How to solve this issue? Please help. Thanks in advance.
Here is the code of adding the content.
<script type="text/javascript">
$('.add_this').click(function(){
var t = jQuery(this);
var id_add = t.attr("id");
var content_category_id = t.attr("rel");
var add_content_id = id_add.substring(id_add.indexOf('_')+1);
var content_creator_id = t.attr("data-clip-id");
$.ajax({
type: "POST",
url: "/path/to/my/controller/method",
data: add_content_id,
cache: false,
success: function(response){
if(response)
{
$("#"+id_clip).text("Clipped");
}
}
});
});
</script>
I want to add again I am able to add the contents but to do so I have to embed this code snippet in details.php that I dont want to do. I need torun from my main script file.
This should work:
$(document).on('click','.add_this',function(){
var t = jQuery(this);
var id_add = t.attr("id");
var content_category_id = t.attr("rel");
var add_content_id = id_add.substring(id_add.indexOf('_')+1);
var content_creator_id = t.attr("data-clip-id");
$.ajax({
type: "POST",
url: "/path/to/my/controller/method",
data: add_content_id,
cache: false,
success: function(response){
if(response)
{
$("#"+id_clip).text("Clipped");
}
}
});
});
The title is quite self-explanatory: I need to read a HTML file through jQuery and store its contents into a string variable.
I tried using .load and $.get, but they wouldn't do what I needed.
This is the code I've tried so far, based on the comments below, but they didn't populate my template variable at all:
var template = "";
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
success: function(html) {
var twig = String(html);
template.concat(twig);
}
});
console.log(template);
AND:
var template = "";
var fileUrl = "includes/twig/image_box.twig";
jQuery.get(fileUrl).then(function(text, status, xhr){
var html = String(text);
template.concat(html);
// console.log(html); // WORKS!
});
console.log(template); // Does not work
It's weird why this isn't working. Weird for me at least. This is how I'd populate a variable in PHP so I've carried the same logic to JS. Maybe there is an alternative way?
P.S:V I've also tried all alternative ways, like concatenating with += and assigning inside the callback function to template with =, but nothing worked.
Thanks to the ones who are trying to help me!
Maybe you should try a AJAX request with $.ajax()
Check the jQuery API here
$.ajax({
url: 'yourHTMLfile.html',
type: 'get',
async: false,
success: function(html) {
console.log(html); // here you'll store the html in a string if you want
}
});
DEMO
EDIT: Added a demo!
I reread your question and I noticed you're calling the console log right above the ajax request but you forgot the ajax is asynchronous that means the page will do a request and only will set the template value when the response return with success(if it returns). So the console.log(template) don't appears because it may be not loaded yet.
var template = "";
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
success: function(html) {
var twig = String(html);
template.concat(twig);
console.log(template); // the change!
}
});
or
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
async: false,
success: function(html) {
var twig = String(html);
template.concat(twig);
}
});
console.log(template); // the change!
You can try this:
//as you see I have used this very page's url to test and you should replace it
var fileUrl = "/questions/20400076/reading-a-file-into-a-string-in-jquery-js";
jQuery.get(fileUrl).then(function(text, status, xhr){
//text argument is what you want
});
and if it won't work try if your browser can open the file. if it could you'd better try ajax method in jQuery if not you might have some problems regarding permissions or somethings like that in you application server.