I am using a jquery calendar script that assigns the content of a div using ajax.
$('#details-event-id').html(id);
The div tag:
<div id="details-event-id"></div>
is in another file and displays the id correctly.
<div id="details-event-id">91</div>
Is it possible to get the id, 91, to be assigned to a PHP variable?
Using ajax you can send the value to the server and then assign to the php variable.
If you think you assign php variable in any javascript event in client side, its not possible without any asynchronous calling of the server script.
If I understand correctly you would like to send the variable id to a PHP file. You can achieve this by using AJAX. Bellow I'm showing two ways to get it done.
var id = $('#details-event-id').html(id);
AJAX with good old JS
ajax(myfile.php, {id:id}, function() {
// the following will be executed when the request has been completed
alert('Variable id has been sent successfully!');
});
function ajax(file, params, callback) {
var url = file + '?';
// loop through object and assemble the url
var notFirst = false;
for (var key in params) {
if (params.hasOwnProperty(key)) {
url += (notFirst ? '&' : '') + key + "=" + params[key];
}
notFirst = true;
}
// create a AJAX call with url as parameter
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callback(xmlhttp.responseText);
}
};
xmlhttp.open('GET', url, true);
xmlhttp.send();
}
AJAX with JQuery
$.ajax({
url: 'ajax.php', //This is the current doc
type: "GET",
data: ({
id: id
}),
success: function(data) {
// the following will be executed when the request has been completed
alert('Variable id has been sent successfully!');
}
});
Offtopic: you can see why some prefer JQuery...
When either function (Jquery or plain JS) is launched it will send the variable id to the file myfile.php. In order to retrieve the variable from the call you won't use $_GET[...] but $_REQUEST[...].
myfile.php
<?php
if(!isset($_REQUEST['id'])) {
echo "no variable was sent";
}
$id = $_REQUEST['id'];
// process data, save in db, etc ....
You may return a value to the JS callback function by using echo() not return
Related
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 :)
I have problem with the site I'm developing. The dynamically loaded div (ajax) is empty in IE9 and works poorly on firefox (php doesn't compile) and I can read the source of my php file in the div.
I've tried a lot of solutions like changing from GET to POST or adding a unique id to the url or making an async request but the content is absolutely empty. Any ideas? thanks
function pageload(hash) {
if(hash == '' || hash == null)
{
document.location.hash = "#php"; // home page
}
if(hash)
{
getPage();
}
}
function getUniqueTime() {
var time = new Date().getTime();
while (time == new Date().getTime());
return new Date().getTime();
}
function getPage() {
var str = getUniqueTime();
console.log(str);
var data = 'page=' + encodeURIComponent(document.location.hash);
$('#content').fadeOut(200);
$.ajax({
url: "loader.php?_=" + str,
type: "POST",
data: data,
cache: false,
success: function (html) {
$('#content').fadeIn(200);
$('#content').html(html);
}
});
}
EDIT:
//loader.php
<?
require_once('session.class.php');
require_once('user.class.php');
$se = new session();
$lo = new user();
$se->regenerate();
if(isset($_POST))
{
$alpha = (string) $_POST['page'];
if($alpha == '#php')
{
include 'homeloader.php';
}
else if($alpha == '#cplus')
{
include 'cplusloader.php';
}
else if($alpha == '#web')
{
include 'underloader.php';
}
else if($alpha == '#about')
{
include 'underloader.php';
}
else if($alpha == '#social')
{
include 'socialloader.php';
}
}
else
$page = 'error';
echo $page;
?>
try this:
//on click of a button:
$("#button").live("click", function(){
//get you string data
var str = "test";
//do new version of ajax
$.post("loader.php", {str:str}, function(html){
$('#content').html(html);
});
});
and you dont need to do AJAX method anymore $.post works amazing
php doesn't compile? async request? actually not specifying ascync: true the request is executed asyncroniously and in version jQuery 1.8 there is no sync AJAX requests at all. Attach an error handler and you will see that your request probably results an error:
...
cache: false,
success: function (html) {
$('#content').fadeIn(200);
$('#content').html(html);
},
error: function (a,b) {
alert('Error!');
}
...
Normally AJAX consists of 2 parts - client side and server side. I don't see serverside posted in your question. You have to check both of them. Make a simple loader.php returning the string success and get rid of all extra get params. First test your php file in browser to be sure that it works. Check FireBug for javascript errors ...
How to post data to a php script (showitemid.php) using ajax and open the same script (showitemid.php) immediately in a thickbox on a hyperlink click and display that posted data. Below is my code:
postitemid.php
This file consists of multiple check-boxes. The user will tick the checkboxes and click a hyperlink. On clicking the hyperlink all the selected check-box values would be posted to showitemid.php and then immediately showitemid.php would open in a thickbox and display the received values. But it isn't receiving any values in my code ? Need help.
$('#showitem).click(function()
{
var data = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
$.ajax({type: 'POST',
url: 'showitemid.php',
data: data,success: success,dataType: dataType});
});
showitemid.php
$data = '';
if (isset($_POST['data']))
{
$data = $_POST['data'];
}
elseif (isset($_GET['data']))
{
$data = $_GET['data'];
}
echo 'd='.$data;
use something like this
$('#showthickbox').click(function()
{
var data = $('input:checkbox:checked').map(function() {
return this.value;
}).get();//your code
$.post("showitemid.php",{data:data},function(data){
$("#thickbox").html(data);
})
})
})
in your showitemid.php
echo "your data";
The main problem with the original code is the data being sent has no key named data to match $_POST['data']) so $_POST['data']) is empty. You have to send key/value pairs, you are only sending a value with no key. You are likely getting a bit confused since you use the same variable name constantly
var dataArray = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
var dataToServer= { data : dataArray} /* now have the key to match $_REQUEST in php */
Now can use AJAX shorthand method load() to populate content
$('#myContainer').load( "yourfile.php", dataToServer, function(){
/* new html exists run open thickbox code here*/
})
i have a jquery that brinds text from a page through ajax and displays that text in a div
i want to pass that data to a php variable how can i do that ?
my jquery code is
<script type="text/javascript">
var xmlHttp = null;
window.onload = function() {
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "abc.php", true);
xmlHttp.onreadystatechange = onCallback;
xmlHttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlHttp.send(null);
}
function onCallback() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
alert(xmlHttp.responseText);
document.getElementById('show').innerHTML=xmlHttp.responseText;
}
}
}
</script>
here i want to save xmlhttp.responseTexrt in a php variable in the same file how i can do that ?
Javascript is executed on the browser, and php is executed in the web server. You can not directly pass values from javascript to php.
Therefore, you need to make another ajax call (POST) from javascript to the web server that sends the xmlHttp.responseText, and write php code in the server to store the value to database.
Pass your data in URL,
var data = "somedata";
xmlHttp.open("GET", "abc.php&send=" + data, true);
For Passing a serialized array, first convert it into string
var send = toString(array);
xmlHttp.open("GET", "abc.php" + send, true);
For storing array to PHP variable use $receive = explode(',',$_POST['send']);
I am using AJAX extensively and my PHP based notification system was not sufficient.
I have this function:
<script>
function user_notify($string, $class){
if($class == null){
$class = 'error';
}
$('<div class="' + $class + '"><div class="notification-text">' + $string + '</div></div>').hide().appendTo('#system-notifications').fadeIn('slow');
}
function DeleteTask(SpanName, TaskId){
if (confirm("Are you sure you want to delete this task?")) {
var curDateTime = new Date(); //For IE
var status = document.getElementById('status');
var poststr = "uniqueID=" + curDateTime.getTime() ;
var SpanName = SpanName;
if(SpanName == 'project_todos_complete'){
var showCompleted = 1;
} else {
var showCompleted = 0;
}
//alert (SpanName);
makePOSTRequest('http://*****webdesigns.com/project_manager/include/ajax/global.php?action=delete_task&showCompleted=' + showCompleted + '&id=' + TaskId, poststr, SpanName);
}
if(ajax_status == 4){
user_notify('Task deleted.', 'success');
ajax_status = null;
}
}
</script>
I have a global javascript variable that holds the readyState. If 4 is a response from the server, we can assume the AJAX was successful (I know, not neccessarily the cgi/php is execute if any). So I store that, and within the function that called the AJAX post, if the readyState is 4, I call the user_notify function.
It works beautifully with one exception: the first action that should trigger a notification does not. All consecutive actions successfully generate a message. It's not a specific action that doesn't work, just the first one.
The html:
<body>
<div id="system-notifications"></div>
<div class="wrapper">...</div>
What am I missing here?
UPDATE:
I am in the process of moving legacy javascript/Ajax calls to jQuery/Ajax. Everything works except one aspect: the targeted div does not 'refresh' with the return data from the .ajax jQuery call. The notification pops up (the first time and all consecutive times), the php executes (refreshing the page verfies this), but the div does not update with the html that the PHP script generates.
$('form#addToDoForm').submit(function(){
var project_id = $('#addToDoForm input[name=project_id]');
var assigned_id = $('#addToDoForm input[name=assigned_user_id]');
var description = $('#addToDoForm textarea[name=description]');
var responsible_id = $('#addToDoForm input[name=responsible_user_id :selected]');
alert(responsible_id.val());
return false;
var due = $('#addToDoForm input[name=due]');
var result_div = 'project_todos_' + project_id;
var query_string = 'action=add_to_do&id=' + project_id;
var ajax_url = 'http://avwebdesigns.com/basecamp/include/ajax/global.php?' + query_string;
var successMessage = '<b>' + description.val() + '</b> added.';
var data =
'project_id=' + project_id.val() +
'&assigned_user_id=' + assigned_id.val() +
'&responsible_user_id=' + responsible_id.val() +
'&description=' + encodeURIComponent(description.val()) +
'&due=' + encodeURIComponent(due.val()); // encodeURIComponent()
$.ajax({
type: 'POST',
url: ajax_url,
data: data,
cache: false,
success: function(data){
$('#'+result_div).html(data); // $('#'+result_div).html(data.returnValue);
user_notify(successMessage, 'success');
},
error:function(data){
$('#'+result_div).html(data);
user_notify(failureMessage, 'error');
}
});
return false;
});
Any ideas?
You are missing the non-blocking characteristics of an AJAX call probably. I can't really tell what makePOSTRequest does, but judging from your design I assume you expect it to be synchronous where it probably is not. Due to the asynchronous nature of an AJAX call, you need to pass a callback function to the call that is called when the AJAX request completes.
What probably happens in your case is that makePOSTRequest immediately returns and because the first request hasn't finished yet, ajax_status will not be 4 yet. Then, by the time the second request is sent, your first will have completed and your global variable will have been set to 4, so this time it works and this is also the cause why it works in all subsequent attempts.
This shows another flaw in your design: it's actually a very bad idea to capture the status of an AJAX request in a global variable. These requests are potentially sent in a concurrent fashion so you would have several requests that share one and the same variable - this calls for a 'race condition'. Have a look at the examples in the Ajax section of the jQuery documentation to see how to handle this correctly with the help of a callback function.