I would like to send some data by using jquery ajax function to my PHP file.
I have created such function:
function ajax_call (url, select, select_name)
{
$(select).change(function () {
$(".result").fadeIn(400).html('<img src="ajax-loader.gif"/>');
var select_value = $(this).val();
$.ajax({
type: 'POST',
url: url,
data: { select_name : select_value },
success: function(data){
$(".result").html(data);
}
});
});
}
I call it:
ajax_call ('url path to my PHP file', '#my_select_div', 'my_data_name');
I have problem with this part:
data: { select_name : select_value }
I would like to get:
$_POST['my_data_name']
but I'm getting:
$_POST['select_name']
Any ideas?
Thanks for your answers.
When using object literal syntax, the key can be a string or an identifier. The identifier represents the key name, not a variable. You have to assign the key/value after creating the object if you want to use variable key names.
var data = {};
data[select_name] = select_value;
$.ajax({
type: 'POST',
url: url,
data: data
Related
Hey I can't pass a JS variable through AJAX to php file. No matter if I try POST or GET it's not working: with POST it gave me [] or Undefined index if I want to print_r($_POST['adminID']
And GET, there I get {"fancybox":"true"}
$('#adminList tr').on('click', function() {
var adminID = $(this).find(".adminID").text();
console.log(adminID);
$.ajax({
type: 'POST',
url: 'modules/management/user_edit.php',
data: {adminID : adminID},
success: function(data)
{
$.fancybox.open({
src : 'modules/management/user_edit.php',
type : 'ajax'
});
}
});
});
and module/management/user_edit.php i just want to post this adminID
You send double request to user_edit.php file, first with POST data, and second without. You should display result of first request in fancybox.
$('#adminList tr').on('click', function() {
var adminID = $(this).find(".adminID").text();
$.ajax({
type: 'POST',
url: 'modules/management/user_edit.php',
data: {adminID : adminID},
success: function(response)
{
$.fancybox.open(response);
}
});
});
My Javascript code is the following:
function on(logged_user) {
alert(logged_user);
$.ajax({
url: "update_stats.php",
type: "POST",
data: logged_user
});
}
update_stats.php contains
<?php
$logged_user = $_POST["logged_user"];
?>
but I can see that $logged_user is just an empty string (I'm inserting it into a database table)
Your data parameter for the $.ajax call is not in the right format. From the manual:
The data option can contain either a query string of the form
key1=value1&key2=value2, or an object of the form {key1: 'value1',
key2: 'value2'}
You should change that line to:
data: { logged_user : logged_user },
or
data: 'logged_user=' + logged_user,
just try this:
function on(logged_user) {
alert(logged_user);
$.ajax({
type : 'POST',
url : update_stats.php,
data : logged_user,
dataType : 'json',
encode : true
});
}
Its not javascript , its a jquery ajax, so please include a jquery library.
and change your function like this
Syntax to pass the values like,
data: '{ "key":' + value+ ', "key":"value" }',
or
data = "key=" + value
or
data: JSON.stringify({ key: value, key: value}),
function on(logged_user) {
var dataString = "logged_user=" + logged_user
$.ajax({
type: "POST",
url: "update_stats.php",
data: dataString,
cache: false,
success: function(result) {
alert(result)
}
})
}
You need to pass data in key - value format to get accesible by $_POST, $_GET and $_REQUEST array variables in php.
data: {'logged_user' : data: logged_user}
You can access raw input like JSON data or text data which not in the key value format you can use file_get_contents("php://input") to access data.
This is my imple code on submit of form. Where I want to insert table data values in database through ajax. But it's not going to controller.
$('#submit').click(function(){
var TableData = new Array();
$('#cart_details tr').each(function(row, tr){
TableData[row]={
"productname" : $(tr).find('td:eq(0)').text()
, "quantity" :$(tr).find('td:eq(1)').text()
, "unit" : $(tr).find('td:eq(2)').text()
, "unit_rate" : $(tr).find('td:eq(3)').text()
}
});
TableData.shift();
//TableData = $.toJSON(TableData);
var TableData = JSON.stringify(TableData);
alert(TableData);
var followurl='<?php echo base_url()."index.php/purchase/save_product";?>';
$.ajax({
type: "POST",
url:followurl,
data: TableData,
datatype : "json",
cache: false,
success: function (data) {
alert("dsad"+data);
}
});
});
When I stringify tabledata array output is like this..
[{"productname":"Copper Sulphate","quantity":"1","unit":"1","unit_rate":"100"},
{"productname":"Hypta Hydrate","quantity":"1","unit":"1","unit_rate":"100"}]
My question is why it's not going to controller? it's because of array object or something else??
Tabledata is javascript object array . Am I right??
Use
$.ajax({
instead of
$.post({
use this code
$.ajax({
type: "POST",
url:followurl,
data: {TableData : TableData},
cache: false,
success: function (data) {
alert("dsad"+data);
}
});
check the Documentation jquery.post
The syntax for $.post is
$(selector).post(URL,data,function(data,status,xhr),dataType)
You don't have to define the type ,
but here you are using the $.ajax mixing with $.post
this is the $.ajax function syntax
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
SO change the $.post to $.ajax and try
As you can read in the documentation, you can pass an object to data. I think you'd make things easier and simpler for you if you followed that approach.
...
//TableData = $.toJSON(TableData); NO!!!
//var TableData = JSON.stringify(TableData); NO!!!
//alert(TableData);
var followurl='<?php echo base_url()."index.php/purchase/save_product";?>';
$.ajax({
type: "POST",
url:followurl,
data: {
dataTable: TableData
},
datatype : "json",
cache: false,
success: function (data) {
alert(data);
}
});
});
Very simple example (without validation or anything of the kind) of index.php/purchase/save_product
$data = $_POST["dataTable"];
echo $data[0]["productname"];// Sending back the productName of the first element received.
die();
As you can see, you could access data in your index.php/purchase/save_product file very easily if you followed this approach.
Hope it helps.
Hi It look like you are using some CMS or Framework. Can you please let us know which framework or CMS you are using. I would then be able to sort out this issue. It looks like you are using Code Ignitor. If its so then i hope this would help you
$.post( "<?php echo base_url();?>index.php/purchase/save_product", function(data) {
alert( "success" );
}, 'html') // here specify the datatype
.fail(function() {
alert( "error" );
})
in Your case your ajax call must look like
var followurl="<?php echo base_url();?>index.php/purchase/save_product";
$.ajax({
type: "POST",
url:followurl,
data: TableData,
datatype : "json",
cache: false,
success: function (data) {
alert("dsad"+data);
}
});
});
Error Seems to be in your followUrl please try using as its in mine code
I have set an Ajax call for Pagination. I need to pass one more vaiable which is stored in the URL
URL
http://thisite.com/pagetitl/?id=12 **// where 'id=' is a variable I want to pass.**
Ajax Call
function page(page) {
var dataString = '&page=' + page; // pagination with ajax
pag.ajax({
type: "GET",
url: "cmn_pg.php",
data: dataString,
success: function (ccc) {
pag("#search_results").html(ccc);
}
});
}
I have tried to GET it in PHP file $id=$_GET[id], but wont work.
I ask how to pass it with AJAX because I'm quite new to AJAX.
If you are building your query string manually then:
dataString = 'page=' + encodeURIComponent(page);
but you are using jQuery, so don't build it manually:
url: "cmn_pg.php",
data: {
"page": page
},
success: function (ccc) {
(You also need to use the right name for it in PHP: <?php $id = $_GET['page'] ?>)
You can pass via url like this
pag.ajax
({
type: "GET",
url: "cmn_pg.php?page="+page,
success: function(ccc)
{
pag("#search_results").html(ccc);
}
});
Or
pag.ajax
({
type: "post",
url: "cmn_pg.php",
data: {'data':dataString},//You can add as many datas seperated by comma to pass more values
success: function(ccc)
{
pag("#search_results").html(ccc);
}
});
And in php
$dataString = $_POST['data'];
You named the variable "page" and try to access it via "id" in PHP. You have to create the query string liek this:
var dataString = '&id=' + page;
Alertnitavly you can use pass an object to the "data" parameter andjQUery does the transformationf for you. Sample:
data: { id: page },
Data to be sent to the server. It is converted to a query string, if
not already a string. It's appended to the url for GET-requests. See
processData option to prevent this automatic processing. Object must
be Key/Value pairs. If value is an Array, jQuery serializes multiple
values with same key based on the value of the traditional setting
(described below).
Soruce: http://api.jquery.com/jQuery.ajax/
Try this,
pag.ajax({
type: "GET",
url: "cmn_pg.php",
data: {
page: page, // your page number
id:12// your id to send
},
success: function (ccc) {
pag("#search_results").html(ccc);
}
});
function page(page) {
var dataString = '&page=' + page; // pagination with ajax pag.ajax
({
type: "GET",
url: "cmn_pg.php",
data: {
page: page
},
success: function(ccc) {
pag("#search_results").html(ccc);
}
});
if more data is there to pass add to data variable as given bellow :-
data : {page:page,data2:data2},
I am trying to pass a value of a button using some ajax to a separate file.
Here is my code.
$("input#downloadSingle").click(function() {
var myData = $("input#downloadSingle").val();
$.ajax({
type: 'post',
url:'singleDownload.php',
data: myData,
success: function(results) {
alert('works');
}
});
});
However, when I test out the next page by doing a var_dump on $_POST. I don't get any data back. Thoughts?
You're not specifying the name of the $_POST variable you're gonna get on the singleDownload.php file (unless that's part of the button's value), so you should try something like:
$("input#downloadSingle").click(function() {
var myData = "whatever=" + $("input#downloadSingle").val();
$.ajax({
type: 'post',
url:'singleDownload.php',
data: myData,
success: function(results) {
alert('works');
}
});
});
And make sure $_POST in your php file is the same whatever variable