Jquery caching data-* attributes - javascript

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()
}

Related

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

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!

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 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');
}

How to pass form data to PHP via AJAX call (CodeIgniter Framework)

I have the following HTML structure:
<form method="POST">
Name : <input id="asgname" type="text"> <br>
Description : <input id="asgdescription" type="text"> <br>
Save
</form>
I want that on clicking the save button, the form values are sent to the server via AJAX call.
For that, I've attached the click event via following command
$("#asgsave").click(save_assignment);
save_assignment is also a javascript function defined as follow:
function save_assignment() {
return $.ajax({
type: "POST",
url: "<?php echo base_url();?>index.php/user/save_assignment",
data: $('form').serialize(),
success: function(response) {
alert('Form was submitted');
},
error: function(error) {
alert("Error");
}
});
}
The above is not working. So I tried the following approach as well:
function save_assignment() {
var formvalues = {
name : $('#asgname').text(),
descripion : $('#asgdescription').text(),
};
return $.ajax({
type: "POST",
url: "<?php echo base_url();?>index.php/user/save_assignment",
data: {values : formvalues},
success: function(response) {
alert('Form was submitted');
},
error: function(error) {
alert("Error");
}
});
}
But this is also not working.
Can anyone please guide me as to why are the above methods not working and what is the correct way to do so ?
EDIT-1 :
By not working, I mean: in the first case ($('form').serialize() approach) the data is not being sent to the server. I checked it via chrome and firefox debugger that there was no post data sent corresponding to the form.
And in the second case, empty values are being sent. i.e. the post data sent to server is like following:
values[name]
values[description]
i.e. the above values are empty.
EDIT-2:
By logging on firephp, I have confirmed that the save_assignment PHP script is BEING EXECUTED. Thus ajax call is working fine but it is NOT passing the data correctly.
Try to use event.preventDefault() like,
$("#asgsave").on('click',function(e){
e.preventDefault();
save_assignment();
});
or use return false after ajax call like,
function save_assignment() {
//ajax code
return false;
}
you have to use callbacks in the success function, cause ajax is asynchronously
edit
have you already tried console.log('foo'); in your function? so you are able to test if the function is called ;)
edit 2
add the following line to your ajax options
dataType: "json"
You could just serialize your form values:
http://api.jquery.com/serialize/
However, looking over your code, I'll take a stab and guess that you are not getting and sending your values properly. Using jQuery, you grab a value from input like so:
$('#idofInput').val();
http://api.jquery.com/val/
You are doing: $('#asgname').text()
Format your data properly: data : { foo : 'bar', bar : 'foo' }
One last guess, make sure your CodeIgniter config has CSRF protection disabled, otherwise you would need to pass: $this->security->get_csrf_token_name() & $this->security->get_csrf_hash();

Access DOM elements after ajax.load

I am inserting the HTML response from an AJAX call into my page, but then when I try to access those elements after they have been created, it fails..
This is how i retrieve and insert the HTML:
$.ajax({url: 'output.aspx',
data: 'id=5',
type: 'get',
datatype: 'html',
success: function(outData) {$('#my_container').html(outData);}
})
The outcome HTML, which is inserted into the <div> (id = my_container) looks like:
<div id="my_container">
<ul>
<li id="578" class="notselected">milk</li>
<li id="579" class="notselected">ice cream</li>
<li id="580" class="selected">chewing gum</li>
</ul>
</div>
...and afterwards, when I try to access any of the <li> elements using queries like:
$('#my_container li:first') or
$('#my_container ul:first-child') or similar, nothing gets selected.
I am using the Listen plugin to detect any click events on the <li>elements and it works... But i couldn't figure out how to detect if the div is populated with the output HTML and accordingly change one of the <li>'s class for example...
$(document).ready does not work either...
Imagine I need to change the css style of the second <li>.. what is the solution to this?
How are you checking to see whether your AJAX call has completed? Because it's asynchronous, the elements will not, of course, be available to the code which executes immediately after your $.ajax(…) call.
Try manipulating those elements from within the success function or in other code which is called from there — at that point, you will know that the content is available.
Are you sure your actual request is successful? If nothing is selected, the most probably reason is that nothing was actually inserted into #my_container in the first place.
First, try the following code (in place of the original AJAX call you showed):
var html = $.ajax({url: 'output.aspx',
data: 'id=5',
type: 'get',
datatype: 'html',
async: false
}).responseText;
$('#my_container').html(html);
If that works, your li:first selector is just being called before the AJAX request finishes. If that doesn't work, try the following code:
$.ajax({url: 'output.aspx',
data: 'id=5',
type: 'get',
datatype: 'html',
success: function(outData) { $('#my_container').html(outData); },
error: function(errorMsg) { alert('Error occured: ' + errorMsg); }
});
That will cause an error message to pop up if the request fails. If an error message pops up with an error message, the request is not returning.
it's looks like you are trying to access to those elements before their was created because your current ajax call is asynchronous, try to put the option:
"async=false"
to your ajax and it should be work.

Categories

Resources