Adding an external <script> with data parameters after ajax request - javascript

I need to add a < script > tag with external src and with data-*="" parameters inside a < form >. It is ok if you just add it in page. But if I do it after an ajax request, script reports it can't find data- parameters, and it is outside needed html elements.
I read that jQuery on .append() somehow rearranges < script > tags, and put them in the end (outside needed elements), and looses data- attributes.
Is there any other way to append a script after ajax request with needed data- parameters?
I tried
$('<script>').attr(/*all data params*/)
but it does not work.
Please help

You need to make sure you get the result from your Ajax request in the right place. As this is an asynchronous operation, it might be that you're data parameters are not populated at all.
The following code sends a request when you click the button and gets the result in the callback function :
function callback(data) {
// Got result from AJAX, play with DOM + jQuery here
console.log("callback called, data : ", data);
$("#callbackResultId").html(JSON.stringify(data));
}
$(document).ready(function(e) {
$("#textAjaxButtonId").click(function(){
$.ajax({
url: '/echo/json',
type: 'POST',
dataType: "json",
data: {
json: JSON.stringify({
'attr': 'value'
})
},
success: function(data, status, xhr){
callback(data);
}
});
})
});
http://jsfiddle.net/uemaft67/
The callback function is the place where you would get your Ajax response, and therefore build the DOM nodes along with the needed attributes.
Hope this helps!

Related

script doesn't load after ajax response

I was trying to make an ajax call and show an html part inside a div class. For that i used the following way.
$.ajax({
type: "get",
url: "{{url('searchByCheckbox')}}",
dataType: 'html',
success: function(html)
{
$(".infinite-scroll").html(html)
}
});
But the problem is there is a script inside that html part which i wanted to load when i make first ajax call it's not loaded but for the second one it's loaded the script.
suppose the html response like this :
<script>
alert()
</script>
// html
How do i make it work?
I put the script above the html page which i'm getting as response.
(those who are marking the Question as duplicate should read at least what i want and what they wanted )
Im sure that the error is happening because of the script, because you are closing the </script> tag inside the html.
The best solution is to return the data from your ajax call as a json
To do that you should:
1- add a dataType to your ajax parameter as the below:
$.ajax({
type: "get",
dataType: "json",
2- In the php file handling the ajax call, you must resurn the values as a json as below:
Assume that currently you are doing the following:
echo $html
You should change it to match the below:
$retArr = array(
"html" => $html, //Your html code without the javascript function
"jsFunc" => $jsFunc //Your java script function parameters
) ;
echo json_encode($retArr) ;
And then your ajax success must be as the below:
success: function(data)
{ //You can access all the object parametes by calling the object name `data` followed by a dot `.` and then by the parameter key
data.jsFunc // Your javascript function params
$(".infinite-scroll").html(data.html) ;
}

Refresh a DIV on ajax success

I have a page with has a heading say :
<div class="something"><? some php code ?></div>
In that page I also have an ajax doing a job like:
<script>
$(document).ready(function () {
$(document).ajaxStart(function () {
$("#loader").show();
}).ajaxStop(function () {
$("#loader").hide();
});
});
$('#link').on('click', function(e) {
e.preventDefault;
var href = this.getAttribute('href');
$.ajax({
url: href,
success: function(text) {
alert("Added Succesfully");
}
});
return false;
});
</script>
Now in the success in ajax i also want to refresh the div i mentioned. Only refresh as it is attached to PHP which will fetch data from an external API. Is this possible ?
You could put your php code in an external file and reload your div by calling JQuery load method:
$("#something").load("mycode.php");
I hope it helps you.
link
$.ajax({
dataType: "json",
url: "http://www.omdbapi.com/?i=tt0111161",
success: function (data) {
console.log(data);
$("#movie-data").append(JSON.stringify(data));
With the append function you can insert the data from the ajax call into a div. explanation and example
The append() method inserts specified content at the end of the selected elements.
Tip: To insert content at the beginning of the selected elements, use the prepend() method.
Or maybe this answer can fix your issue
or you can take a look at the jquery load function
Load data from the server and place the returned HTML into the matched element.
This method is the simplest way to fetch data from the server. It is roughly equivalent to $.get(url, data, success) except that it is a method rather than global function and it has an implicit callback function. When a successful response is detected (i.e. when textStatus is "success" or "notmodified"), .load() sets the HTML contents of the matched element to the returned data.

Jquery caching data-* attributes

In my HTML page , I have the following div:
<div id="notification"></div>
An ajax call add some attribute to that div after receiving successful response.This is what the ajax success does:
$("form").on("submit", function (e) {
e.preventDefault();
$.ajax({
dataType: 'json',
type: "POST",
url: "/dummy/url",
data: {Redacted},
success: function (data) {
$('#notification').attr({'data-status': data['status'], 'data-message': data['message']});
$('#notification').click();
$('#notification').removeAttr("data-status data-message");
}
});
});
The problem is the attributes of #notification does not go away after using removeAttr. I mean it removes the attributes from the page, but remains as cached. Thats why I am getting same data-message on every click though the server returns different data-message.
For example:
In my first ajax call, server returned:
{"status":"success","message":"Invitation sent"}
In this case the #notification triggers and shows me data-message="Invitation Sent". But in my second call server returned:
{"status":"danger","message":"Invitation sending failed"}
But #notification shows data-message="Invitation Sent" again.
Any suggestion for me on this? How can I remove the cached data? Or is there any alternative of what I am doing up there?
Instead of using attribute, use data(). If you had already used data() to read the attribute it is going to be cached as a property of the element.
success: function (data) {
var elementData = {
status: data['status'],
message: data['message']
}
$('#notification').data(elementData);
$('#notification').click();
// not sure why it needs to be removed here
// if it does use `removeData()
}

jQuery AJAX reload specific div

I have the following code, as part of a code to add some value to a database.
After executing the $.ajax succesfully, I want a specific div (with class 'lijst') to be reloaded with the refreshed data.
$.ajax({
url: \"frontend/inc/functions/add_selectie.php\",
type: \"POST\",
data: ({ 'p_id' : p_id, 'v_id' : v_id, 'pd_id' : pd_id }),
cache: false,
success: function()
{
$(\".lijst\").hide().fadeIn('slow');
}
});
However, with this solution, only the div is refreshed, not the actual PHP variables that are specified in there. When I refresh my browser manually, the values are updated.
How can I refresh the div and also update the variables?
According to the jQuery.ajax documentation, the function signature of "success".
Type: Function( PlainObject data, String textStatus, jqXHR
jqXHR ) A function to be called if the request succeeds. The function
gets passed three arguments: The data returned from the server ...
So in other words:
success: function(data) {
$(".lijst").html(data).hide().fadeIn('slow');
}
Actually, the PHP variables specified in the html are worked at the sever part. PHP variables in the html have replaced by the string of there value when it is ready to be sent to the browser. And your ajax request will cause PHP to update database. So when you have sent the request and then refresh the page, PHP will replace the varables in the html again.
According to this above, your ajax request and the server repsonse are not aware of the PHP variables's existence. So you must update the content yourself.
Maybe you will do something like this:
success: function(data) {
$(".lijst").hide();
$(".title").html(data.title); // $(".title") may be a tag that surround a PHP variable
$(".content").html(data.content); // the same as $(".title")
$(".lijst").fadeIn('slow');
}

Can ajax call on return add new javascript function to the page?

I have a jQuery ajax call that returns html of a table. Now I need to let user to do some javascript action on the table.
Can the return ajax response contain the javascript code or do I have to load the javascript code in the page on the first load of the page?
The user has the option of triggering the 'new' javascript. It doesn't have to triggered on ajax call.
To answer the actual question, the return response can contain the script. Simplest is to place it after the html, as the ready event has already fired in page it is being loaded into
You can use the success (or other event) callbacks provided with jQuery .ajax() to perform this JS action. Something like this:
$.ajax({
success: function(){
// Perform JS action
}
}
The jQuery API lists all such event callbacks available for AJAX calls. Check this for more info.
The returned ajax response can contain javascript code as a string. Then you can eval(response).
If you want to request a script with ajax that will be run when retrieved, then you can use jQuery's getScript() method to retrieve it and then execute it.
Per the jQuery doc, getScript() is a shorthand for:
$.ajax({
url: url,
dataType: "script",
success: success
});
Which shows that jQuery's ajax command will handle a returned script for you automatically if you set the data type appropriately.
You can make your request a variable and extend upon it after the set up.
// Make the request to the server
var dataID = $("#WhatINeedForAParameter").val();
var request = $.ajax({
url: "PageOrControllerOrWebApi/MethodName",
type: "POST",
data: { id : dataID },
dataType: "json"
});
// When the request is done process
// what you need done
request.done(function(msg) {
alert('You got this ' + msg);
});
// If the request failed you can
// see what the problem was and
// handle the situation accordingly
request.fail(function(jqXHR, textStatus) {
alert( "Your request failed: " + textStatus );
});
you can do it using success callback i think this can be a way please try
$.ajax({
.....,
.....,
success:
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = url;
$("#tableID").append( script );
});
i hope it should help.

Categories

Resources