I'm creating a plugin that will add a custom page to the website (with no template).
I'm struggling to work out how talk to WordPress from inside the Jquery part of my plugin.
At present, there is a variable called res that contains all the HTML for the page.
$.post( templateUrl + "templates/template2.html", function( data ) {
tinyMCE.triggerSave();
var res = data.replace("[([PREHEADER])]", $("#peg-newsletter-preheader").val())
res = res.replace("[([HEADING])]", $("#peg-newsletter-heading").val());
});
Any help is appreciated.
Thanks.
You are using post incorrectly.
This section of the function
function( data ) {
tinyMCE.triggerSave();
var res = data.replace("[([PREHEADER])]", $("#peg-newsletter-preheader").val())
res = res.replace("[([HEADING])]", $("#peg-newsletter-heading").val());
})
is a call back (meaning this is a response you get from WP after you make a successful post). Changing values here only changes the values that you receive rather than wp.
To 'talk' to wp you need to post the data in the body: http://api.jquery.com/jquery.post/
So your jquery post will look like this:
$.post( templateUrl + "templates/template2.html",
{ preHeader: "something", Header: "something" },
function( data ) {
alert("Post successful");
});
However this would assume that your end point allow for a post request to do what you want.
I am not sure what you are trying to achieve though. It looks like you want to change the HTML template of WP? If so I don't know of any rest api that would allow you to do that, as these api's are primarily for pulling WP Posts/Blog data from WP. HTH
Related
I know this question had been asked many times in here, i tried each one of it but it just couldn't work.
I have a website application hosted under https://app.yyy.com, and another one which is basically just a receipt template, which i put inside the mine.com web server. The receipt template has its own script on it, and its URL is https://yyy.com/receipt/receiptTemplate.html. I'm telling all these details because i read that templates that are hosted under the same domain may be subjected to CORS issue when trying to pass data from one window to another.
My requirement is to pass data object from the website application to the receipt template, in which the script will get the object data and render it to the template.
I have the following in the wesbite application script, which is to make a call to fetch data, and open up the receipt template upon successful call. I also tried to attach the data by using window.opener (as suggested by one of the answer that i found in here.
$.get('/getdata', function(data) {
var invoice = window.open('https://yyy.com/receipt/receiptemplate.html');
window.opener.receiptdata = data;
});
And on the receipt script, i have the following
$(document).ready(function(){
var data = window.receiptdata;
generateReceipt(data);
});
But the above couldn't work.
I tried the following with localStorage this time, also suggested by the answer that i found in here..
$.get('/getdata', function(data) {
var invoice = window.open('https://yyy.com/receipt/receiptemplate.html');
localStorage.setItem('receiptdata', data);
});
$(document).ready(function(){
var data = localStorage.getItem('receiptdata');
generateReceipt(data);
});
But didn't work too.
I dunno how else can i pass the object data to the other page... =(
You have a typo to begin with: window in window.opener.receiptdata = data; is your current window, you want to access the window object you just created: invoice.
$.get('/getdata', function(data) {
var invoice = window.open(generateURL(), '');
invoice.receiptdata = data;
}
As a fiddle since StackSnippets won't allow popups.
But for this to work, since you are hosting the two pages on different subdomains, you may need to change their origin:
document.domain = 'yyy.com';
Now, if these were hosted on completely different domains, you would have to use postMessage:
var invoice = window.open('https://yyy.com/receipt/receiptemplate.html');
invoice.postMessage(receiptdata, 'app.yyy');
and in your template
addEventListener('message', e => {
if(e.origin === 'http://app.yyy.com') {
window.receiptdata = e.data;
}
});
I have a script sending a matrix, something like [[1,2,3,4], [7,6,5,4], [2,3,4,5]]. When I send it using res.send(JSON.stringify(dataArray)); and display it in jade using h1#results I do indeed see the format is correct.
However I would like to use this data inside the google charts. My intuition would say to present the data like this: data.addRows = results;. This is however not the case because jade doesn't understand that I mean the variable send.
I suspect I do not understand some basic principle behind jade. I understand that most of jade/html is fixed and that only code within "script" tags get executed but as far as I can see all code inside google's function drawChart() {) is within a script tag.
EDIT
My new ajax script:
$(function() {
$('#search').on('keyup', function(e){
if(e.keyCode === 13) {
var parameters = { search: $(this).val()};
$.get('/seraching', parameters, function(data) {
$('#results').html(data);
console.log('parsing json');
var chartData = (data);
console.log(chartData[0])
drawChart(chartData, parameters.search);
});
}
});
});
So, there several issues at play here. First, using Express and Jade to deliver a processed template, using AJAX with a search parameter to get some data, and using an Express route to send some data based on the search parameter you send it.
Initially you want Express and Jade to set up the main page:
main.jade
html
head
script(src='googlechart.js')
script(src='myJS.js')
body
title Title
h1 Heading
input("type='text', id='search'")
button("id='submit'")
So here we ensure that Google chart is loaded as well as the JS that will contain your AJAX call. I've also included the text box for the search parameter.
In your Express app you would render the page like this:
app.get('/', function (req, res) {
res.render("main.jade");
});
myJS.js
First set up the chart object. Then, when the submit button is clicked, use the value of the search field in the ajax data property. Once the promise is resolved, display the results.
var chart = new google.visualization.DataTable();
$('#submit').click(function () {
var param = $('#search').val();
$.ajax({
url: '/getdata',
dataType: 'JSON',
data: { search: param }
}).done(function (data) {
// note that jQuery automatically parses JSON for you
chart.addRows(data);
});
});
But! In order to do this you need to set up a route in Express to handle the AJAX call which would look like:
app.get('/getdata', function (req, res) {
var param = req.param('search');
// filter data by search param
res.send(JSON.stringify(data));
});
So, you only need Jade once to set up the main template. It's the Express routes that you need to deliver the JSON data when you submit an AJAX request.
Hope that's a better answer :) Oh, there might be a couple of typos in here because I've not used Express for a while, but I'm pretty sure it's correct.
If I have a HTML or a JSP page having list of sports like below.
Tennis
Football
Hockey
Cricket
All these 4 should be a Link. If I click on any of them it should return some details wherever clicked. For this I need to pass this sport name to a REST client which will pass this as a parameter to a rest service.
My question is how to pass the value of a link whichever clicked from HTML page to a Java application like we pass text box or check box values from HTML using the form action? Or is there any better approach, please suggest
I suggest you to look at jQuery.ajax. Basically you'll want to create an XHR (GET, POST etc depending on the rest client configuration) and send your data.
Here is a very crude example on the subject;
$('.sports').on('click', function() {
var clickedElementText = $(this).text();
$.ajax({
url: "/your/endpoint/url",
method: "POST",
data: {
sportName : clickedElementText;
},
}).success(function( response ) {
/* success callback */
}).failure(function( jqXHR, textStatus ) {
/* failure callback */
});
}
Ajax is a good way or you can just define the element
<a href="/sports/detail?sportName=tennis">
I am working on a social networking site where user Posts are displayed on the home page. They can be liked and commented on. If a post is liked,
it updates the like table through AJAX and have like count incremented by one.
AJAX code:
$(".mlike").click(function () {
$(".murconform").submit(function(e){
return false;
});
var $this=$(this);
var post_id = $(this).val();
var user_id = $(".user_id").text();
alert('Post: '+post_id +' User: '+user_id);
var request = $.ajax({
url: "likes.php",
type: "POST",
data: { post : post_id , user : user_id },
dataType: "html"
});
request.done(function( msg ) {
$this.prev('.likecount').html( msg );
});
});
In the home.php page I have some PHP variables ($userID, $userName) that are data fetched from MySQL and they all work fine but they
don't work with the variables ($viewedUserID, $viewedUserName) in the user.php. In the user.php, only posts related to profile been
viewed are fetched but when you press the like button and try to comment on any of the post it says undefine variables; $viewedUserID, $viewedUserName. And these
variables are defined from the beginning of the page in user.php.
I have been thinking of what might be the possible cause of this and was also thinking the AJAX was suppossed to have effect on the clicked
button only.
NOTE: The alert works just fine.
Thanks in advance.
Was going to write as a comment, but I guess an answer will be clearer:
Ajax
How does AJAX work?
I think you're getting confused with what Ajax's job is. The problem is Ajax is literally just a connector between your front-end (JS / HTML) and back-end (PHP / Rails etc)
Your statements that "Ajax isn't updating MYSQL" lead me to believe you're relying on Ajax to update your table. It won't
Your table will update by using PHP, which is why most of the comments are focused on the PHP & not the JS
PHP
Your Ajax needs to send the correct data to PHP, but then it's your server-side scripts' job to sort it all out, sending a worthy response
Your JS looks like it will work well, but I think your problem will be with your backend. If you update your question with your PHP you'll get a lot more clearer answers!
I have built a calendar in php. It currently can be controlled by GET values from the URL. Now I want the calendar to be managed and displayed using AJAX instead. So that the page not need to be reloaded.
How do I do this best with AJAX? More specifically, I wonder how I do with all GET values? There are quite a few. The only solution I find out is that each link in the calendar must have an onclick-statement to a great many attributes (the GET attributes)? Feels like the wrong way.
Please help me.
Edit: How should this code be changed to work out?
$('a.cal_update').bind("click", function ()
{
event.preventDefault();
update_url = $(this).attr("href");
$.ajax({
type : "GET"
, dataType : 'json'
, url : update_url
, async : false
, success : function(data)
{
$('#calendar').html(data.html);
}
});
return false;
});
Keep the existing links and forms, build on things that work
You have existing views of the data. Keep the same data but add additional views that provide it in a clean data format (such as JSON) instead of a document format (like HTML). Add a query string parameter or HTTP header that you use to decide which view to return.
Use a library (such as YUI 3, jQuery, etc) to bind event handlers to your existing links and forms to override the normal activation functionality and replace it with an Ajax call to the alternative view.
Use pushState to keep your URLs bookmarkable.
You can return a JSON string from the server and handle it with Ajax on the client side.