How to post data to iframe with Jquery - javascript

How can I dynamically post data to an iframe in Jquery.
I really need to post data to an Iframe in this case, I cannot use a $.POST because data received is returned sequentially (buffered)
If you have a workaround to make jquery handle data returned by a $.POST 'when it receives the data. I'm very curious!
At the moment I handle it with GETS this way:
var iframe = $('<iframe style="display:none;"></iframe>');
$( "body" ).append(iframe);
iframe.attr('src','server.php?type=getFolders&inode='+nodeData.inode).load(function(){$(this).remove()});
This basically creates a temporary iframe and lets the php inject javascript in it (using ob_flush();flush(); )while it is returning data, then when it's finished, it simply removes the iframe to clean up.
from within the iframe, I access the main frame with window.parent. then the mainframe's methods.
this is ideal but works with GET, how can I make this work with POST ?

This function creates a temporary form, then send data using jQuery :
function postToIframe(data,url,target){
$('body').append('<form action="'+url+'" method="post" target="'+target+'" id="postToIframe"></form>');
$.each(data,function(n,v){
$('#postToIframe').append('<input type="hidden" name="'+n+'" value="'+v+'" />');
});
$('#postToIframe').submit().remove();
}
target is the 'name' attr of the target iFrame, and data is a JS object :
data={last_name:'Smith',first_name:'John'}

Ok, so as this apparently doesn't exist, I created my own solution. Sharing it here in case anybody wants to POST to an iFrame in jQuery.
the js function/ class-like:
function iframeform(url)
{
var object = this;
object.time = new Date().getTime();
object.form = $('<form action="'+url+'" target="iframe'+object.time+'" method="post" style="display:none;" id="form'+object.time+'" name="form'+object.time+'"></form>');
object.addParameter = function(parameter,value)
{
$("<input type='hidden' />")
.attr("name", parameter)
.attr("value", value)
.appendTo(object.form);
}
object.send = function()
{
var iframe = $('<iframe data-time="'+object.time+'" style="display:none;" id="iframe'+object.time+'"></iframe>');
$( "body" ).append(iframe);
$( "body" ).append(object.form);
object.form.submit();
iframe.load(function(){ $('#form'+$(this).data('time')).remove(); $(this).remove(); });
}
}
then when you need to send a form to a temporary iframe :
var dummy = new iframeform('server.php');
dummy.addParameter('type','test');
dummy.addParameter('message','Works...');
dummy.send();
This is the server.php example file :
if($_POST[type] == 'test')
{
header( 'Content-type: text/html; charset=utf-8' );
echo '<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>';
echo str_pad('',4096); //fill browser buffer
for($i = 0; $i < 10; $i++)
{
echo '<script type="text/javascript">window.parent.console.log(\''.$_POST[message].'\');</script>';
ob_flush(); flush();
usleep(350000);
}
}
And the result is as expected:
the main frame's console outputs the string 'Works...' every 350ms starting immediately, even if the php is still running.
When the php is finished sending the chunks, it simply removes the temporary form and the temporary iframe.

Either you can use target method or use AJAX for the above work
<form action="..." target="an_iframe" type="post">
<input type="text" name="cmd" placeholder="type a command here..." />
<input type="submit" value="Run!" />
</form>
<iframe id="an_iframe"></iframe>

Related

passing data using post array in java-script

i am try to load B.php from A.php after execution in the function and pass some data using a post array from A.php to B.php within same time.
code list as follows
A.php
<script type="text/javascript">
alert_for_the_fucntion();
window.location.href = "B.php";
function alert_for_the_fucntion() {
$.post("B.php", {action: 'test'});
}
</script>
B.php
<?php
if (array_key_exists("action", $_POST)) {
if ($_POST['action'] == 'test') {
echo 'ok';
}
}
?>
for testing purpose i tried to echo something in the B.php. but currently this is not working. have i done any mistakes? or is there any possible method to do this.
Your code does this:
Tells the browser to navigate to B.php (using a GET request)
Triggers a POST request using XMLHttpRequest
The POST request probably gets canceled because the browser immediately leaves the page (and the XHR request is asynchronous). If it doesn't, then the response is ignored. Either way, it has no effect.
You then see the result of the GET request (which, obviously, doesn't include $_POST['action']) displayed in the browser window.
If you want to programmatically generate a POST request and display the result as a new page then you need to submit a form.
Don't use location. Don't use XMLHttpRequest (or anything that wraps around it, like $.ajax).
var f = document.createElement("form");
f.method = "POST";
f.action = "B.php";
var i = document.createElement("input");
i.type = "hidden";
i.name = "action";
i.value = "test";
f.appendChild(i);
document.body.appendChild(f);
f.submit();
If you want to process the results in JavaScript then:
Don't navigate to a different page (remove the line using `location)
Add a done handler to the Ajax code
e.g.
$.post("B.php", {action: 'test'}).done(process_response);
function process_response(data) {
document.body.appendChild(
document.createTextNode(data)
);
}
Try this:
Javascript:
<script type="text/javascript">
window.onload = alert_for_the_fucntion;
function alert_for_the_fucntion() {
$.post("B.php",
{
action: 'test'
},
function(data, status){
if(status=="success"){
alert(data);
}
}
);
}
</script>
PHP
<?php
if(isset($_POST['action'])){
echo $_POST['action'];
}
?>

Get a value of a form without $_POST or $_GET methods

I am writing a wordpress page with usage of javascript, jQuery and PHP. It generates a QRcode out of passed values to the page. After it is generated, I extract an src of a QRcode which is in data:image/png;base64 format. The problem is in passing this string to PHP without using any methods. I need it to form a HTML formated email, which is sent when page is loaded. I am not familiar with AJAX, but I know that there is a URL() method, which can pass values to the PHP functions?
Here is a code I wrote (yes, it is redundant and untidy...):
Be sure to save it onto your device and show it when you arrive!
<div id="qrcode"></div>
<form method="post">
<input type="text" name="image" id="image"></input>
<input type="submit" value="Send to e-mail"></input>
</form>
[gravityform id="3" title="false" description="false"] //Hidden form with values for QRcode
<script type="text/javascript" src="http://yourjavascript.com/10124121272/qrcode.js"></script>
<script>
var email = document.getElementById("input_3_1").value;
var date = document.getElementById("input_3_2").value;
var type = document.getElementById("input_3_3").value;
var id = document.getElementById("input_3_4").value;
var qrcode = new QRCode("qrcode", {
text: "Email of buyer: "+email+"; Type of an offer: "+type+"; Date of purchase: "+date+"; ID: "+id,
width: 256,
height: 256,
colorDark : "#000000",
colorLight : "#ffffff",
correctLevel : QRCode.CorrectLevel.H
});
jQuery(document).ready(function( $ ) {
var image = jQuery('img[alt="Scan me!"]').attr('src');
jQuery('#image').val(image);
});
</script>
[insert_php]
add_filter( 'wp_mail_content_type', 'wpdocs_set_html_mail_content_type' );
$to = $_GET[email];
$image = Some magical approach to get base64 image from form name="image"
$subject = 'Subject of an email';
$message = '<html><head><body>
<h1>Hello! Here is your QRcode!</h1>
<img src=$image />
</body></head><html>'
wp_mail( $to, $subject, $message );
remove_filter( 'wp_mail_content_type', 'wpdocs_set_html_mail_content_type' );
function wpdocs_set_html_mail_content_type() {
return 'text/html';
}
[/insert_php]
The problem is in passing this string to PHP without using any methods.
The method/verb is a key part of an HTTP request which is required if you want to send data to your PHP script. You must make an HTTP request of some sort.
You can easily use AJAX to get your data to your script.
$.post(
'/yourScript.php'
qrCodeStringData
'text/plain'
).then(function () {
// Do something if successful
}).catch(function () {
// Do something if failure
});
Also, I get the impression that you're inventing your own data format in that QR code. I recommend using JSON so you don't have to worry about structuring your data. (What if someone sticks a semicolon in your data? Suddenly your format is unusable. Using a well known format like JSON means you don't have to deal with it.)

Basic form submission with jquery/ajax not working

I'm new to jquery and ajax. I'm trying to get my first ajax script to work, but it's not working and I need some assistance, please.
I have a php page that is supposed to post to another php page, where the latter will do some processing and get some files to get zipped and download. The user needs to input a starting and ending date, and the second php script will use this information to prepare the data. This functionality works perfectly fine without jquery, but doesn't work when I add jquery.
What do I want to achieve? I want to post in the to the same php page and get the post output in a <div></div> tag.
My first php page contains (downloadPage.php):
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<form action="doDownload.php" method="post" id="dateRangeID">
<input id='time1' class='input' name="datefield1" style="text-align:center;"/>
<input id='time2' class='input' name="datefield2" style="text-align:center;"/>
<input type="submit" value="Download Data" name="submit" id="submitButton">
</form>
<div id="result"></div> <!-- I would like it to post the result here //-->
The second page (doDownload.php),
<div id="content">
<?php
if(isset($_POST['submit']))
{
$dateVal1 = $_POST['datefield1'];
$dateVal2 = $_POST['datefield2'];
if($dateVal1 != $dateVal2)
{
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename="file.zip"');
$fullListOfFiles = $downloadFullTmpFolder.$filesList;
$command = "sudo $ldlib -u myuser /usr/bin/python3 $downloadScriptFile -datadir $gnomeDataDir -time1 $dateVal1C -time2 $dateVal2C -outdir $downloadFullTmpFolder > debug_download.txt 2>&1";
$output = shell_exec($command);
$fp = popen('cat '.$fullListOfFiles.' | sudo -u myuser zip -# -9 - ', 'r');
$bufsize = 1024;
$buff = '';
while( !feof($fp) )
{
$buff = fread($fp, $bufsize);
echo $buff;
}
pclose($fp);
}
else
{
echo("<p>Dates have to be different in order for the download to start.</p>");
}
}
else
{
echo("<p>Error: Page called without submit.</p>");
}
?>
</div>
Finally, the jquery part in downloadPage.php, which if I add it doesn't work anymore (which I'd like to learn how to do right, and I mainly learned from the manual of jquery, the last example in the link)
<script>
/* attach a submit handler to the form */
$("#dateRangeID").submit(
function(event)
{
event.preventDefault();
var $form = $(this),
t1 = $form.find("input[name='datefield1']").val(),
t2 = $form.find("input[name='datefield2']").val(),
subm = $form.find("input[name='submit']").val(),
url = $form.attr('action');
var posting = $.post(url, { datefield1: t1, datefield2: t2, submit: subm} );
/* Put the results in a div */
posting.done(function(data) {
var content = $(data).find('#content'); // <--- So this turns out to be wrong. Right is only $(data);
$("#result").empty().append(content);
});
});
</script>
What is wrong in this? Please assist. Thank you.
If you require any additional information, please ask.
Looking at the obvious, you have:
var content = $(data).find('#content');
where, you're trying to find an element with the ID content in one of the following results:
<p>Dates have to be different in order for the download to start.</p>
or
<p>Error: Page called without submit.</p>

post data to PHP page in external server and load content from JavaScript in local computer

I want to post data to a PHP file in a server (www.domaine.com) using a JavaScript located in computer / mobile app
example : test.php
<?php
$x = $_POST['count'];
for ($i = 0; $i < $x; $x++)
echo $x;
?>
data to be post using JavaScript and PSOT method to test.php
example
input
test.php / post data : count=5
output
01234
I want JavaScript to get me the output (01234) after posting (count=5) to (test.php) located in external server (www.domaine.com)
I basically develop in C# but as I'm obliged to do a cross-platform mobile app I switched to JavaScript (won't use Xamarin) for C# I was able to do everything using WebBrowser but not anymore in JavaScript, isn't there any object equivalent to WebBrowser in .NET ?
I need it for a mobile app that will load data from GPS Tracking website, API returns data in both XML and JSON
note : I don't have access to the external server
Here I'll give you a pretty good example of how these things are usually managed.
Still, it's up to you and your programming experience to grasp the meaning of it.
html and js example:
<form action="" id="formId" method="post" accept-charset="utf-8">
<label for="inputNumber">Input something: </label>
<input type="number" id="inputNumber" name="count"></input>
</form>
<span id="submit">Submit</span>
<script>
var getPhpResponse = function( data ) {
console.log("manage php response HERE");
}
$("#submit").click(function(){
$("#formId").submit();
});
$(document).ready(function () {
$("#formId").bind("submit", function (event)
{
$.ajax({
async: true,
data: $("#formId").serialize(),
success: function(data, textStatus) {
getPhpResponse( data )
},
type:"POST",
url:"name/and/location/of/php/file.php"
});
return false;
});
});
</script>
file.php example:
<?php
$x = $_POST['count'];
echo '{"response":"';
for ($i = 0; $i < $x; $i++)
{
echo $i;
}
echo '"}';
Poxriptum:
There should be further input validation, one can't trust the type="number" just yet.
That the submit button is a span instead of an input is a personal choice that makes difference just for styling purposes.
You should read up on AJAX and JSON.
Consider using a PHP framework, such as CakePHP; it may serve you well.
This answer assumes you have access to the server. If you don't, then you should be reading the API documentation instead of asking questions on SO without even detailing which API you are talking about.
Edit:
Here is the $less version.
<form action="" id="formId" method="post" accept-charset="utf-8">
<label for="inputNumber">Input something: </label>
<input type="number" id="inputNumber" name="count"></input>
</form>
<span id="submit">Submit</span>
<script>
document.getElementById("submit").onclick = function () {
var url = 'name/and/location/of/php/file.php';
var userInput = encodeURIComponent(document.getElementById("inputNumber").value);
var data = "count=" + userInput;
makeRequest( data, url );
};
var getPhpResponse = function( data ) {
console.log("manage php response HERE");
console.log(data);
parsed = JSON.parse(data);
console.log(parsed);
}
var xhr = new XMLHttpRequest();
var makeRequest = function( data, url ) {
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.send(data);
};
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if ( xhr.readyState == 4 )
{
if ( xhr.status == 200 || window.location.href.indexOf("http") == -1 )
{
getPhpResponse(xhr.responseText);
}
else
{
console.log("Manage error here");
}
}
}
</script>

Executing php script on button click and returning value by ob_start

I have button which in enclosed by <a> tag. When clicked, it executes redirect.php script.
login.php - contains
<input type = "button" id = "loginButton2" class = "btn btn-primary" value = "Login | Twitter " style = "left:650px; margin-top: -32px; position:relative"/>
redirect.php contains twitter authentication code. If authenticated successfully then gives id and name. I want to fetch these both value in index.php
Using ob_start(); I can receive values from php script to JS function via json.
But I am confused about how to manage the code in index.php to execute script on button click and receiving these two value also.
redirect.php
<?php
session_start();
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');
if (empty($_SESSION['access_token']) || empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret'])) {
header('Location: ./clearsessions.php');
}
$access_token = $_SESSION['access_token'];
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$content = $connection->get('account/verify_credentials');
$twitteruser = $content->{'screen_name'};
$notweets = 5;
$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets);
$id = $content->{'id'};
$name = $content->{'name'};
?>
Please let me know if you need further explaination.
Bottomline:
Rather executing redirect.php script on link click, I want it to execute via function on button click event.
Getting id and name from redirect.php to index.php after redirect script executed
I already have session_start() to manage the twitter session. So dont want to mess up using mutiple session if not necessary ..
UPDATE after david's answer
<body>
<input type="button" value="Run somePHPfile.php" id = "b1" />
<script>
$('#b1').click(function () {
window.location.href = 'redirect.php';
$.get('index.php', function(data) { //If I put this out side click then it gives undefined value for name and id before redirect.php gets executed
// data.id is the id
var id= data.id;
var name = data.name;
alert(name);
});
});
</script>
</body>
Apologize to say:
On button click redirect.php script executed. redirect.php includes other files, which finally reach to index.php. And index.php returns name and id.
So is this enough to manage it : $.get('index.php', function(data) { ... }
To bind to a click event of an HTML button, you would use JavaScript. Since you tagged the question with jQuery, I'll assume its use. The event handler would look something like this:
$('#loginButton2').click(function () {
window.location.href = 'redirect.php';
});
Note: This simulates an anchor click effectively. If you instead want to more closely resemble an HTTP redirect, you might want to use this instead:
window.location.replace('redirect.php');
As for the id and name values, how exactly does this flow return the user to index.php in the first place? Your redirect.php has, well, a redirect (though not all code paths result in that) so it kind of assumes non-AJAX interaction. (I think XHR follows redirects sometimes, but the behavior is different from one browser to another.)
If the redirect isn't terribly important and you just want to make an AJAX call to redirect.php, then you can do that with a simple AJAX request:
$.get('redirect.php');
In order to get those values back to the page, they'll need to be emitted from redirect.php. Something like this:
echo json_encode((object) array('id' => $id, 'name' => $name));
Then in the client-side code you would have those values available in the AJAX callback:
$.get('redirect.php', function(data) {
// data.id is the id
// data.name is the name
// use these values client-side however you need
});
<script>
$("#loginButton2").on('click',function(){
window.location.href="redirect.php";
});
</script>
and in redirect.php file
$_SESSION['id']=$id ;
$_SESSION['name']=$name;
and also
<input type = "button" id = "loginButton2" class = "btn btn-primary" value = "Login | Twitter " style = "left:650px; margin-top: -32px; position:relative"/>
to
<input type = "button" id = "loginButton2" class = "btn btn-primary" value = "Login | Twitter " style = "left:650px; margin-top: -32px; position:relative"/>

Categories

Resources