The purpose of this code was to populate a div from a PHP file when a button is clicked.
Also to pre populate a div when page loads - I have completed this task.
Now I want to load a second div at the same time and I'm unsure how to go about this.
function loadpage(clicked_id) {
if (clicked_id != 0 || clicked_id != null || clicked_id !="") {
$("#Table").load("marshfight1.php?action=fight&id="+ clicked_id);
$("#mobs").load("marshtab.php");
}
}
$(document).ready(function() {
// initial
$('#mobs').load('marshtab.php');
});
Echo "<div id=Table></div>";
Echo "<div id=mobs></div>";
$selem = mysql_query("SELECT * FROM senemies WHERE userid='$playerinfo[id]' && arena='10'");
while($enem = mysql_fetch_array($selem)) {
Echo "<button><type=button id=\"$enem[id]\" onclick=\"loadpage(this.id)\" name=\"$enem[id]\">$enem[name]<br>Level: $enem[level]<br> HP: $enem[hp]</a></button>";
}
Everything works fine except for the second .load to update #mobs.
The problem appears to be the inclusion of PHP in your javascript. Remember that though PHP will throw a compile error, IE will do its best and FF will do its best up to the point of the error then very quietly quit. Thus it will appear to be working but actually half your code never gets executed. ctrl-shift-k in FF will give you a rundown of errors.
What you need is ajax. This is easy to implement in both jquery and 'straight' javascript.
Forgive me if you already know this, but others use this forum so a brief summary of the process would be:
Button is clicked triggering JS onclick function.
onclick function sends appropriate data (which button for instance and/or usernumber etc) to php file.
onclick function puts whatever the php returns in the div as desired.
You need to get your js and php organised and separated.
A good overview and basic tutorial can be found at http://www.w3schools.com/ajax/
Related
I've searched for a solution but only found solutions for other versions of sharepoint.
Pages are modern sharepoint template, inside a modern script editor webpart i'm laoding my .js file.
Sometimes the function is called, sometimes it's not. On refreshing the page, the function fires.
These did not work
$(document).ready
window.onload
SP.SOD.executeFunc("sp.js", myFunction);
ExecuteOrDelayUntilScriptLoaded(myFunction, "sp.js");
_spBodyOnLoadFunctionNames.push("myFunction");
Anyone have any idea how to fire functions after sharepoint is actually loaded?
With SPFX you have the option to include jQuery or you can do it with just regular browser core JavaScript API.
I used the following to override the search textbox on SP modern to be able to use the search center results page since Microsoft forgot that they provide a Search Center Override Url setting in the settings page and don't actually use it in modern for some whacky reason that someone should totally get a hand slappin for.
/*
Because modern does funky html stuff you'll wanna wait until your specific html element you need to work with is available to be worked with.
*/
$(document).ready(function() {
setTimeout(doesThatDarnSearchBoxExistYetOrWhat, 150);
});
function doesThatDarnSearchBoxExistYetOrWhat() {
var $search = $(".ms-compositeHeader-searchBoxContainer");
if($search === null) {
//Not found, keep waiting.
setTimeout(doesThatDarnSearchBoxExistYetOrWhat, 150);
} else {
// Found, fix that.
getTheModernSpSearchTheHeckOuttaMyFace();
}
}
function getTheModernSpSearchTheHeckOuttaMyFace() {
//Strip events on search form
$(".ms-compositeHeader-searchBoxContainer").html($(".ms-compositeHeader-searchBoxContainer").html())
$form = $(".ms-compositeHeader-searchBoxContainer FORM");
//Change submission to search center results page
$form.attr("action","/sites/Search-Center/Pages/results.aspx")
//Change textbox name to "k" for search param.
$form.find("input[type='search']").attr("name","k")
}
I am currently trying to implement the WordPress Contact Form 7 Plugin into a WordPress-site I created. The theme uses jQuery to overwrite the default link behaviour and AJAX to load the requested page without actually reloading the whole page.
The problem is: The contact form works perfectly when the page where it is used on is loaded directly. However, if the page is loaded via AJAX, there are two strange behaviours: The Google reCAPTCHA widget is not showing up and after submit, instead of showing the div with the success-message, I am redirected to the themes "404" page. The mail gets sent successfully though. I use the plugin/contact-form in AJAX mode - so it makes an AJAX call itself to submit the data and handle the response without page refresh.
I am a bit overwhelmed where to start to solve this problem. Just for testing, I tried to hardcode all scripts from the direct pageload to the theme, so that they are also there when the contact-page is loaded via AJAX. Unfortunately, this didn't have any effect at all. I also tried to call the wpcf7InitForm() function of the plugin, as it was suggested in another question here - also with no success.
This is my ajaxload-script:
jQuery(document).ready(function($) {
// Targeting all internal links
$(document).on('click', 'a[href^="http://' + top.location.host.toString() + '"]:not([href*="wp-admin"])', function(event) {
event.preventDefault();
var url = $(this).attr('href');
$.ajax(url, {
beforeSend: function() {
if ($('#ajax-loader').length == 0) { $('body').append('<div id="ajax-loader"></div>'); }
$('#ajax-loader').fadeIn();
// Dimming static elements during loading
$('#mainbar').animate( { opacity: '0.5' } );
},
success: function(data) {
var data = $('<div />').html(data);
window.history.pushState('...', '...', url);
document.title = $(data).find('title').text();
$('#mainbar').html($(data).find('#mainbar > *'));
// Undoing design modifications to static elements
$('#mainbar').animate( { opacity: '1' }, 150 );
$('body').triggerHandler('reflow');
},
});
});
});
Help on this topic would be really appreciated and thanks in advance!
Couple ideas after reading through some stuff:
Might be a bug with the recaptcha - looks like the latest version specifically fixes recaptcha problems (not sure if they are yours though): http://contactform7.com/2015/11/23/contact-form-7-431/#more-16357
The div not showing up should be easy to debug by using absolute paths. In Wordpress, I usually use the bloginfo(); function. Try putting something like this in your form submit success callback to test path visibility between the AJAX and non-AJAX pages:
<?php
$pathCheck = bloginfo('template_directory');
echo $pathCheck;
?>
The problem with the div not showing up could also be how you are structuring the callback. From this question, it appears that the plugin has specific callback hooks you have to use that aren't in the documentation:
$(".your-form-class").on('wpcf7:mailsent', function(event){
// Show success div code would go in here
});
Great question btw. You used proper english and clearly explained your problem, pretty rare on S.O. Hope some of this gets you going.
Im trying to do something that should be very simple yet my head is about to explode considering I cannot get it to work.
In my asp.net MVC app, I make an Ajax call to the server, and the server sends back a message (as a string), which includes a link.
The message basically looks like this : Action failed, Learn more..
I am inserting this returned message in a div that shows the alerts from the server.
However, whatever I try, the 'Learn more.' part will never be inserted.
If I do alert(returnedMessage), it shows the correct html, but as soon as I do
$(mydiv).html(returnedMessage), the anchor-tag is gone. I tried unescaping, normal jscript innerHtml...not sure what I'm missing.
Thanks!
**UPDATE with some extra code **
I have the ajax call that returns a message. I have a method that then sets the message into the div and shows the alert.
the ajax call handling:
success: function (result) {
if (result.Message) {
showAlert(result.Message);
}
},
The javascript:
function showAlert(message) {
// neither setting the actual div, nor the span works
alert(message);
$('#server-message').html(message)
//$('#server-message span').html(message);
$('#server-message').fadeIn(100);
};
the html:
<div id="server-message">
<span></span>
</div>
also worth trying if you are escaping the double quotes properly :)
var returnMessage = 'Learn more.';
You should your message to .html() function $(mydiv).html(returnedMessage) if you doing $(mydiv).html = you only overwriting html property in this object.
I would first like to state that I started learning HTML 5 days ago, and therefore I am very new to everything.
I am trying to implement the code given here: http://jsfiddle.net/NFXzn/9/.
But for some reason the dropdown menu is blank. I have uploaded my code here: http://gbrowse2014.biology.gatech.edu/viru.html
Since I did not make the code, I am assuming the problems lies with how I implemented the code (specifically the javascript). I have narrowed the problem down to one particular function:
$.each(g_Vehicle, function(index) {
var iYear = g_Vehicle[index].Year;
if ($.inArray(iYear, g_YearsArray) == -1) {
g_YearsArray.push(iYear);
}
});
I am using firefox, and I have gone through www.w3schools.com to look for implementation tips, but I have not corrected the problem.
On a sidenote, does anyone know how to change the code to use the dropdown-checkboxes instead of the dropboxes?
That loop is working fine. The problem is that you're running the code before your select is loaded, so nothing is being appended to the page. Either wrap your code in $(document).ready( function() { ... });, or move your <script> blocks to the bottom of the page (after the HTML has completely loaded).
http://learn.jquery.com/using-jquery-core/document-ready/
(On the top-left corner of the jsFiddle page, you'll see a dropdown which displays onLoad -- which is automatically doing that job for you. Your page as it stands is the equivalent of No wrap - in <head> -- not what you want.)
So I have a drop down menu that's supposed to be populated by a Json object value. The code reads like this:
$("#sport").val(model.SportId);
Well, when I load the page, it doesn't work. The drop down list defaults to the default "None Selected" option. So I do a ghetto debug and I put an alert on model.SportId to see what's up.
And when I refresh the page...it works. The only thing that I did was
alert(model.SportId);
It brings up a pop up window that says "1" and then the drop down menu value goes to the option 'Major League Baseball' (which is the text of that option value). That's it. That's the only thing I changed. Putting the alert before that first line of code. If I put the alert after the code, it doesn't work. I have no idea why this is.
The viewmodel that the Json object is derived from has SportId as a nullable int. Could that have anything to do with it?
Edit:
Okay, so in my razor view, this is the javascript I have:
<script type="text/javascript">
$(document).ready(function () {
var model=#Html.Raw(Json.Encode(Model.Title));
var read=#Html.Raw(Json.Encode(Model));
var sportsurl='#Url.Action("GetSports", "Titles")';
var sportsteamsurl='#Url.Action("GetSportsTeams", "Titles")';
TitleBasicEdit(model, read, sportsurl, sportsteamsurl);
});
And the javascript function titlebasicedit is:
function TitleBasicEdit(model, url, read, backurl, seasonsurl, autocompleteurl, urlforward, sportsurl, sportsteamsurl) {
if ((model.TitleTypeId == 3) || (model.TitleTypeId == 8)) {
GetSports(sportsurl);
SportsDependency(sportsteamsurl);
alert(model.SportId);
$("#sport").val(model.SportId);
$("#sport").change();
$("#hometeam").val(model.HomeSportTeamId);
$("#awayteam").val(model.AwaySportTeamId);
}
It could be an issue related to an asynchronous task you perform while populating your options (like an ajax request). That could be the reason why the alert() works: it stops the execution oj javascript so that the task has enough time to be completed (anyway a link may be really appreciated).
edit: the GetSports() function could be that task;
I wonder if it is because model.SportId is a typeof === 'number' ..? Have you tried this? I don't know why it would work though, because jQuery should be smart enough to handle this:
$("#sport").val(model.SportId+'');
Also, try this:
alert($("#sport").length);
$("#sport").val(model.SportId);
alert($("#sport").length);
It could be that your javascript is executing before the HTML loads. The alert() may give it just enough time to load.