Is there anyway to send post data to a php script other than having a form? (Not using GET of course).
I want javascript to reload the page after X seconds and post some data to the page at the same time. I could do it with GET but I would rather use POST, as it looks cleaner.
Thanks a lot.
EDIT: Would it be possible to do with PHP header? I'm sure it is better to use JQuery but for my current situation I could implement that a lot easier/faster : )
Cheers
I ended up doing it like so:
<script>
function mySubmit() {
var form = document.forms.myForm;
form.submit();
}
</script>
...
<body onLoad="mySubmit()";>
<form action="script.php?GET_Value=<?php echo $GET_var ?>" name="myForm" method="post">
<input type="hidden" name="POST_Value" value="<?php echo $POST_Var ?>">
</form>
</body>
Seems to work fine for me, but please say if there is anything wrong with it!
Thanks everyone.
As requested above, here is how you could dynamically add a hidden form and submit it when you want to refresh the page.
Somewhere in your HTML:
<div id="hidden_form_container" style="display:none;"></div>
And some Javascript:
function postRefreshPage () {
var theForm, newInput1, newInput2;
// Start by creating a <form>
theForm = document.createElement('form');
theForm.action = 'somepage.php';
theForm.method = 'post';
// Next create the <input>s in the form and give them names and values
newInput1 = document.createElement('input');
newInput1.type = 'hidden';
newInput1.name = 'input_1';
newInput1.value = 'value 1';
newInput2 = document.createElement('input');
newInput2.type = 'hidden';
newInput2.name = 'input_2';
newInput2.value = 'value 2';
// Now put everything together...
theForm.appendChild(newInput1);
theForm.appendChild(newInput2);
// ...and it to the DOM...
document.getElementById('hidden_form_container').appendChild(theForm);
// ...and submit it
theForm.submit();
}
This is equivalent to submitting this HTML form:
<form action="somepage.php" method="post">
<input type="hidden" name="input_1" value="value 1" />
<input type="hidden" name="input_2" value="value 2" />
</form>
You can use JQuery to post to a php page:
http://api.jquery.com/jQuery.post/
By jQuery:
$.ajax({
url: "yourphpscript.php",
type: "post",
data: json/array/whatever,
success: function(){ // trigger when request was successfull
window.location.href = 'somewhere'
},
error: anyFunction // when error happened
complete: otherFunction // when request is completed -no matter if the error or not
// callbacks are of course not mandatory
})
or simplest:
$.post( "yourphpscript.php", data, success_callback_as_above );
more on http://api.jquery.com/jQuery.ajax
Use the FormData API.
From the example there:
var formData = new FormData();
formData.append("username", "Groucho");
formData.append("accountnum", 123456);
var request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php");
request.send(formData);
Form your own header, as such:
POST /submit.php HTTP/1.1
Host: localhost
User-Agent: Mozilla/4.0
Content-Length: 27
Content-Type: application/x-www-form-urlencoded
userId=admin&password=letmein
How about this:
function redirectWithPostData(strLocation, objData, strTarget)
{
var objForm = document.createElement('FORM');
objForm.method = 'post';
objForm.action = strLocation;
if (strTarget)
objForm.target = strTarget;
var strKey;
for (strKey in objData)
{
var objInput = document.createElement('INPUT');
objInput.type = 'hidden';
objInput.name = strKey;
objInput.value = objData[strKey];
objForm.appendChild(objInput);
}
document.body.appendChild(objForm);
objForm.submit();
if (strTarget)
document.body.removeChild(objForm);
}
use like this:
redirectWithPostData('page.aspx', {UserIDs: getMultiUserSelectedItems()},'_top');
You can send an xhr request with the data you want to post before reloading the page.
And reload the page only if the xhr request is finished.
So basically you would want to do a synchronous request.
Related
I need to POST a JSON ecoded string using the following parameters:
{"params":"query=ADDQUERY&hitsPerPage=6&filters=type%3Aartists"}
I have;
An endpoint URL to query;
An input search box and a search button to trigger the query. I need to replace ADDQUERY with the user input.
Can anyone shed some light on calling this info with JSON POST?
Like this,
you can copy and paste this, just make sure to change the target url, and the input boxes querySelector , if it has an ID use '#' + the box id.
Edited your fiddle. Here's the full code.
<div class="bodyparent">
<div class="searchbar">
<div class="searchbar_inner">
<div class="searchleft">
<image onclick="search()" src ="search.png"/>
</div>
<div class="searchright">
<input onchange="search()" id="searchinput" type="text" placeholder="Search...">
</div>
</div>
</div>
<div class="searchresults">
</div>
<script>
function search(){
var box = document.querySelector("#searchinput");
var json = { "params" : "query=" + box.value + "&hitsPerPage=" + 6 + "&filters=type_artists"};
var postData = JSON.stringify(json);
//this is the string you requested above.
var x = new XMLHttpRequest();
x.open("POST" , "https://ufhsub9629-dsn.algolia.net/1/indexes/search/query?x-algolia-application-id=UFHSUB9629&x-algolia-api-key=69ed687a250f4c895cc73f6ee142a42e" , true);
x.onreadystatechange = function(){
if(x.status == 200 && x.readyState == 4){
//do whatever here
}
}
x.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
x.send(JSON.stringify(json));
}
</script>
Its definitely working buddy:
I understand that you are trying to build your query using just PHP. You could look into using CURL to build the URL and send the request to a site or you could just encode the string with JS and redirect the page with the new URL.http://codular.com/curl-with-php A better option would be to send the request with AJAX and prevent a page refresh. Hope this helps. http://jsfiddle.net/codedcontainer/xpvt214o/287107/
$('form#artistForm').on('submit', function(e){
e.preventDefault();
var inputVals = $(this).serializeArray();
var singleInputVal = returnSingleInputVal('search', inputVals);
var queryObj = buildAjaxObject(singleInputVal);
sendAjaxRequest('/echo/json', queryObj);
});
function buildAjaxObject(searchQuery){
var dataObject = {
query :searchQuery,
hitsPerPage: 6,
filters: ['artist', 'asc']
}
return dataObject;
}
function sendAjaxRequest(url, dataObject){
$.post(url, JSON.stringify(dataObject), function(data){
$('#resultString').text(data);
});
}
function returnSingleInputVal(inputName, inputArray){
for (var a = 0; a <= inputArray.length -1; a++){
if ( inputArray[a].name == inputName){
return inputArray[a].value;
}
}
}
Is there a way to post attributes other than the value to another page?
For eg: If i have <option value="Bulgaria" data-key="BG" data-geo="EMEA">Bulgaria</option>
I know i can post the value and get it on the thank you page with $_POST,
but what if i wanted to get the data-key instead of the value?
$( "#myselect option:selected" ).data("key") or
$( "#myselect option:selected" ).attr("data-key")
But you need to send values via js insted of html form send
You can only post the value (unless you use AJAX and a bit of manipulation). If you go for the JavaScript route, this would be achieved with something like this:
$('form').submit(function(e) {
data = {};
url = '';
e.preventDefault();
$('input', this).each(function() {
var pcs = $(this).data();
var datakey = $(this).attr('data-key');
if (undefined == data[datakey]) {
data[datakey] = {};
data[datakey]['_'] = $(this).val();
}
$.each(pcs, function(k, v) {
data[datakey][k] = v;
});
});
$.ajax({
url: url,
data: data,
type: "POST"
}).done(function() {
// data-key successfully POSTed
});
});
The better question is why are you attempting to do this? If you only want an output of BG, use that as the value. If you want both Bulgaria and BG, you can make use of a hidden input to additionally send the secondary data (as a value):
<input type="hidden" name="shortcode" value="BG" />
Simple, you can try it:
HTML:
<form ... method="post" onsubmit="return form_check()">
<input type="hidden" name="data_key" id="data_key">
<input type="hidden" name="data_geo" id="data_geo">
...
<button type="submit">Submit</button>
</form>
jQuery:
function form_check() {
$('#data_key').val($('#myselect option:selected').data('key'));
$('#data_geo').val($('#myselect option:selected').data('geo'));
return true;
}
then in your PHP you'll receive them in $_POST['data_key'] and $_POST['data_geo'].
My code works fine when I run the php script without ajax as a GET request. I get prompted to download the rendered pdf and all is well. However, I need to use ajax because I need to send more info from an html page to the php script than can be handled in a GET request.
What do I need to put into my ajax to make this work?
Thanks
js
function makePDF()
{
var x;
if(window.event) // IE8 and earlier
{
x=event.keyCode;
}
else if(event.which) // IE9/Firefox/Chrome/Opera/Safari
{
x=event.which;
}
keychar=String.fromCharCode(x);
alert(keychar);
if (keychar == 'p' || keychar == 'P')
{
var charSheetHTML = characterSheet.innerHTML;
$.ajax({
url: 'pdf.php',
data: {'charactersheet': charSheetHTML,},
type: 'post',
success: function (data) {**WHAT_DO_I_PUT_HERE??**},
error: function (data) { alert("error\n" + data.toString()); }
});
}
}
pdf.php
<?php
include_once( "bxcharacter/PDFChar.php.inc" );
PDFChar();
?>
PDFChar.hph.inc
<?php
require_once('./tcpdf/tcpdf.php');
function PDFChar(){
$pdf = new TCPDF();
$pdf->AddPage('P');
$pdf->writeHTML($_POST['charactersheet']);
$pdf->Output("character.pdf", 'D');
}
?>
This is not an ajax solution, but you can send your data with this way and if no error occurs, your page will not change.
Create a form element with inputs hidden which contains your data you want to send:
example format:
<form id="myForm" method="GET" action="pdf.php">
<input type="hidden" name="data1" type="hidden" value="your JSON.stringify() data">
</form>
js code (call these where your ajax request is):
var myForm = '<form id="myForm" method="GET" action="pdf.php">';
myForm += '<input type="hidden" name="data1" type="hidden" value="JSON.stringify() data">';
myForm += '</form>';
$("body").append(myForm); // temporarily appending
$("#myData-form").submit(); // submitting form with data
$("#myData-form").remove(); // remove form after submit
And as you said, force download will force file to download and page will remain same. However, if an error occurs, your page will change of course.
I don't know whether this is an effective way or not but in my case, this does the trick.
Old question, but I was trying to do something similar with Laravel PDF extension, and stumbled across this question. I did successfully do this asynchronously with the help of a nice blog post
https://nehalist.io/downloading-files-from-post-requests/
https://github.com/nehalist/download-post-requests
The using the form method, like the previous answer works fine too, but maybe this will help anyone else trying to achieve this with AJAX. The author's XMLHttpRequest method worked great for me!
The code that worked for me (almost verbatim from the blog post) ->
document.getElementById('exportpdf').addEventListener('click', function () {
var request = new XMLHttpRequest();
request.open('POST', '/your/post/endpoint/here', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.responseType = 'blob';
request.onload = function() {
if(request.status === 200) {
var disposition = request.getResponseHeader('content-disposition');
var matches = /"([^"]*)"/.exec(disposition);
var filename = (matches != null && matches[1] ? matches[1] : 'file.pdf');
var blob = new Blob([request.response], { type: 'application/pdf' });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
};
I tried to get it to work with jQuery AJAX but failed, so I went with XMLHttpRequest. With jQuery, The download would work, but the content was always empty. I tried to do something like in this post -
https://keyangxiang.com/2017/09/01/HTML5-XHR-download-binary-content-as-Blob/
$.ajax does not support either arraybuffer or blob as its dataType. Thus we need write a beforeSend handler:
//setup ajax
$.ajaxSetup({
beforeSend:function(jqXHR,settings){
if (settings.dataType === 'binary'){
settings.xhr().responseType='arraybuffer';
settings.processData=false;
}
}
})
//use ajax now
$.ajax({
url:url,
dataType:"binary",
success:function(data){
console.log(data); //ArrayBuffer
console.log(new Blob([data])) // Blob
}
})
But never got it to work. Maybe someone smarter can figure out the jQuery method :)
Rooms are an array
window.location = "booking_status.php?array="+ JSON.stringify(rooms);
sending from javascript to php page
on php page url show full array value which are store in array in page address bar url
like that
http://localhost/zalawadi/booking_status.php?array=[{%22id%22:10,%22rate%22:100}]
I want to prevent this data which show in url %22id%22:10,%22rate%22:100
I am decoding on php page any other way to send array data from javascript to php page
The only way to send data to another page without showing them in the url is to use POST.
Basically, you can put your data into an invisible form input :
<form method="post" id="form" action="booking_status.php">
<input name="array" id="array" type="hidden" value="" />
</form>
Send
<script type="text/javascript">
function sendForm(){
document.getElementById('array').value = JSON.stringify(rooms);
document.getElementById('form').submit(); //fixed syntax
}
</script>
You can use a hidden form and the post method. Then you would use $_POST instead of $_GET.
<form action="script.php" onsubmit="this.firstChild.value=JSON.stringify(value);">
<input type="hidden" value="" />
Link text
</form>
You can use a POST request, however this would require generating and submitting a form:
// assuming `rooms` already defined
var frm = document.createElement('form'), inp = document.createElement('input');
frm.action = "booking_status.php";
frm.method = "post";
inp.type = "hidden";
inp.name = "array";
inp.value = JSON.stringify(rooms);
frm.appendChild(inp);
document.body.appendChild(frm);
frm.submit();
Why not just POST the data instead then?
For example, with jQuery:
$.ajax({
type: "POST",
url: "booking_status.php",
data: JSON.stringify(rooms),
success: // add success function here!
});
The advantage is you're not passing some horrific URL. As an added bonus, this example is also asynchronous, so the user doesn't see any refresh in their browser.
Non-Framework Version
If you don't wish to use jQuery, you can do this with pure Javascript, using the XMLHttpRequest object, like so:
var url = "get_data.php";
var param = JSON.stringify(rooms);
var http = new XMLHttpRequest();
http.open("POST", url, true);
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
// Request has gone well. Add something here.
}
}
http.send(param);
My goal is to have input field that will take value of whats was typed and echoed through. The js function will grab the value of the input box two seconds after user stops typing and post it. The issue seems to be with the php not echoing the value of the input box. When I take out the js function and use a button that forces refresh then
it works fine. How come php is not taking the value posted by js function?
Example SITE
JS
<script type="text/javascript">
$(document).ready(function() {
var timer;
$('#video-input1').on('keyup', function() {
var value = this.value;
clearTimeout(timer);
timer = setTimeout(function() {
//do your submit here
$("#ytVideo").submit()
//alert('submitted:' + value);
}, 2000);
});
//then include your submit definition. What you want to do once submit is executed
$('#ytVideo').submit(function(e){
e.preventDefault(); //prevent page refresh
var form = $('#ytVideo').serialize();
//submit.php is the page where you submit your form
$.post('index.php', form, function(data){
});
return false;
});
});
</script>
PHP
<?php
if($_POST)
{
$url = $_POST['yurl'];
function getYoutubeVideoID($url) {
$formatted_url = preg_replace('~https?://(?:[0-9A-Z-]+\.)?(?:youtu\.be/| youtube\.com\S*[^\w\-\s])([\w\-]{11})
(?=[^\w\-]|$)(?![?=&+%\w]*(?:[\'"][^<>]*>| </a>))[?=&+%\w-]*~ix','http://www.youtube.com/watch?v=$1',$url);
return $formatted_url;
}
$formatted_url = getYoutubeVideoID($url);
$parsed_url = parse_url($formatted_url);
parse_str($parsed_url['query'], $parsed_query_string);
$v = $parsed_query_string['v'];
$hth = 300; //$_POST['yheight'];
$wdth = 500; //$_POST['ywidth'];
$is_auto = 0;
//Iframe code with optional autoplay
echo htmlentities ('<iframe src="http://www.youtube.com/embed/'.$v.'" frameborder="0" width="'.$wdth.'" height="'.$hth.'"></iframe>');
}
?>
form
<html>
<form method="post" id="ytVideo" action="">
Youtube URL: <input id="video-input1" type="text" value="<?php $url ?>" name="yurl">
<input type="submit" value="Generate Embed Code" name="ysubmit">
</form>
</html>
It's because you are not returning your php result anywhere. It's simply lost...
$.post('index.php', form, function(data){
var x = $(data);
$("body").html(x);
});