modifying main view from inside partial view - javascript

I have a main view that let's say has the following:
<div id='test'>Some Text</div>
<div id='placeholder'></div>
then using ajax I'm replacing the contents of 'placeholder' with a partial view that looks like this:
<div id='ajaxContent'>
// new content
</div>
<script>
$(document).ready(function() {
console.log($('#test').text());
$('#test').css('color','red');
});
</script>
so in my script I'm trying to change the color of the text in div 'test' to red, but I keep getting 'undefined' in the console. How do I access the test div in the main view from the partial view coming into the main view through ajax?
If they're ending up on the same page, shouldn't the html elements be able to see each other?

Your JavaScript fragment is simply removed by jQuery on html(...) call. A similar issue can be found here: jQuery .load() / .ajax() not executing javascript in returned HTML after appended
Thus, you have to insert partial data in this manner (assuming you have your partial respone in result variable):
$(result).find('#ajaxContent').appendTo('#placeholder');
$(result).find('script').appendTo('#placeholder');
Also, as #RolandBertolom said before, you don't need ready() in your partial response in JavaScript.

You actually do not need to use $(document).ready. It's just useless. But it shouldn't break anything. As well as you can access any element on the page from script inserted anywhere in the same document. So problem is somewhere out your question's scope.
Try:
run $('#test').text() from console.
replace $('#test').text() with $('body') or something else in your script.
...
Be deductive when you debugging! ;-)

you should not be using $(document).ready again because you document will already loaded with main page so again using it wont help.
try like this:
suppose this is your test.php:
<script>
jQuery(document).ready(function() {
$.ajax({
type:'post',
url:'submit.php',
success:function(data) {
$('#placeholder').append(data);
}
});
});
</script>
<div id='test'>Some Text</div>
<div id='placeholder'></div>
//this is your submit.php the content to replace
<?php
echo "<div id='ajaxContent'>
</div>
<script>
$(function(){
console.log($('#test').text());
$('#test').css('color','red');
});
</script>";
?>
NOTE: what i exactly mean here is use:
$(function(){
console.log($('#test').text());
$('#test').css('color','red');
});
in script.

Related

jquerys load not loading html page properly

I got a main view like this,
<body>
<div id="view"></div>
</body>
The problem is if I inject an HTML content to this div it is not working, but when I copy paste the elements between the body tag its working.
I have included a jsfiddle of my script and partial : https://jsfiddle.net/whb65L5w/7/
It does some preprocessing of data to be populated on the body as well as the partial. But using jquerys load function the page is not working properly, can someone tell me why.
This is how i load the partial:
$( "#view" ).load( "views/sales.html" );
You can see that even though I selected items, it's not being checked

External POST form through iframe

I'm trying to get a page which includes a POST form to load inside an iframe for users to be able to confirm an action such as deleting a listing. I have successfully got the JS and the form page to load inside the iframe, but when I click an action inside the form, it's not updating the listing. Instead, it just refreshes the page.
The form is working fine because if I try to access the content-url manually in the browser and update the form, it works fine.
How can I get the iframe content to refresh instead of the parent page and load the response inside the iframe itself? What I am doing wrong exactly?
Any help is appreciated!!
Here's my code:
HTML:
<button class="myclass" content-url="<?php bloginfo('siteurl') ?>/?a_action=delete_auction&pid=<?php the_ID(); ?>">Delete Me</button>
<div class="popup"><iframe id="mynewiframeid" name="myframename" src=""></iframe></div>
JS:
$(document).ready(function() {
$(document).click(function(e) {
if ($(".popup").is(":visible")) {
$(".popup").fadeOut("fast")
}
});
$(".myclass").click(function() {
if (!$(".popup").is(":visible")) {
$('#mynewiframeid').attr('src',$(this).attr('content-url'));
$(".popup").fadeIn("slow");
}
return false;
});
$(".popup").click(function(e) {
e.stopPropagation()
})
});
Form:
<div class="popup_content">
<h3> You are about to delete <b><?php echo $title; ?></b>!</h3>
<?php
if(isset($_POST['yes_confirm']))
{
$s = "update ".$wpdb->prefix."posts set post_status='trash' where id='$pid'";
$wpdb->query($s);
echo '<div class="deleted_item_ok">';
printf(__('Your item has been deleted successfully!'));
echo '</div>';
}
else
{
?>
<form method="post">
<div class="are_you_sure_delete">
<?php
_e('Are you sure you want to delete this item?');
?>
</div>
<button class="button-small button-w-green" type="submit" id="submits" name="yes_confirm">Yes, Delete</button>
<button class="button-small button-w-red" type="submit" id="submits" name="no_confirm">No!</button>
</form>
<?php } ?>
</div>
You are trying to replace html in the class "popup" with following js code..
HTML => <div class="popup"><iframe id="iframeid" src=""></iframe></div>
JS => $('.popup').html(response);
This replaces the iframe element in the HTML above with the response..! Therefore after response comes, no iframes inside the page..
If you do want to use an iframe, I don't think you have to deal with AJAX. Instead just change the src of iframe. You may use following js code..
$(document).ready(function() {
$(document).click(function(e) {
if ($(".popup").is(":visible")) {
$(".popup").fadeOut("fast")
}
});
$(".myclass").click(function() {
if (!$(".popup").is(":visible")) {
$('#iframeid').attr('src',$(this).attr('content-url'));
$(".popup").fadeIn("slow");
}
return false;
});
$(".popup").click(function(e) {
e.stopPropagation()
})
});
Fiddle (with fake src urls)
First of all, correct the following errors and then see if it works:
in your you are missing semicolon after the closing parenthesis
you close the php tags and right after you continue with url and then you add another closing php tags
What you are looking for is this inside your content-url:
<?php bloginfo('siteurl') . '/?a_action=delete_auction&pid=' . $the_ID; ?>
What is the_ID()? I dont see that function. And if exists it has to return the value that you will store in variable $the_ID. You also have to call that function before button tag to get that variable.
In your JS you need to wrap everything in $(document).ready(function() {}
It seems you are trying to do GET request and not POST request since you are not sending any data in the body but in the url
Missing semicolon at the end of first .click function
I didn't even look at all other .click functions cause there's some repetitions going on and more weird stuff

PHP: Reading DOM info of own HTML page

So, let's say I have only one file on my server called index.php :
<!DOCTYPE html>
<html>
<body style="background-color: orange;">
<!-- On/Off button's picture -->
<?php
echo ("<img id='button' src='data/button.jpg' alt='off'/>");
?>
</body>
</html>
Now, let's say I attach a JavaScript that changes the buttons ALT to ON when I click the button at some point.
How can I read the DOM elements on this page using PHP?
So far, I've found this code:
$dom = new DOMDocument;
$dom->loadHTML($html);
$main = $dom->getElementById('alt');
but I can't figure out how I would fit that in my code above, what page should I call loadHTML() for?
How do I make PHP read DOM elements it generated using echo?
First of all, your button has id button, so searching for the id alt would return no results.
Second: The piece of php you found reads a page $html (probably file_get_contents('some_url'), puts it in the variable dom and parses it, searching for the id alt. In your case it would read your own page, breaking it down in pieces looking for that button.
Thats of no use if you can read the status with javascript on your own page. You can then pass it to php trough an ajax-call or by adding it to the url like mypage.php?button=off
$main = $dom->getElementById('button');

jQuery Auto-submit form inside of a <div> loads in new page

I'm developing a project of "prettifying" of a part of an existing web application. There is a need of putting the existing code: search criteria form in one div, and search results in another div (forming a kind of tabs, but that's another story).
Using jQuery I was able to manage that, but right now I am struggling with the results page, which by itself is yet another form that auto-submits to another file (using document.form.submit()), which is the final search results view. This auto-submit causes that the final view quits the destination div and loads as a new page (not new window).
So, the flow is like that:
First file, let's call it "criteria.html" loads the search criteria form (inside of a div) + another div (empty) destined to be filled with search results.:
<div id="criteria">... form with search criteria here...</div>
<div id="results"></div>
On submit, using jQuery's "hide()" method, I hide the first div (surrounding the search criteria form), and make Ajax call to the second file, let's call it "results.php":
<script>
$("#criteria").hide();
$.ajax({
...,
url: "results.php",
success: function(data){
$("#results").html(data);
},
...
});
</script>
results.php searches according to given criteria, and displays an "intermediary form" (which returns as a data result of the ajax query above) with a lot of hidden fields, and at the end executes:
<script>document.form.submit();</script>
which submits to another file, let's call it "resultsView.php"
This line causes that a result page shows outside the div "results", as a new page.
As there is a lot of logic in those files (more than 700 lines each), the idea of rewriting this monster just gives me creeps.
And now the question: is this a normal behavior (opening the result outside div)?
I tried removing the document.form.submit() code and everything works fine (well, without showing the results from "resultsView.php"). It's this line that causes the viewport to reset. I also tried with empty pages (to eliminate the possibility of the interaction with contents of the pages) - still the same result.
I hope there is not too much text and the problem is clearly stated. Every suggestion of how to fix this will be greatly appreciated.
If I understand your question correctly, you need to process the final submit using ajax instead of <script>document.form.submit();</script> so that you can handle the results on-page. Traditional form submits will always reload/open the action page. If you want to avoid that you'll have to control the form submit response via ajax and handle the results accordingly... like you are doing with the first submit.
The only alternative I can think of is to make div id="results" an iframe instead, so that it contains the subsequent form submit. Of course, that unleashes further restrictions that may cause other troubles.
I am not sure if I understood your question, but maybe u can do something like this.
This is my JQuery script: [I just wait for the submission search. When it happens, I use the $.Post method to call a function that should return the Html results (You can include somenthing to hide any field you want using JQuery or css)].
<script type="text/javascript" src="http://code.jquery.com/jquery-1.3.2.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("form#searchForm").submit(function() {
var theCity = $("select#chooseCity").val();
var theName = $("input#searchInput").val();
$.post("callProvideSearchResults.php", {theCity: theCity, theName: theName}, function(data) {
$("div#searchResults").html(data);
});
return false
});
});
</script>
This is my Body: {it consists of the choice of a city, the a form to provide the name of the person you are lookng for and the place to provide the results.
<body>
<FORM id="searchForm">
<h2>Select the city: </h2>
<select id="chooseCity">
<?php
$theCitiesOptionsHTML = "cityOptions.html";
require($thePathDataFiles.$theCitiesOptionsHTML); / A large list of cities
?>
</select>
<h2> What is the name of the person </h2>
<P> <INPUT id="searchInput" TYPE="TEXT" SIZE=50></P>
<P><INPUT TYPE="submit" VALUE="search"></P>
</FORM>
<div id="searchResults">
<!-- Here: Search results -->
</div>
</body>
// Function callProvideSearchResults.php // Just call the function that makes all the job and echo the $Html page
<?php
include "provideSearchResults.php";
$theName=$_POST['theName'];
$theCity=$_POST['theCity'];
echo provideSearchResults($theName, $theCity);
?>
// provideSearchResults.php // Database connection and search
<?php
function provideSearchResults($theName, $theCity) {
include "databaseConnection.php";
//database Queries
// Generate $theHtml using strings or ob_start, for instance
return $theHtml;
}
?>

Modifying controls collection error in VB.net

I need a function to be performed on the page load, which uses a stored session variable. I have added the following to my <body> tag.
<body onload="doSomething(event,'<%= Session("StartTime") %>')>
This does work. However, it is causing a problem elsewhere, when I try to add a control to my controls collection:
dim myPanel= New Panel
...
Me.Controls.Add(myPanel)
It bombs out at this stage, giving the following error:
"The Controls collection cannot be
modified because the control contains
code blocks (i.e. <% ... %>). "
I've tried the suggestion of using <%#...%> instead of <%=...%>, but this prevents the session variable being found- it is just blank.
Or,
<body onload="doSomething(event,'<asp:PlaceHolder id="starttimePlaceholder" runat="server"</asp:Placeholder>')>
Then, on the server side to populate it:
starttimePlaceholder.Controls.Add(New LiteralControl(Session("StartTime")))
I found a solution that worked
I forced my script to run on a server-control.
<body ms_positioning="GridLayout" onload="callFromDiv(event);">
<div runat="server" ID="serverDiv">
<script type="text/javascript">
//This function must be placed in a separate div, since placing it directly
//in body tag prevents new controls being added later
function callFromDiv(e){
doSomething(e,'<%= Session("StartTime") %>')
}
</script>
</div>

Categories