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
Related
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'
}
?>
The Ajax function below sends data from a page to the same page where it is interpreted by PHP.
Using Firebug we can see that the data is sent, however it is not received by the PHP page. If we change it to a $.get function and $_GET the data in PHP then it works.
Why does it not work with $.post and $_POST
$.ajax({
type: "POST",
url: 'http://www.example.com/page-in-question',
data: obj,
success: function(data){ alert(data)},
dataType: 'json'
});
if there is a problem, it probably in your php page.
Try to browse the php page directly in the browser and check what is your output.
If you need some inputs from post just change it to the GET in order to debug
try this
var sname = $("#sname").val();
var lname = $("#lname").val();
var html = $.ajax({
type: "POST",
url: "ajax.class.php",
data: "sname=" + sname +"&lname="+ lname ,
async: false
}).responseText;
if(html)
{
alert(html);
return false;
}
else
{
alert(html);
return true;
}
alax.class.php
<php
echo $_REQUEST['sname'];
echo $_REQUEST['sname'];
?>
Ajax on same page will not work to show data via POST etc because, PHP has already run that's why you would typically use the external page to process your data and then use ajax to grab the response.
example
success: function(){
$('#responseDiv').text(data);
}
You are posting the data... Check if the target is returning some data or not.
if it returns some data then only you can see the data otherwise not.
add both success and error.. so that you can get what exactly
success: function( data,textStatus,jqXHR ){
console.log(data);//if it returns any data
console.log(textStatus);//or alert(textStatus);
}
error: function( jqXHR,textStatus,errorThrown ){
console.log("There is some error");
console.log(errorThrown);
}
I just want to pass my variable data.company_name from callback function:
<script>
function AjaxInsert() {
var company_name = $("#company_name").val();
dataToSend = {};
dataToSend.company_name = company_name;
$.ajax({
url: 'insert.php',
data: dataToSend,
dataType: "json",
success : function(data) {
console.log("my variable: "+data.company_name);
}
});//ajax*/
}
</script>
,below in the same script into a PHP (PHPExcel) method:
<?php
$var_needed = 'I need that data.company_name here';
$objWorksheet->setCellValueByColumnAndRow(0,$num_rows+1,$var_needed);
?>
How can be this achieved?
The "same script" has been executed already, so you won't be able to interact with it anymore after page load.
You either want to manipulate your spreadsheet client side with a JS library, or to drop ajax and reload the whole page [and ruin your user experience by the way].
<?php
$var_needed = $_REQUEST['company_name'];
$objWorksheet->setCellValueByColumnAndRow(0,$num_rows+1,$var_needed);
?>
$objWorksheet->setCellValueByColumnAndRow(0,$num_rows+1,$_POST['company_name']);
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;
});