Send a JSON object to AJAX of jQuery Tabs using WordPress - javascript

I am using jQuery Tabs to program a messaging system using WordPress. The point is that when the user clicks one tab, which represents one conversation, an AJAX call is performed automatically with the functionality of jQuery Tabs.
I programmed the jQuery Tab to call an action (that I programmed as well). The action is programmed in PHP using WordPress and I can call it through localhost/mywebpage/wp-admin/admin-ajax.php?action=my_action.
The problem is the following: The default functionality of the jQuery tabs expects the raw output of the PHP file (the ajax action). This means I have to code HTML on the PHP file so I just put the response on the tabs panel (ui.panel.html). However I think this is inefficient and I would like to create a JSON object using WordPres function wp_send_json_success( jsonObject ) which is received on the ui.ajaxSettings.dataFilter function.
When I send HTML to the ui.ajaxSettings.dataFilter function, everything is correctly displayed on the jQuery tabs panel. But when I send a json success, I can see it on the console but I can't display it on the jQuery tabs panel. It appears for a millisecond and then disappears. So the JSON object is being received but for some reason can't be displayed. The only way something is displayed at the jQuery tabs panel is by sending raw HTML by my PHP function. Here is a very simple code example:
This is the JS function:
$( selector ).tabs( {
beforeLoad: function( event, ui ) {
ui.ajaxSettings.dataFilter = function( response ) {
console.log( response );
ui.panel.html( response );
}
} );
This is the PHP function that works good:
<?php
echo 'Hello World!';
This is the PHP function that displays on the panel por a millisecond and then disappears.
<?php
wp_send_json_success( 'Hello World! );
In my opinion, I think something else is executing and erasing what I have displayed on the ui.panel.html but I'm not that expert in jQuery tabs so if there is anyone out there with more experience that can tell me what it's going on I would really appreciate it.

I got it working and the fix was obvious but I am still unsure if this is the best way to do it. This is what I did:
var html = $( '<div>' ).addClass( 'wrapper' );
$( selector ).tabs( {
beforeLoad: function( event, ui ) {
ui.ajaxSettings.dataFilter = function( response ) {
// Do whatever you want with the JSON object (obviously validations)
// In my case I want to create HTML elements with info from the response
var response_js_array = JSON.parse( response );
html.append( $( '<div>' ).text( response_js_array['message'] ) );
},
load: function( event, ui ) {
ui.panel.html( html );
// Do also whatever you want after the messages have been loaded. In my case,
// I scroll down to the last message
scrollDown(); // This is also a function I programmed
}
} );

Related

Jquery ajax post only works once

I have a jquery script that posts a value:
// //Delete a product from the shopping cart
tpj('.remove').on('click', function() {
// Stop form from submitting normally
event.preventDefault();
// Get some values from elements on the page:
console.log('test');
var $remove = tpj(this).attr('id');
url = 'includes/shoppingcart.php';
// Send the data using post
var posting = tpj.post( url, { remove: $remove} );
// Put the results in a div
posting.done(function( data ) {
var content = tpj( data );
tpj( "#result" ).empty().append( content );
});
});
This works the first time, but when I click a second time I redirect to my homepage, which makes sense since the anchor tag the .remove class is in has nothing in its href. However this means the preventdefault() is not working, the entire on click is not working.
Why is that? I googled and found out I should use .on instead of .click but this didn't change anything for me.
The following html line (which fires the jquery):
×
is in my header.php and shoppingcart.php, when the ajax post is made and the result of shoppingcart.php is loaded in my shopping cart, the link stops working like it should.
What do I need to do?
function(EVENT) foggoten in
tpj('.remove').on('click', function() {
//...
}
must be:
tpj('.remove').on('click', function(event) {
//...
}

Post data with jQuery

I'm using sortable to sort a list. Then once the user clicks the Submit button I want it to post the data to another php page. I currently can get it to display an alert with the data I want posted but can't get the JavaScript post right.
This is the submit button.
<input type='submit' value='Submit' onclick='saveOrder();'/>
This is the JavaScript part that creates an alert.
function saveOrder()
{
var wordOrder = $( "#sortable" ).sortable('toArray').toString();
alert(wordOrder);
}
This outputs a,b,c,d,e in an alert box. I want this posted instead of showing an alert.
What I would like to do is post this data so I can loop through it on another PHP page.
foreach( $_POST as $stuff )
{
echo $stuff;
}
You can do this via ajax: -> http://api.jquery.com/jQuery.post/
function saveOrder() {
var wordOrder = $( "#sortable" ).sortable('toArray').toString();
$.post( "your/file.php", {wordOrder: wordOrder}, function( data ) {
//Do nothing
});
//$.post("your/file.php", {wordOrder: wordOrder});
}
in PHP, you can:
echo $_POST['wordOrder'];

jQuery UI breaks the anchor download attribute

[My First Post]
Relevant info:
download attribute
jquery-ui
Statement:
I am using jQuery UI, and have no errors. All my buttons and styled elements behave correctly. During a jQuery UI modification to a link I discovered that an html5 functionality broke. This link currently downloads a base64 encoded file that was generated by another function. I want to note that prior to the modification the file downloads perfectly. Here is the pre-modification working code.
JS
data = '<a download="out.yaml" href="data:text/yaml;base64, '+ encoded +'" > Yaml Output Download</a> ;
document.getElementById( "output").innerHTML = data ;
HTML
<div id="output">
</div>
When I modify to add jQuery UI to the anchor by adding
class="button"
the download functionality stops but the styling is implemented and no errors are given by chrome
broken code:
JS
data = '<a class="button" download="out.yaml" href="data:text/yaml;base64, '+ encoded +'" > Yaml Output Download</a> ;
document.getElementById( "output").innerHTML = data ;
HTML
<div id="output">
</div>
I believe that this is a jQuery UI problem, but would like to know if there is a way to use the jQuery UI button while maintaining the original download capability.
EDIT
JS
data = ' Yaml Output Download ;
//document.getElementById( "output" ).innerHTML = data ;
$( '#output' ).html( data ) ;
$( document ).ready( function() { reload() ; } ) ;
ONLOAD
function reload() {
$( "input[type=submit], a.button, button" )
.button()
.click(function( event ) {
event.preventDefault();
});
} ;
$(function() {
reload() ;
});
SOLOUTION
Since I thought the reloading function was being executed correctly I didn't go back and look at the reload function as jQueryUI was not throwing errors or not functioning. All that was needed to be done was to comment out event.preventDefault() ; which as the name suggests prevents the triggering of the default action, in this case the download of the file.
ONLOAD
function reload() {
$( "input[type=submit], a.button, button" )
.button()
.click(function( event ) {
//event.preventDefault();
});
} ;
Is it possible the javascript snippet (document.getElementById) needs
to run within the jQuery document.ready callback? Regardless of whether
that is the issue, I recommend executing your javascript from within
the document.ready callback, as opposed to leaving the javascript to run
as the page is loaded.

A javascript/jquery function to delete itself after execution

I am sending an ajax request to one of my controller to update the user interaction (which page he visits/likes) for an very insight analytics. I am storing these information in my mongo db.
All I want is, on success of this request, delete this script. But all the alert works, but the script never deletes. The following is my code
<div id="delete_this">
<script>
$(document).ready(function() {
$.ajax({
url: weblink+'user-interactions',
type: 'POST',
dataType: 'html',
data: {
//some post data
},
})
.done(function(html) {
alert("works");
var status = "executed";
alert("works here");
$("#delete_this").remove();
})
.fail(function(html) {
console.log("error");
});
});
</script>
</div>
WHAT I HAVE DONE TILL NOW:
1) tried with adding a div as the parent and pointing to delete that div as shown in script.
2) separated out the .remove() from the script into a new script tag and used something like this.
<script>
$(document).ready(function() {
$("#delete_this").remove();
});
</script>
tried to specify the parentnode and delete the child.
I failed in all three attempts. I am really stuck out here.
Any reasons why it is not working?
I also have another question relating to this.
This link says that the javascript stays in the session till the page is refreshed. So why are'nt we following a standard where we can execute the scripts and delete them
By doing so, we will be able to achieve building a bit more secured webpages. Is'nt it?
You could use plain Javascript to do this (not tested this)
var domNode = document.getElementById('delete_this');
var nodeParent = domNode.parentNode;
nodeParent.removeChild(domNode);
Not sure this is ideal but it should remove it completely from the DOM.
This works :
<button>remove</button>
<script id="test">
$( "button" ).click(function() {
$( "#test" ).remove();
alert("removed " + ($( "#test" ).length == 0));
});
</script>
try it here: http://jsfiddle.net/4ungb/
So either you have a) other errors that prevent that script to complete or b)
your criteria for testing deletion is not correct.

Load javascript file after button click

I am trying to use a set of textboxes to define some data within my JavaScript file. So in a textbox I enter a Team name "Team name", and the javascript file uses this textbox to store the name of a team in order to print a set of tournament brackets.
The javascript file is included in my <head> so it loads before I have actually entered the data in the text boxes. I have this code for a button in the html like so:
script(type='text/javascript')
$('#buttontest').click(function() {
$('div.bracket').show();
$('div.teamList').hide();
});
So when the button is pressed, the textboxes are all hidden, and the brackets with the user-defined team names should appear....here is the code at the end of my javascript file:
$(function() {
$('#singleElim8').bracket({
init: singleElim8Data
})
$('.bracket').hide();
});
So within div.bracket I have the class #singleElim8 which the javascript uses. But how would I change it so that this javascript to initialize the brackets only runs once the button has been clicked? That way the brackets render AFTER the textboxes have been filled in. Any help appreciated.
Just use the getScript method of jQuery
It's very easy to use
$( '#buttontest' ).on( 'click', function() {
$.getScript( 'url to your js file', function( data, textStatus, jqxhr ) {
// do some stuff after script is loaded
} );
} );
When you pass a function as the parameter to jQuery it will execute that function during document.ready(). It allows your page to load all of the scripts before executing them.
$(function() {
$('#buttontest').click(function() {
$('div.bracket').show();
$('div.teamList').hide();
});
$('#singleElim8').bracket({
init: singleElim8Data
})
$('.bracket').hide();
});

Categories

Resources