Trying to use this code to change content on a page without reload. It’s my first time playing with jQuery.
I keep getting this error: Uncaught ReferenceError: swapContent is not defined at HTMLButtonElement.onmousedown
This is the code:
<script type="/text/javascript" src="jquery-1.5.1.js"></script>
<script language="JavaScript" type="/text/javascript">
function swapContent(cv){
"use strict";
$("#myDiv").html("").show();
var url="main_views.php";
$.post(url, {contentVar: cv},function(data){
$("#myDiv").html(data).show();
});
}
</script>
It’s actioned by these buttons:
<button href="#" onClick="return false" onmousedown="javascript:swapContent('con1');">View One</button> •
<button href="#" onClick="return false" onmousedown="javascript:swapContent('con2');">View Two</button> •
<button href="#" onClick="return false" onmousedown="javascript:swapContent('con3');">View Three</button>
and it references this file main_views.php
<?php
$contentVar=$_POST['contentVar'];
if ($contentVar=="con1"){
echo "<p>Stuff</p>";
} else if ($contentVar=="con2"){
echo "<p>Other Stuff</p>";
} else if ($contentVar=="con3"){
echo "<h1>Yet more stuff</h1>";
}
?>
I was following YouTube tutorial to learn it. It is a 2011 video, so I’m wondering if the script is incorrectly formatted?
Have compared mine to the video several times. Have also tried some code checkers to no luck.
Have used the most current jquery 3.6.3
and the same one as the tutorial jquery-1.5.1
Cannot work out what I’m doing wrong.
2
Answers
various things:
1 – the
type="/text/javascript"
is wrong. u can remove it as the default is"application/javascript"
, that is what you want2 – remove the "javascript:" part on the
onmousedown
handler. also remove thehref
on the button, which is not a valid attribute on a button. also remove theonClick
(which is actuallyonclick
but maybe that’s actually the event u want to use?!) and just addtype="button"
.When trying to replicate the issue: it’s the
type="/text/javascript"
that is incorrect.This needs to be changed (or just removed) on both/all
<script>
tags. In the "not working" example, you don’t get an error on jquery as it doesn’t get to the$
line, but fixing your<script>
tag that has your script then gives$ is not defined
as the<script src=jquery
line also needs fixing.Not working:
Working: