I'm not even sure if this is possible, but I need to send POST data to a page via a user-clicked link. Can this be done?
To be clear, I do not want the data returned to the current page; the target page should load in the browser just as though the user had submitted a form, but I need to send the post data without a form, if possible
What do you mean without a form? Can the form be "invisible" to the user? If so, you could do something like:
$("a.post").click(function (e) {
e.preventDefault();
$("<form action='"+this.href+"' method='post'></form>").submit();
});
Obviously it could be done many different ways, but you get the idea.
It would be just like a form with the POST parameters intact in the request just in case you use that information at the server when serving up that page.
How about a form with a hidden input? Just create a click event on the anchor tag that submits the form:
<script type="text/javascript">
$(function () {
$("#postLink").click(function () {
$("#form").submit();
});
});
</script>
<a id="postLink" href="javascript:;;">click to post</a>
<form id="form" action="[postTargetUrl]" method="post">
<input type="hidden" name="postVariable" value="[postValue]" />
</form>
I would just add the data to the url, then the target page can extract it:
Main Page:
Fred
Target page (page2.htm)
$(document).ready(function(){
var name = gup("name", window.location.href);
alert(name);
});
/* Returns URL parameter
* url: http://www.somesite.com?name=hello&id=11111
* z = gup('name', window.location.href); // z = hello
* Original code from Netlobo.com (http://www.netlobo.com/url_query_string_javascript.html)
*/
function gup(n,s){
n = n.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");
var p = (new RegExp("[\\?&]"+n+"=([^&#]*)")).exec(s);
return (p===null) ? "" : p[1];
}
Related
I have a script that works fine when a button is used to post the form. But when I convert the form to (auto)post on an interval, the form (field) values are missing when posted.
I know this has something to do with using the closest(form) as the button assists with closest (form) as a reference, but auto post on Interval has no reference for closest (form). Any help is appreciated thanks. By the way my form is on a sql while loop.
A) is the script when used with button.
B) is the script when used with a Auto(post) on interval.
The form)
<form class="updateform" action="" method="" >
<input type="hidden" class ="customerid" name="" value="<?php echo $customerid?>">
<a class ="test" >test</a>
<div class="update"> </div>
</form>
** A)**
<script>
$(document).ready(function(){
$('.test').click(function(event){
event.preventDefault();
var form = $(this).closest("form");
var field1= form.find('.customerid').val();
// Url to post to and Field name and content */
$.post('/test4.php', {customerid:field1},
// Alert Success
function(data){
// Alerts the results to this Div
form.find('.update').html(data);
});
});
});
</script>
** b)**
<script>
$(function() {
var form = $(this).closest("form");
var field1= $('.customerid').val();
function update() {
$.post("/test4.php", {customerid:field1},
function(data){
$('.update').html(data);
});
}
setInterval(update, 3000);
update();
});
</script>
It's probably because of the .closest() method in the second script. You are trying to select the form there which is closest to this up the tree. But in this case this will either be the scope of the function or the window object. Change it to a jQuery selector and select the correct form.
You can test this by yourself by either using console.log or the debugger statement to check what the values of the elements are in the developer tools of the browser. Get familiar with these guys, you'll need them a lot and are essential tools to even the most experienced developer.
If I may give a tip. Name your jQuery elements (the elements you select with $('element')) with a $ prefix. This way you know by reading the variable what kind of value that variable has. Also giving your variables meaningful names makes it even more easy to read and understand. field1 is generic, but customerIdField tells you what field it is.
$(function() {
var $form = $('form.updateform');
var $updateField = $form.find('.update')
var $customerIdField = form.find('.customerid');
var customerIdValue = $customerIdField.val();
function update() {
$.post("/test4.php", {customerid: customerIdValue}, function(data) {
$updateField.html(data);
});
}
setInterval(update, 3000);
update();
});
On my page I have a list of users. Each user has a profile page on an external site (not the same domain name). To save my client updating their profile details in 2 places, I am using PHP simple HTML Dom Parser. This gets the content of the users external profile page and returns it on my site.
What I am trying to do is load the users profile information into a div on my site only when the users name is clicked.
Each user looks like this:
<div class="actor_container" data-url="www.external-profile-url.com">
<img src="http://placehold.it/500x500" />
</div>
To get the contents of the external page I use this code:
$html = file_get_html('http://www.spotlight.com/5094-1276-6177');
echo $html->find('div.credits', 0);
Obviously this works at the minute as it is hard coded. However I need to make it dynamic so that the external profile info for each user is loaded when the relevant user is clicked.
Update from answer below:
I added this script to the top of the user list:
<script>
jQuery(function ($) {
$(".actor_container").load(function () {
return "http://79.170.44.105/samskirrow.com/nial/wp-content/plugins/nial-customizations/front-end/my.php?url=" + $(this).data("url");
});
});
</script>
then in my.php
<?php
$html = file_get_html($_GET["url"]);
echo $html->find('div.credits', 0);
Currently, when I click on a user, nothing happens
UPDATE
OK I've moved to using AJAX to access my.php. Here is what I have so far:
<script>
jQuery(document).ready(function ($) {
$('.nial_actor').on("click", function (e) {
e.preventDefault();
$.ajax({
url: "http://79.170.44.105/samskirrow.com/nial/wp-content/plugins/nial-customizations/front-end/my.php?url=" + $(this).data("url"),
type: 'GET',
success: function(res) {
var data = $.parseHTML(res);
// append all data
$('#all_data').append(data);
}
});
}); //on
}); // ready
</script>
However this returns the following error:
GET http://79.170.44.105/samskirrow.com/nial/wp-content/plugins/nial-customizations/front-end/my.php?url=undefined 500 (Internal Server Error)
So for some reason the url in data-url is not adding to the end of my ajax url. Have I missed something obvious?
Something like this works?
$(function () {
$(".actor_container").load(function () {
return "my.php?url=" + $(this).data("url");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="actor_container" data-url="www.external-profile-url.com">
<img src="...actor profile img..." />
</div>
And in the PHP file, you can add url as your GET param:
$html = file_get_html($_GET["url"]);
Note that there are lots of vulnerabilities in this methods. Keep this just as a guidance.
I am a new to programming. I like to ask that how can I retrieve the value of the <a> or text
that is hyperlinked and post it to the next page(abc.php). All of the hyperlinked $row['a'] will go to abc.php and process the data based
on the hyperlinked $row['a'] that is clicked. For now, I keep getting undefined, <a> contains
nothing?!
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("a").click(function(event) {
alert("As you can see, the link no longer took you to jquery.com");
var a = $(this).attr('a');
alert(a);
event.preventDefault();
});
});
</script>
echo "<td>"."<a href='abc.php'>".$row['a']."</a></td>";
To retrieve the content of a element you need to use $(this).text() as #Rodion suggested.
The next step will be to send that data through to abc.php by the use of query string: abc.php?ref=[...].
Consider the following Javascript code:
$(document).ready(function() {
$("a").click(function(event) {
var text = $(this).text();
alert("As you can see, the link no longer took you to jquery.com");
alert(text);
window.location.href = window.location.href + '?ref=' + text;
event.preventDefault();
});
});
It retrieves the text of the a element from the Document Object Model and then adds it to the query string of the location referenced by the link.
The last thing to do in here is to prevent the browser from instantly following the reference in href attribute of the a element: that is the plain abc.php. You can achieve this by adding the onclick attribute with return false;:
echo "<td>"."<a href='abc.php' onclick='return false;'>".$row['a']."</a></td>";
You tried to get an attribute a for the link.
If you need to get link text, use $(this).text()
var a = $(this).text();
alert(a);
You can pass text to the next page by get parameters, for example:
echo "<td>"."<a href='abc.php?text=".$row['a']."'>".$row['a']."</a></td>";
or on the client-side using window.location.href=""
Is there a way to call a (jquery action/write an html text) to a div of a new page after calling the window.location command?
Im trying to make an ajax form submit where the user will be redirected to a new page upon submit,
and in that new page a hidden div will appear with text inside of it
currently this is my code
script.js
$.ajax({
url:url,
type:'POST',
data:datastr,
success:function(result){
if(result=="duplicate"){
$("#status").attr('class', 'span12 alert alert-error');
$("#status").show();
$("#status").html("<h4><center>Duplicate Username</center></h4>");
$("#dept_name").closest(".control-group").attr('class', 'control-group');
$("#username").closest(".control-group").attr('class', 'control-group error');
$("#password").closest(".control-group").attr('class', 'control-group');
$("#username").focus();
}
else{
$("#dept_name").closest(".control-group").attr('class', 'control-group');
$("#username").closest(".control-group").attr('class', 'control-group');
$("#password").closest(".control-group").attr('class', 'control-group');
window.location = base + 'admin/departments/edit_dept/' + result;
}
}
});
i want to make this block of code below work on the page where window.location is going
$("#status").attr('class', 'span12 alert alert-error');
$("#status").show();
$("#status").html("<h4><center>Successfully added Department</center></h4>");
is it possible?
thanks
You can use CI session flash data.
http://ellislab.com/codeigniter/user-guide/libraries/sessions.html
Before triggering window.location, set the message in flashdata. On the landing/redirected-to page, check to see if flashdata has a value (success/failure). If so, display (or trigger a js method to show) the message.
You could add a parameter with your window.location, like:
window.location = base + 'admin/departments/edit_dept/' + result + '?showMessage=12'
Then on the next page, have a jquery script that looks for that parameter and shows the message. See this question.
Or you can do it in on the server. But with jquery it works with static html too.
This is a patchup, May require some tuning though.
window.location = base + 'admin/departments/edit_dept/' + result+'/err'; //changed to catchup with the view part
In the Controller:
<?php
if($this->uri->segment(4) == "err"){
$data['err'] = true; #will reflect that we need to show the js in the view
$this->load->view('view', $data);
}
?>
In the view part:
<?php if(isset($err)){ ?>
<script type="text/javascript">
$("#status").attr('class', 'span12 alert alert-error');
$("#status").show();
$("#status").html("<h4><center>Successfully added Department</center></h4>");
</script>
<?php } ?>
We have a form with five <input type="file"/> elements that is in production and working great. We get request timeouts and MaxRequestLength exceeded errors on occasion. To prevent these errors, I planned to write some Javascript to upload the files one-at-a-time instead of all at once. Here is how I planned on doing this...
On document.ready, inject a hidden iframe into page
Change the <form> to target the iframe
Disable all elements on the form (which prevents them from being POSTed)
Enable one file-upload at a time and submit the form
Wait for the response from the server
When server response is printed into iframe, start the next upload
When all uploads are done, refresh the page, which will invoke some server-side logic that populates a grid.
My problem is with number 5. Normally I think I could figure this out no problem, but I am just having one of those days where my brain is on strike. Here is my code thus far...
$(function() {
$("<iframe/>").attr("src", "test.htm").attr("name", "postMe").hide().appendTo("body");
$("form").attr("target", "postMe").submit(function(e) {
e.preventDefault();
$("#btnSubmit").attr("disabled", "disabled").val("Please Wait, Files are Uploading");
for(var i = 1; i < 6; i++) {
$("input[type=file]").attr("disabled", "disabled");
$("#FileUpload" + i).removeAttr("disabled");
$("form")[0].submit();
// HELP!!!
// How do I wait for server before next iteration?
}
location.reload(true);
});
});
What kind of construct do I need here in order to "wait" for the server response before kicking off the next upload?
I've had a lot of success lately using Uploadify--it's very configurable, free, and allows for multiple-uploads. It also provides the option for callback functions allowing you to really configure it any way you want.
http://www.uploadify.com/
I think you should listen for iframe's load event and perform input's switching in the handler. I completed with my own uploader today and this solution worked for me.
Just FYI: jquery.forms plugin is all about making ajax form submitions. I use this plugin to submit a form (such as a file upload) in a separate iframe which the plugin takes care of automatically, and gives you a nice callback when completing.
This way most work for you is done.
http://jquery.malsup.com/form/
It can be done with the help of jQuery's queue method and load event.
<!DOCTYPE HTML>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script>
//here's an upload script
(function($){
//make 'em accessible within the scope
var $iframe, $form;
$(document).ready(function(){
//create 'em only once, but use 'em many times
$iframe = $('<iframe name="iframe" id="iframe" style="display:none"></iframe>').appendTo('body');
$form = $('<form method="post" enctype="multipart/form-data" target="iframe" style="display:none"></form>').appendTo('body');
});
var iframeUpload = $({});
$.iframeUpload = function(s){
iframeUpload.queue(function(next){
//as we only wanna this new event
$iframe.load(function(){
//we must unbind the old one
$iframe.unbind('load');
//success or error, the question is up to you
s.success();
//but remember to remove or replace the old stuff
$form.find('input').remove();
next();
});
$form.attr('action', s.url).append(s.file).submit();
});
};
})(jQuery);
//and this is how to use the script
(function($){$(document).ready(function(){
$('input[type="submit"]').click(function(){
$('input[type="file"]').each(function(){
$.iframeUpload({
url: 'http://example.com/upload.php',
file: this,
success: function(){
console.log('uploaded');
}
});
});
});
})})(jQuery);
</script>
</head>
<body>
<!-- here are multiple files -->
<input type="file" name="file" />
<input type="file" name="file" />
<input type="file" name="file" />
<!-- to upload -->
<input type="submit" />
</body>
</html>
I was able to do this, by starting with the code at A Strategy for Handling Multiple File Uploads Using Javascript. That code uses an XMLHttpRequest for each file, but actually doesn't check the result from the server. I modified it to wait for the result from the server, sequentially, as follows:
var fileNumber = 0
var fileList = [] // see the code linked above for how to handle the fileList
var resultPane = document.getElementById('resultpane') // a textarea box
sendNext = function() {
if (fileNumber >= fileList.length) {
resultPane.value += 'Done uploading '+fileNumber+' files\n'
return 0
}
var formData = new FormData()
var request = new XMLHttpRequest()
request.onreadystatechange = function() {
if (request.readystate == XMLHttpRequest.DONE) {
resultPane.value += request.responseText // show whatever the server said about each file
sendNext() // and send the next file
}
}
formData.set('file', fileList[fileNumber])
request.open('POST', 'https://example.com/upload-receiver')
request.send(formData)
resultPane.value += 'Sending file number '+fileNumber+'\n'
fileNumber++
}