How can I send POST data and navigate with JQuery? - javascript

On my blog I have a lot of <pre> blocks containing code snippets.
What I want to do is add a .click() handler to all the <pre> elements on the page which will send its content to another page - let's call it viewcode.php - via POST.
I know how to send information to this page using $.ajax, I'm just not sure how to send the information and navigate to the page.
The idea is that visitors can click a <pre> which will navigate to another page containing the code on its own for readability and easy copy / paste.
I have a feeling the solution is dead simple and probably obvious, I just can't think of it.

Not sure I would handle it this way, probably I would simply pop up a dialog with the code rather than leave the page, but you could handle this by building a form using javascript then triggering a submit on that form instead of using AJAX.
Using dialogs with jQuery UI:
$('pre').on('click', function() {
$('<div title="Code Preview"><p>' + $(this).text() + '</p></div>').dialog({
... set up dialog parameters ...
});
});
Build a form
$('pre').on('click', function() {
var text = $(this).text();
$('<form class="hidden-form" action="something.php" method="post" style="display: none;"><textarea name="code"></textarea></form>')
.appendTo('body');
$('[name="code"]').val(text);
$('.hidden-form').submit();
});

You could use a hidden <form> element. Then set the onclick() attribute of the <pre> to copy the value from the <pre> to the form. Optionally, you can set the action attribute to select the page you'd like to post the information to. Finally, submit that form.
I know it's not elegant, but it'll work.

If your code snippets are stored somewhere in a database or files, I suggest you just link the snippets to a page where you get the snippet based on some identifier.
If the snippets are only contained in your html, and you just want to display them in a cleaner way, you shouldn't need any ajax posting. You might want to Use a hover div or a jquery plugin, that pop's up and shows a cleaner piece of code obtained from the pre element, something like:
$('pre').click(function() {
var code = $(this).html(); //this is the pre contents you want to send
$('#hoverDiv').html(code).show();
});

Yes, you have to create a form and submit it. You can do all sorts of things with ajax posts/gets but the only way to navigate to a post result is via an actual form post. Here is concise version of it:
$('<form style="display: none;"/>').attr('action', action).html(html).appendTo('body').submit();
My code does this:
// Navigate to Post Response, Convert first form values to query string params:
// Put the things that are too long (could exceed query string limit) into post values
var form = $('#myForm');
var actionWithoutQueryString = form[0].action.split("?")[0];
var action = actionWithoutQueryString + '?' + $.param(form.serializeArray());
var html = myArray.map(function(v, i) { return "<input name='MyList[" + i + "]' value='" + v + "'/>"; }).join("\n");
$('<form style="display: none;"/>').attr('action', action).html(html).appendTo('body').submit();

Related

Html and Javascript send email with text element

I have a form on sharepoint, that whenever a person fills that form, it will create a new page with the text added on the form.
I wanted to send an email using JavaScript and HTML with the copy of the various texts.
I have the id of the text and when i create the javascript code, it does not work.
HTML
<a onclick="javascript:sendEmailJobs()" class="mailto"></a>
JavaScript
function sendEmailJobs(){
var JobCodePost = document.getElementById("RichHtmlFieldJobPostCodeJob").body;
window.location.href = "mailto:?subject=Job Offer &body=" + body;
}
The id of said text is this:
<SharepointWebControls:NoteField ID="RichHtmlFieldJobPostCodeJob" FieldName="JobPostCode" runat="server"/>
Am i doing something wrong?
Document elements don't have a "body" attribute, they have innerHTML and innerText. So your function should look like this:
function sendEmailJobs(){
var JobCodePost = document.getElementById("RichHtmlFieldJobPostCodeJob").innerText;
window.location.href = "mailto:?subject=Job Offer &body=" + JobCodePost;
}
Second thing is to verify that you are indeed selecting the correct element. Third thing is to point out that you can't use innerHTML because even if you get everything else right, mailto: links don't support formatted text.

PHP echo appears to work but doesnt show up in HTML

I am trying to use a php script to generate HTML in order to save lines and what not. I am using jQuery to call my php and then put the result into a specified div as shown below:
function createSidebarRow(div, cellNum, rowName, rowDesc) {
$("#" + div).load("createIndexSidebarRow.php?cellNum=" + cellNum + "&rowName=" + rowName + "&rowDesc=" + rowDesc);
}
However, when this is executed the HTML is not updated on the page, I can see that the code has worked because the browser network activity confirms it. I am trying to figure out what is causing it to not update.
This is the network activity confirming the echo'd HTML.
Sorry for stating the obvious, but the div you are trying to fill up does exist with that particular id right?
If so, try this:
$("#" + div).load("createIndexSidebarRow.php?cellNum=" + cellNum + "&rowName=" + rowName + "&rowDesc=" + rowDesc, function() {
alert('success');
});
If the id does exist (and it's unique) and you get an alert there should be no reason for it not to work.
It might be so, that the div is not yet created in the DOM. (the div that should received the html).
Are you calling createSidebarRow directly on page load?
If so, put the function call in a document ready:
jQuery(document).ready(function(){
createSidebarRow (... );
});
Turns out jQuery doesn't play ball when you include spaces in the POST URL. I removed the space and used %20 instead and all is well now. Thanks for any advice.

Can jQuery or Javascript change elements within textareas?

My first SO question! Here's what I am trying to do:
I'm rewriting a tool that generates some code a user can paste directly into Craigslist and other classified ad posting websites. I have created a list of websites (they populate from a database with PHP) the user can choose from with a radio button, and I want their choice to populate as bare text (not a link) between some <p></p> elements in a textarea. I'm using jQuery for this.
Textarea before the user chooses:
<p id="thing"></p>
Textarea after the user chooses:
<p id="thing">www.somewebsite.com</p>
HTML
<input type="radio" name="sitechoice" value="www.websiteone.com">www.websiteone.com<br />
<input type="radio" name="sitechoice" value="www.secondwebs.com">www.secondwebs.com
<textarea>
Some stuff already in here
Here is the website you chose:
<p id="thing"></p>
More stuff already here.
</textarea>
JS
$(document).ready(function () {
$("input").change(function () {
var website = $(this).val();
alert(website);
$("#thing2").html(website);
});
});
JS Fiddle (With comments)
If you see the JS Fiddle, you can see that I put another p element on the page outside the textarea, and it updates just fine, but the one inside the textarea does not. I have read many other like questions on SO and I'm starting to think that I can't change an element that's between textarea tags, I can only change the entire textarea itself. Please, lead me to enlightenment!
You actually can fairly easily manipulate the text contents of the textarea like it is part of the DOM, by transforming its contents into a jQuery object.
Here is a jsFiddle demonstrating this solution: http://jsfiddle.net/YxtH4/2/
The relevant code, inside the input change event:
// Your normal code
var website = $(this).val();
$("#thing2").html(website);
// This turns the textarea's val into a jQuery object ...
// And inserts it into an empty div that is created
var textareaHtml = $('<div>' + $("#textarea").val() + '</div>');
// Here you can do your normal selectors
textareaHtml.find("#thing").html(website);
// And this sets the textarea's content to the empty div's content
$("#textarea").val(textareaHtml.html());
The empty div wrapping your HTML is so that you can easily retrieve it as a string later using jQuery's .html() method, and so the parse does not fail if additional text is entered around the p element inside the textarea.
The real magic is $($("#textarea").val()), which takes your textarea's text and parses it into an HTML node contained in a jQuery object.
It can't do it the way that you are thinking (i.e., manipulate it as if it were a DOM element), but it is still accessible as the value of the textarea, so you can retrieve it like that, use basic string manipulation to alter it, and then set the updated string as the new value of the textarea again.
Something like this . . . first give the <textarea> an id value:
<textarea id="taTarget">
Some stuff already in here
Here is the website you chose:
<p id="thing"></p>
More stuff already here.
</textarea>
Then alter your script like this:
$(document).ready(function () {
$("input").change(function () {
var website = $(this).val();
var currentTAVal = $("#taTarget").val();
$("#taTarget").val(currentTAVal.replace(/(<p id="thing">)([^<]*)(<\/p>)/, "$1" + website + "$3"));
});
});
Unless you need the <p> element in there, you might consider using a more simple placeholder, since it won't actually act as an HTML element within the textarea. :)
EDIT : Fixed a typo in the .replace() regex.
I know that this answer is a little bit late, but here it goes =)
You can do exactly the way you want to do. But for that, you need to implement a small trick.
by having this HTML
<input type="radio" name="sitechoice" value="www.websiteone.com">www.websiteone.com
<br />
<input type="radio" name="sitechoice" value="www.secondwebs.com">www.secondwebs.com
<p id="thing2"></p>
<textarea id="textarea">
<p id="thing"></p>
</textarea>
you can edit textarea content, as a DOM by implementing something like the function changeInnerText
$(document).ready(function () {
$("input").change(function () {
var website = $(this).val(); // Gets value of input
changeInnerText(website);
//$("#thing").html(website); // Changes
//$("#thing2").html(website); // Does not change
});
var changeInnerText = function(text) {
var v = $("#textarea").val();
var span = $("<span>");
span.html(v);
var obj = span.find("#thing")[0];
$(obj).html(text);
console.log(obj);
console.log(span.html());
$("#textarea").val(span.html());
}
});
As you can see, I just get the information from the textarea, I create a temporary variable span to place textarea's content. and then manipulate it as DOM.
Instead of attempting to insert the text into the <p> element, insert the text into <textarea> element and include the <p> tag. Something like this should do the trick:
Change:
$("#thing").html(website);
to:
$("textarea").html('<p id="thing">'+website+'</p>');
And here is a fiddle: http://jsfiddle.net/nR94s/

JQuery/Javascript how to Parse HTML using a Get

I have the following working code. This displays a drop down and also fetches a html file to be displayed:
$.getJSON('json/shares.json', function(data) {
var items = [];
$.each(data.Shares, function(key, val) {
items.push('<option id="' + val.shareID+ '">' + val.shareID+ '</option>');
});
$('<select/>', {
'id': 'shares',
html: items.join('')
}).appendTo('#shares');
});
</script>
<script type="text/javascript">
$.get('lon_shares.html', function(data){
$(data).appendTo('#shares');
});
</script>
I need to amend this to a few extra things.
Firstly, I need the drop down to auto submit when a choice is made.
I then need it to get the html file relevant to the choice, for example if they choose the "FML" option it will get the html file "FML_shares.html" if they choose "GBP" then it should get "GBP_shares.html" and finally if the choice doesn't have any html file related to it then an error should be displayed such as "no such file" etc.
Just to make it a little more complex, I don't want the whole file. The file has a table in it and I want to get the data from the first row of the table, for the first five columns of data and display those alone.
Thanks for any assistance, I've been searching for a solution for a while without any success and my JQuery/Javascript knowledge is very basic! (I've done something similar with PHP in the past but that's not an option here)
Well for the first point you could just run
$('#shares').on('change', function(){
var val = $(this).val();
//submit another ajax request with this value, and get the relevant page, then you'd just need to parse it for the appropriate content from that page.
});
If you want to parse the returned page and get only part of this we'd need to know the markup structure.
Seems like you just need to bind to the .change event of the dropdown you are creating to do the submission, which you can retrieve with .get. You can use jQuery to parse the html. It does a nice job of that:
.appendTo('#shares')
.change(function () {
$.get($(this).val() + '_shares.html)
.done(function (html) {
var $table = $(html).find("table tr:first td").slice(0,5);
})
.fail(function () { /* no such file */ });
});
This code is untested, but hopefully you can follow the example. Also beware of GET caching.

Button in list from Javascript loop throws back the of the list

I got this javascript loop which generates a unordered list with maybe 50 list items.. Now I want to put a button in every list item which stores the content in a database. Think retweet.
I figured out a way which is put the button and the content from the listitem within a hidden input in the loop but that seems like a bad shortcut. Like this:
html += "<form action=\"add.php\" method=\"post\"><input type=\"hidden\" value=\"" + listitem + "\" name=\"item\"\/>";
html += "<input type=\"submit\" value=\"repost\" \/><\/form>";
Using jQuery seems much more subtle and more like the right thing to do. I've gotten this far:
$("button").click(function()
var value = ($(this).text());
$.post('add.php',{value:value};
});
With a button in the loop instead of the input. But I can't even get the jQuery to response to the button click. Is there anyway this is possible or should I just go with the shortcut?!
The loop =
var html = "<li><h2 class=\"postTitle\">" + title + " <\/h2>";
html += "<p id=\"postText\" class=\"postText\">" + text + "</p></li>";
$('#Content').append($(html));
And the html where the loop ends up:
<ul id="list">
<div id="Content">
</div>
</ul>
From the code above the jQuery selector being used ("button") will not match anything in your code as you've used an input for the button; try:
$("input[type=submit]").click(function () {
...
});
Ideally use a more targeted selector as I presume you don't want every submit button to do this :)
Try giving your button a unique id?
resulting in:
$('#myId').click(function(){
//your code here
});
That is much better to specify.
You can also try to give it a class and an id
$('.myClass').click(function(){
var myButton = $(this).attr('id');
if(myButton == 'myId'){ do this} else if(myButton == 'myOtherId'){do this}
});
that way you can handle several buttons in one function, and if there are many buttons if statements will make your code look all messed up and you can use a select case :)
First, if you send your data via AJAX $.post, you should prevent submitting a form:
$("button[type=submit]").click(function(oEvent) {
oEvent.preventDefault();
// or in the end of handler
return false;
});
Second, <input> and <button> elements will return nothing in $(elem).text(), to get a value you should use $(elem).val() method.
Third, use the id attribute for HTML elements, this will help you manage DOM easier.

Categories

Resources