I would appreciate your opinion/advice on the following
Scenario
HTML has PDF file nick name, back end has URL for each nick.
The link URL is always download.php?what=%PDF_Nick% to ensure download for JS disabled clients.
For JS enabled clients I do JQuery AJAX call and rewrite link URL from download.php?what=%PDF_Nick% to http://examplesite.com/requestedPFF.pdf to activate download from the client. I set "async: false" to allow AJAX get new url.
Problem
AJAX returns valid script rewriting JS url variable, but location.href runs again to the initial url, creating extra back end call
Do you think it's related to the bug ignoring "async: false," definition or it's mistake I've made and missed to catch?
Thank you in advance
HTML code
<a href="/download.php?what=PDF_A" onclick="javascript:download
('PDF_A')">Download</a>
JS code
function download ( what ) {
var url = "download.php?what="+what;
$.ajax({
type: "GET",
url: "download.php?ajax=true",
data: "what=" + what
async: false,
dataType: "script"
});
// if AJAX got the download URL I expect actual download to start:
location.href = url;
}
Back end (download.php) code
$myPDF = array();
$myPDF["PDF_A"] = "PDF_A.pdf";
....
$url = "http://examplesite.com/" . $myPDF["PDF_A"];
...
if ( $_GET["ajax"] === "true" ) {
// overwrite JS url variable
print('url = "'.$url.'";');
} else {
header("Location: ". $url );
header("Connection: close");
}
You're encountering a scoping problem here. The URL variable in your JS code is declared via the var keyword inside the scope of the download function. This means that only code inside the download function can modify that particular url value.
The script returned from the download.php is modifying the URL value in the global scope (on the browser, this is the "window" object), which is not the same value as the url inside the scope of the download function.
If you don't use the 'var' keyword on the declaration of the url variable, it will be created automatically in the global scope and your code will function as you expect.
I agree with the others, that your design is inherently flawed and should be revisited, however.
Is there a reason you disable the asynchronous nature of the AJAX request? it will lock the browser until the request is completed.
You are better off using a callback instead:
$.ajax({
type: "GET",
url: "download.php?ajax=true",
data: "what=" + what,
dataType: "script",
success: function(msg) {
location.href = url;
}
});
Or you can use a synchron ajax call with .responseText like in this example:
var html = $.ajax({
url: "some.php",
async: false
}).responseText;
For your code this means:
function download ( what ) {
var url = "download.php?what="+what;
location.href = $.ajax({
type: "GET",
url: "download.php?ajax=true",
data: "what=" + what
async: false,
dataType: "script"
}).responseText;
}
Related
I am trying to send a variable from JS to php through ajax but I'm not able to get in php file.
JS
var names = ['lee','carter'] ;
$.ajax({
type: "POST",
url: "http://localhost/test/ajax.php",
data: {name:names},
}).done(function() {
location.href = 'http://localhost/test/ajax.php' ;
});
PHP
print_r($_POST);
this is showing an empty array but when I do console.log(data) it shows an array in console.log
var names = ['lee','carter'] ;
$.ajax({
type: "POST",
url: "http://localhost/test/ajax.php",
data: {name:names},
}).done(function(data) {
console.log(data) ;
});
Edit: (by mega6382) I believe OP wants to open a page in browser with post params, which cannot be done by AJAX. All others who answered got mistaken by the AJAX code in the question and started providing AJAX solutions, without realizing what OP is trying to do. If you were to read OP's comments on Jeroen's answer.
The problem is with what you do when the ajax request finishes:
}).done(function() {
location.href = 'http://localhost/test/ajax.php' ;
});
Here you are re-directing to http://localhost/test/ajax.php (requesting it a second time...), using a GET request so $_POST is indeed empty.
Just do the following in your php file to receive a json formatted string
echo json_encode(['success' => true]);
Instead of ajax try sending a dynamically generated form like:
var names = ['lee','carter'] ;
var newForm = $('<form>', {
'action': "http://localhost/test/ajax.php",
'target': '_top',
'method': 'POST'
});
names.forEach(function (item, index)
{
newForm.append($('<input>', {
'name': 'name[]',
'value': item,
'type': 'hidden'
}));
});
$(document.body).append(newForm);
newForm.submit();
This will send the values over POST via a form. It will do both redirect to the new page and send post vals.
Since you're using an AJAX request, in this case POST, you could use the _REQUEST method in php for obtaining the JS variable. In your case try:
$names = $_REQUEST['name']
echo $names;
/* Or try JSON_ENCODE if echo isn't working*/
$json = json_encode($names)
echo ($json);
var names = ['lee','carter'] ;
JSON.stringify(names);
$.ajax({
type: "POST",
dataType: 'json',
url: "http://localhost/test/ajax.php",
data: {name:names}
}).done(function() {
console.log('ok');
});
This is a successful ajax call. Now in order to "check by yourself" that is working you don't have to redirect to the other page because that way you refresh and lose the data. What you have to do is:
Open developer tab in your browser
Go to network tab
Locate your ajax call (it has the name of your php class that you do
the call)
go to response tab and there you have your php output
This link is to help you understand how to debug ajax call
Is it possible to mix post and get in ajax? Specifically have a form POST data to a url with get variables?
In html and PHP I would normally do this:
<form action="script.php?foo=bar" method="POST">
...insert inputs and buttons here...
</form>
And the PHP script would handle it based on logic/classes.
I have tried the following and several variations to no avail:
$(document).ready(function() {
$('#formSubmitButton').click(function() {
var data = $('#valueToBePassed').val();
$.ajax({
type: "POST",
//contentType: 'application/json',
url: "script.php?foo=bar",
data: data,
processData: false,
success: function(returnData) {
$('#content').html( returnData );
}
});
});
});
Is this even possible? If so what am I doing wrong. I do not feel as if I am trying to reinvent the wheel as it is already possible and used regularly (whether or not if it is recommended) by plenty of scripts (granted they are php based).
Please check out the below jsfiddle URL and
https://jsfiddle.net/cnhd4cjn/
url: "script.php?data="+data, //to get it in the URL as query param
data:"data="+data, // to get it in the payload data
Also check the network tab in dev tools to inspect the URL pattern on click of the submit button
You can, here's what I do.
$(document).ready(function() {
$('#formSubmitButton').click(function() {
// My GET variable that I will be passing to my URL
getVariable = $('#valueToBePassed').val();
// Making an example object to use in my POST and putting it into a JSON string
var obj = {
'testKey': 'someTestData'
}
postData = JSON.stringify(obj);
// Jquery's AJAX shorthand POST function, I'm just concatenating the GET variable to the URL
$.post('myurl.com?action=' + getVariable, postData, function(data) {
JSONparsedData = $.parseJSON(data);
nonparsedData = data;
});
});
});
I can see 1 syntax error in you code .
use
data: {data:data},
instead of
data: data,
and then try to access like
$_POST['data']; and $_GET['foo'];
But i have never tried the GET params inside a POST request :) , this is only a suggestion.
I am trying to understand a $.ajax call:
var url = "/api/followuser.php/" + userID ;
$.ajax(url, { 'success': function(data) {
/do something
}
});
Thia ajax call is required to pass the variable 'userID' to the file '/api/followuser.php' to make a database query(php/Mysql).
I don't have access to '/api/followuser.php' .
Can anyone help me figure out how to get the variable 'userID' from the URL in a php file to be used in a database query.( I know how to pass variable as 'data: userID,' in $.ajax and use it in a php file but i want to understand this particular example)
Maybe you mean followuser.php?user_id= instead? The slash is probably causing issues since that's interpreted as a directory by the server:
var url = "/api/followuser.php?user_id=" + userID;
you need to use GET method with ajax, to do this you can use next example
$.ajax({
url: "/api/followuser.php",
type: "GET",
data: {variable: "valueofvariable"},
success: function(data) {
console.log(data);
}
});
so in your php file you can read the variable like this
<?php
if(isset($_GET["variable"])){
echo $_GET["variable"];
// if this works you should see in console 'valueofvariable'
}
?>
I'm pretty new to ajax and I applied it succesfully to a Drupal site. But I was wondering, how do I get an URL to a page where part of the content is loaded through ajax. Is this even possible? The JSON object is retrieved on click, so how do I make it work when retrieving a certain URL?
I realize this is a very broad questionany, any help would be greatly appreciated.
Thanks in advance!
My JS looks like this:
Drupal.behaviors.ajax_pages = function (context) {
$('a.categoryLink:not(.categoryLink-processed)', context).click(function () {
var updateProducts = function(data) {
// The data parameter is a JSON object. The films property is the list of films items that was returned from the server response to the ajax request.
if (data.films != undefined) {
$('.region-sidebar-second .section').hide().html(data.films).fadeIn();
}
if (data.more != undefined) {
$('#content .section').hide().html(data.more).fadeIn();
}
}
$.ajax({
type: 'POST',
url: this.href, // Which url should be handle the ajax request. This is the url defined in the <a> html tag
success: updateProducts, // The js function that will be called upon success request
dataType: 'json', //define the type of data that is going to get back from the server
data: 'js=1' //Pass a key/value pair
});
return false; // return false so the navigation stops here and not continue to the page in the link
}).addClass('categoryLink-processed');
}
On the begining of the page load ajax based on hash part of the url page#id,
$(document).ready(function() {
$.ajax({
type: 'POST',
url: "/path/to/page",
success: updateProducts,
dataType: 'json',
data: 'id=' + window.location.replace(/.*#/, '')
});
$('a.categoryLink:not(.categoryLink-processed)', context).click(function () {
$.ajax({
type: 'POST',
url: "/path/to/page",
success: updateProducts,
dataType: 'json',
data: 'id=' + this.href.replace(/.*#/, '')
});
});
Or you can use jquery-history but I didn't test it.
I don't know what exactly you are trying to do. But unless you have a module that creates the JSON data you need to do it yourself.
You would need to create a menu callback with hook_menu. In the callback function you can return json data by using drupal_json.
If you create the menu callback etc yourself, the URL will be whatever you make it to. Else you just have to use the URL defined by the module you want to use.
Here a sample use case:
I request a simple form via an ajax request. I want to submit the result to the same page that I requested. Is there a way to access the URL of that request in the resulting request's javascript?
Below is some code that accomplishes what I want via javascript AND PHP. The downside to this is that I have to include my javascript in the same file as myajaxform.php. I'd rather separate it, so I can minify, have it cached etc.
I can't use location.href, b/c it refers to the window's location not the latest request.
frm.submit(function () {
if (frm.validate()) {
var data = frm.serialize();
jQuery.ajax({
url : '<?= $_SERVER['PHP_SELF'] ?>',
type : 'POST',
data : data,
dataType: "html",
success : function (data) {
}
});
}
return false;
});
If there's not a way to access it via javascript directly, how would you solve this problem so that the javascript can go in it's own file? I guess that I could in the original ajax request's success handler, create some sort of reference to the URL. Thoughts? Maybe something using the jQuery data method?
You can store the url to submit to in the action attribute of the form, and then set the url to frm.action:
jQuery.ajax({
url : frm.action,
type : 'POST',
data : data,
dataType: "html",
success : function (data) {
}
});
Forgive me if I totally misinterpret your question, as I find it somewhat confusing. What about
frm.submit(function () {
if (frm.validate()) {
var data = frm.serialize();
jQuery.ajax({
url : window.location.href,
type : 'POST',
data : data,
dataType: "html",
success : function (data) {
}
});
}
return false;
});