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'
}
?>
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.
This is a process that I use for other ajax update functions, but for this specific instance, it doesn't want to work. I don't know if I'm missing something in my code, or if the fact that part of the query string is a url and needs to be encoded before the AJAX plugin (don't know this and couldn't find any info on it, just brainstorming).
When I access the php script directly and echo out the query, then run it in console mode, it works fine. When I try to access it with AJAX, I get the success response, but the entry is not updated in the DB, so I assume that means the script did not run properly.
Here is my code:
AJAX
jQuery('#nl-details').on('click','#d-cl-change', function(){
var mls = jQuery('#d-mls').val(),
cl = jQuery('#d-cl-input').val(),
url = 'scripts/forms/cl/clchange.php?mls='+mls+'url='+cl;
jQuery('#test').html(url); //This is just for me to view the URL
jQuery.ajax({
url: url,
dataType: 'json',
success: function(data){
jQuery('#d-cl-save').fadeIn('200').delay('800').fadeOut('800');
jQuery('#d-cl-url').html('Go to Listing');
},
error: function(){
jQuery('#d-cl-fail').fadeIn('200').delay('800').fadeOut('800');
}
});
});
PHP
//Generic include for MYSQL Credentials
define('INCLUDE_CHECK',true);
require('../../c.php');
$url = mysqli_real_escape_string($link,urldecode($_GET['url']));
$mls = mysqli_real_escape_string($link,$_GET['mls']);
$query = "UPDATE `nht_actprop`
SET CLLINK = '".$url."'
WHERE MSTMLSNO = '".$mls."'";
$result = mysqli_query($link,$query);
echo $query;
mysqli_close($link);
On this line of yor code you are missing a &
url = 'scripts/forms/cl/clchange.php?mls='+mls+'url='+cl;
I think it's supposed to be like this
url = 'scripts/forms/cl/clchange.php?mls='+mls+'&url='+cl;
I see that you have chosen a best answer already but I would just like to share with you how I would tackle this task.
I would recommend using AJAX's type option to send data via GET like this:
jQuery('#nl-details').on('click','#d-cl-change', function(){
var url = 'scripts/forms/cl/clchange.php';
jQuery('#test').html(url); //This is just for me to view the URL
jQuery.ajax({
url: url,
type: 'GET',
data: {
mls: jQuery('#d-mls').val(),
url: jQuery('#d-cl-input').val()
},
dataType: 'json',
success: function(data){
jQuery('#d-cl-save').fadeIn('200').delay('800').fadeOut('800');
jQuery('#d-cl-url').html('Go to Listing');
},
error: function(){
jQuery('#d-cl-fail').fadeIn('200').delay('800').fadeOut('800');
}
});
});
And the best part is that you don't have to change your PHP at all
Good luck! Let me know your thoughts
Hello i have searched the whole website for a soltution found something but didnt get it to work.
-I have the main function on the head area of the page. (This will return Data from a PHP)
-This Data i need as a variable but dont know how to handle.
function note(content,usern){
note = Function("");
$.ajax({
type: "POST",
url: "note.php",
data: {'token': content, 'user': usern }, success: function(data){ var myneededvar = data; }, }); }
Ok thats works and also data is given out
Now im calling the function in the script like this
note(token,notename);
and i need the result myneededvar
but cant get it to work.
Firstly, your variable myneededvar is local to the success handler function and will not be available outside.
Secondly, your AJAX call is asynchronous and you cannot expect to immediately get the AJAX return data in a variable right after the AJAX call statement.
i.e., you cannot do:
note(...); // call your method
alert(myneededvar); // this won't work as the AJAX call wouldn't have completed
Thirdly, not sure why you have that note = Function(""); statement there. You should remove that.
Something like this should work:
var myneededvar;
function note(content, usern){
$.ajax({
type: "POST",
url: "note.php",
data: {'token': content, 'user': usern },
success: function(data){
myneededvar = data;
// use it here or call a method that uses myneededvar
}
});
}
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;
}