Add javascript function to wordpress page - javascript

I have a page that locates a link inside it and when that link is clicked it should save some data in database.
Besides, I have a file named "add.php" that communicates with the DB and operates well.
In my wordpress page I have added below codes for accessing the add.php file and send some parameters to it.
<a href="javascript:add(true);" >Click Me</a>
<script type="text/javascript">
function add(b){
$(document).ready(function(){
var result = $.ajax({
type: "POST",
url: "add.php",
data: { add: b }
});
result.done(function(msg) {
alert(msg);
});
result.fail(function(jqXHR, textStatus) {
alert( "No such data exists: " + textStatus );
});
});
}
</script>
I had this exact code in an html file and it worked smoothly. but it doesn't work on wordpress page like that.
Plus, the problem is that when I click the link -Click Me- it doesn't do anything.
please tell me where the problem is and how to solve it ?

I would recommend you to use this:
<a href="#" data-add="true" class='hitClick'>Click Me</a>
<!--use data* attributes to pass specific data -->
now in your function:
function add() {
event.preventDefault(); //<------make sure to add it.
var result = jQuery.ajax({
type: "POST",
url: "add.php",
data: {
add: jQuery(this).data('add')
}
});
result.done(function(msg) {
alert(msg);
});
result.fail(function(jqXHR, textStatus) {
alert("No such data exists: " + textStatus);
});
}
jQuery(document).ready(function(){
jQuery('.hitClick').on('click', add); // bind the click and use as callback
});

Related

Why can't I toss post variable to PHP when I cover .ajax with function?

I have 3 files for showing data from myAdmin and it shows no error but after I put function around .ajax, to re-use it, I cannot pass button id to PHP. " Undefined index: btnId"
What seems wrong?
HTML file, written in PHP (below looped in for code)
print"<button class='refresh' data-name='$btnId' id='$btnId'>{$btnId}</button>";
print "<table id='$idForShowNewData' class='showNewData'></table>";
show.js
$(document).ready(function(){
$('.refresh').click(function(){
$(function showTable() {
    $.ajax({
url: "show.php",
type: "POST",
data: {
"btnId": $(this).data("name")
},
success: function(data) {
//more code
},
error: function(xhr,XMLHttpRequest,errorThrown){
//more code
}
});
});
showTable();
});
});
PHP file that get's data from myAdmin. Getting id like below is at the top of the script.
$gotBtnId = $_POST['btnId'];
this in showTable refers to window object and not the button whose data-name you want to send in the request.
If you want showTable to be invoked when the page is loaded and also be registered as a listener for click events to the refresh button, declare it as follows:
const $refreshBtn = $('button.refresh');
function showTable() {
    $.ajax({
url: "show.php",
type: "POST",
data: {
"btnId": $refreshBtn.data("name")
},
success: function(data) {
//more code
},
error: function(xhr,XMLHttpRequest,errorThrown){
//more code
}
});
});
$(function() {
showTable();
$refreshBtn.click(showTable);
});

Send value in a database through jquery + ajax

I want to store the value "20_2018" (for example) with an id in my database. I want to count clicks on each downloading.
This is what I tried:
<html>
<body>
<a id="20_2018" rel="link1" href="folder.pdf">Download</a>
<script type="text/javascript">
$(document).ready(function(){
$(\'a[rel="link1"]\').click(function() {
$.ajax({
type:'POST',
url: 'send.php', // folder for sending value in id to the database
data: 'id='+$(this).attr("id"), // take the value in the id
async: false
});
return true;
});
</script>
</body>
</html>
Somehow this does not work. How can I implement a click count for downloads?
First, prevent the default action with preventDefault, then send your request. After success, bring them to the file URL.
$(document).ready(function(){
$('a[rel="link1"]').click(function(event) {
event.preventDefault();
// Gets href of the clicked anchor
var href = $(this).attr('href');
$.ajax({
type:'POST',
url: 'send.php',
data: 'id='+$(this).attr("id"),
success: function(){
// After recording click count, bring them there
location.assign(href);
},
error: function(){
alert('failed');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="20_2018" rel="link1" href="folder.pdf">Download</a>

Replace the URL, contents and title without reloading the page

I want to create one page site by change div content with out load new page.
So, I've implemented my code like this:
HTML:
<title>Post title</title>
<body>
<a class="js-post-bt" href="/post/1" data-id="1"></a>
<a class="js-post-bt" href="/post/2" data-id="2"></a>
<a class="js-post-bt" href="/post/3" data-id="4"></a>
<div id="post-container"></div>
</body>
Script
$(function() {
$(".js-post-bt").on("click", function(e) {
var post_id = $(this).attr("data-id");
$.ajax({
url: "post_title.php?id="+post_id,
success: function(data) {
var title = data;
$.ajax({
url: "post.php?id="+post_id,
success: function(data2) {
// how to change url to post/post_id?
document.title = title;
$("#post-container").html(data2);
}
});
}
});
e.preventDefault();
});
});
Is it possible to create only one ajax call and get returned data either title and post data.
ANd how to change browser address to post/post_id after anchor link clicked.
You can use history api in HTML5
Demo -> http://html5demos.com/history
Howto ->
http://diveintohtml5.info/history.html
http://html5doctor.com/history-api/
If you want to make just one ajax call, which is a good idea, you will also need to change the code on your server.
It should respond a json object:
json_encode( array( "title" => $title, "post_data" => $post_data ) );
And you ajax call becomes:
$(function() {
$(".js-post-bt").on("click", function(e) {
var post_id = $(this).attr("data-id");
$.ajax({
url: "post_title.php?id="+post_id,
dataType: "json",
success: function(json_data){
document.title = json_data["title"];
$("#post-container").html(json_data["post_data"]);
}
});
e.preventDefault();
});
});

jQuery timing issue (ajax)

I'm trying to send two values to a python script, if a certain button is pressed.
But there is a problem:
With alert("test"); everything works perfectly. But without it, there is nothing send.
I think this is a kind of timing problem, but i cannot really think about what is the problem.
Strange is, that i even can put the alert in front of the ajax function (but still in the $("#submit").click part) and it works perfectly.
<script type="text/javascript" src="./jquery-1.4.4.min.js"></script>
<script type="text/javascript">
/*<![CDATA[*/
$(document).ready(function(){
$("#submit").click(function(){
jQuery.ajax({
type: "POST",
url: "../../../cgi-bin/testCgi.py",
data: {"nick" : $("#nick").val(), "msg" : $("#msg").val()},
success: function (msg) {
alert("Data: " + msg);
}
});
alert("test");
});
});
/*]]>*/
</script>
If #submit is a link element <a href="..."> or a form button, you will need to cancel the default action.
$("#submit").click(function(e){
// added following line and the parameter in the function definition
e.preventDefault();
jQuery.ajax({
type: "POST",
url: "../../../cgi-bin/testCgi.py",
data: {"nick" : $("#nick").val(), "msg" : $("#msg").val()},
success: function (msg) {
alert("Data: " + msg);
}
});
alert("test");
});
If you do not do this, then the page follows the link, or submits the page.

Passing parameters to a JQuery function

I'm creating HTML with a loop that has a column for Action. That column
is a Hyperlink that when the user clicks calls a JavaScript
function and passes the parameters...
example:
<a href="#" OnClick="DoAction(1,'Jose');" > Click </a>
<a href="#" OnClick="DoAction(2,'Juan');" > Click </a>
<a href="#" OnClick="DoAction(3,'Pedro');" > Click </a>
...
<a href="#" OnClick="DoAction(n,'xxx');" > Click </a>
I want that function to call an Ajax jQuery function with the correct
parameters.
Any help?
Using POST
function DoAction( id, name )
{
$.ajax({
type: "POST",
url: "someurl.php",
data: "id=" + id + "&name=" + name,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
}
Using GET
function DoAction( id, name )
{
$.ajax({
type: "GET",
url: "someurl.php",
data: "id=" + id + "&name=" + name,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
}
EDIT:
A, perhaps, better way to do this that would work (using GET) if javascript were not enabled would be to generate the URL for the href, then use a click handler to call that URL via ajax instead.
Click
Click
Click
...
Click
<script type="text/javascript">
$(function() {
$('.ajax-link').click( function() {
$.get( $(this).attr('href'), function(msg) {
alert( "Data Saved: " + msg );
});
return false; // don't follow the link!
});
});
</script>
If you want to do an ajax call or a simple javascript function, don't forget to close your function with the return false
like this:
function DoAction(id, name)
{
// your code
return false;
}
Do you want to pass parameters to another page or to the function only?
If only the function, you don't need to add the $.ajax() tvanfosson added. Just add your function content instead.
Like:
function DoAction (id, name ) {
// ...
// do anything you want here
alert ("id: "+id+" - name: "+name);
//...
}
This will return an alert box with the id and name values.
try something like this
#vote_links a will catch all ids inside vote links div id ...
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(\'#vote_links a\').click(function() {// alert(\'vote clicked\');
var det = jQuery(this).get(0).id.split("-");// alert(jQuery(this).get(0).id);
var votes_id = det[0];
$("#about-button").css({
opacity: 0.3
});
$("#contact-button").css({
opacity: 0.3
});
$("#page-wrap div.button").click(function(){
<script type="text/javascript" src="jquery.js">
</script>
<script type="text/javascript">
function omtCallFromAjax(urlVariable)
{
alert("omt:"+urlVariable);
$("#omtDiv").load("omtt.php?"+urlVariable);
}
</script>
try this it work for me

Categories