Javascripts in dynamic loaded div not working (JSON) - javascript

This might be duplicate - but in all other soloutions I can't seem to find any usefull information for my purpose.
I have this script parsing data to a .php file which generate content from a database query.
The .php file returns the generated HTML content as JSON - And this generated content includes som JS (some contextMenu functions to run when clicked on certain DIV's inside the loaded content).
These functions does not work in the loaded content.
From my main site I run:
$('.part_click').on('click', function(){
var data_id = $(this).attr('id');
$.ajax({
url: 'explode_machine.php',
type: 'POST',
data: {id: data_id, machineid: '<?php echo $machineid;?>'},
dataType: 'json',
success: function(data){
$('#explode').html(data.html);
}
});
});
And the .php returns (among many things):
$('#clickedDiv').contextMenu('#menu-Div',{triggerOn:'contextmenu'});
#clickedDiv and #menu-Div is just fancy names used here as the actual names and numbers of id's may vary depending on the database query.
The .js file including the contextMenu function is loaded in the top of my main site.
If i right click on the #clickedDiv inside the dynamic loaded content nothing happens - If I add the same function to content outside the dynamic loaded content everything works as aspected.
As far as I understand from other topics the problem is either in the JSON parsing or in the .html() - but I'm not able to sort it out.

Assuming the #clickedDiv element is added by your AJAX success handler, you need to initialise that plugin after the element is placed in the DOM. Try this:
$('.part_click').on('click', function(){
var data_id = $(this).attr('id');
$.ajax({
url: 'explode_machine.php',
type: 'POST',
data: {
id: data_id,
machineid: '<?php echo $machineid;?>'
},
dataType: 'json',
success: function(data){
$('#explode').html(data.html);
// initialise the plugin here:
$('#clickedDiv').contextMenu('#menu-Div', {
triggerOn: 'contextmenu'
});
}
});
});

Related

jquery load call to controller and populate div element

I have a div element in my index.cshtml with id #myresults and i am trying to load data through jquery.load method by calling a mvc controller method. But i am not able to get the right syntax.
I am passing a custom object as a parameter as well.
var mycustomObject = {
obj1:value1,
obj2:value2,
..
}
The following does not work...(an i have tried other combinations as well..i get server not found error)
$("#myresults").load ('#Url.Action("MyActionMethod","Home")',mycustomObject);
while the following works
$("#myresults").load('/Home/MyActionMethod', mycustomObject);
While the last statement works, it works only on localhost.
Whats the right syntax to use for jquery load with Url.Action ?
#Url.Action() will always generate the correct url, so if your getting a 404, it means this code is in an external script file. Razor code is not executed in external scripts so your url would literally be the text "#Url.Action("MyActionMethod","Home")".
Options to solve this include
moving the code into the view or its layout
declaring a global variable in the view - var url =
'#Url.Action("MyActionMethod","Home")'; an in the external file use
$("#myresults").load(url, mycustomObject);
assign the url to an element as a data-* attribute, for example
<button type="button" id="loadSomething" data-url="#Url.Action("MyActionMethod","Home")">...</button>,and in
the external file
$('#loadSomething').click(function() {
var url = $(this).data('url');
$("#myresults").load(url, mycustomObject);
});
Define the div element as:
<div id="myresults" onload="loadMyData();"></div>
And make the ajax call in your method:
<script type="text/javascript">
function loadMyData() {
$.ajax({
cache: false,
url: '#Html.Raw(Url.Action(MyActionMethod","Home"))',
data: { obj1:value1, obj2:value2 },
dataType: "json",
type: 'post',
success: function (result) {
if (result.success) {
$('#myresults').html(result.data);
}
else {
alert("Failed to load data!");
}
}
});
}
</script>

table positioning with AJAX to PHP post

I have a jQuery script that sends POST data via AJAX to a php file that then creates a table. I have used firebug to check the console and everything gets created properly. On the success: I reload the window and the table isn't displayed.
I know the table html was created properly from the php file because I commented out the reload so I could see exactly what it created) I have lots of things displayed on my page and would like the table in a particular spot. How can I get the table to actually display where I want it to?
<script>
$(document).ready(function () {
$("#stayinfobutton").click(function () {
var id = $('#id').val();
var dataString = {
id: id
};
console.log(dataString);
$.ajax({
type: "POST",
url: "classes/table_auto_guests.php",
data: dataString,
cache: false,
/*success: function(html)
{
window.location.reload(true);
}*/
});
});
});
</script>
The window.location call will reload a new page in the browser window, this will loose the data returned to the ajax call by the server.
Usually the response to Ajax calls is loaded directly into your page, something like:
success: function(html)
{
$('#guestsTable').html(html);
$('userForm').hide();
}
I made up the guestsTable div and userForm names, ;).
The return data may need some coercing to make it into html (I'm assuming your using JQuery), hopefully the php script will set it to html/text in the header, also dataType: html can be passed in the $.ajax({...}) call.
Alternatively, if the classes/table_auto_guests.php returns a full page which you want to load in the browser, Ajax may not be what you are looking for. This post contains code on how to submit the data as a form, and load the result as a new page.

Append a php file with jquery

i have a file which echoes out data from a database.
I wish to have a load more button which appends this file so that it will keep loading the rest of the results.
The php page works fine but need help with the jquery...
have used this else where for a json return but dont think this is needed for this.
So i am trying this:
$(document).ready(function(){
$("#loadmore").click(function () {
$("#content").append('includes/loadmorebuilds.php');
});
});
In essence, this works but it appends 'includes/loadmorebuilds.php' as just that. I simply appends those words and not the file.
Any help on this?
Many thanks!
You could use $.ajax to get content from file to be appended into DOM. One important thing is that you should use Relative PATH to your web root on url parameter in $.ajax
So it will become like this
$('#loadmore').click(function() {
$.ajax({
url: '/relative/path/to/your/script',
success: function(html) {
$("#content").append(html);
}
});
});
And make sure you should be able to access your script on http://www.example.com/relative/path/to/your/script
You have two options:
$('#content').load('includes/loadmorebuilds.php');
Which will replace the content of #content with the new html.
Or this:
$.ajax({
url: 'includes/loadmorebuilds.php'
}).done(function(data) {
$('#content').append(data);
});
Which will append the new data.
use $.ajax
$(document).ready(function(){
$(".loader").click(function(){
$.ajax({
url:"index.php",
dataType:"html",
type:'POST',
beforeSend: function(){
},
success:function(result){
$(".content").append(result);
},
});
});
});

Update div after ajax database insert

so i have some comments pulled from a database and echoed into a div.
Im am entering new comments via a form and they are inserted into the database with ajax.
I want the comments in the div to update and show the new ones as soon as they are posted.
How can i refresh the div to show new content, without the page loading again?
javascript is like so:
// ... goes after Validation
if (check == true) {
$.ajax({
type: "POST",
url: "process/addcomment.php",
data: $targetForm.serialize(),
dataType: "json",
success: function(response){
if (response.databaseSuccess)
$comment.after('<div class="success">Update Added!</div>');
else
$comment.after('<div class="error">Something went wrong!</div>');
}
});
}
return false;
});
});
Thanks for any help.
I think you would like to use
http://api.jquery.com/prepend/ for making new comments on the top,
OR,
http://api.jquery.com/append for making new comments on the bottom.
right after using
$comment.after('<div class="success">Update Added!</div>');
Just append or prepend the valid structure that forms your comment box is okay for it.
just like for example:
$("#comment-holder").append("<div class='commentbox'><p class='commenthead'>" + response.newCommentHeadline + "</p><p class='commentcontent'>" + response.newCommentContent + "</p></div>");
Also worth looking into your response.databaseSuccess, you might want to compare it more strictly like using "==", because boolean not always work as you expect, since i am not sure if your responding document are in the correct format that it correctly interprets as a boolean.
you should extract your required data from response json and generate a Html for appending to your div with id of "comment" then as you apply your css it will get styled.
my suggestion is if you don't want to add extra info from your server to the comment, you only need a flag as success or fail and instead of sending data to server and retrieving it you can use your local data when successfully inserted to your database
if (check == true) {
$.ajax({
type: "POST",
url: "process/addcomment.php",
data: $targetForm.serialize(),
dataType: "json",
success: function(response){
$("#comment").after('<div><div class="from">'+response.from+'</div><div class="message">'+response.message+'</div></div>');
}
fail:function(){
$("#comment").after('<div class="error">Something went wrong!</div>');
}
});
}

Get jQuery object from HTML string

I have an AJAX request that grabs the source of Wikipedia pages:
$.ajax({
url: "TrollWikipedia.ashx",
data: {
url: "http://en.wikipedia.org/wiki/20s",
},
type: "GET",
success: function (html) {
var page = $(html);
alert(page.find("#content").length); //Alerts 0
alert(page.html()); //alerts null
}
});
It successfully returns the source of the page (I have a copy of the string it returns here on jsFiddle).
The problem: I can't seem to make a jQuery object from the HTML (like they do here). For some reason, it doesn't seem to be creating the object correctly. What am I doing wrong?
html data seems to be badly parsed (maybe a closing div tag is missing in the html code), use:
$.ajax({
url: "TrollWikipedia.ashx",
data: {
url: "http://en.wikipedia.org/wiki/20s",
},
type: "GET",
datatype: "html",
success: function (html) {
html=html.replace(/(<body [^>]*>)/i, '$1<div>').replace(/(<\/body>)/i, '</div>$1');
var page = $(html);
alert($("#content",page).length); //Alerts 1
alert(page.html()); //alerts html
}
});
html string contains the links pointing to en.wikipedia.org site, so when we do $(html) jQuery might be getting exception due to cross domain script calls inside the html markup due to which you are not getting any thing after $(html)

Categories