Can't get value of POST via ajax - php

I'm searching for about 4 hours and I still don't understand, why this code doesn't work.
I am using Codeigniter framework, csrf is off, xss filtering is off.
My js:
var url_to_ajax = base_url + "ajaxcalls/newcomment";
$.ajax({
url: url_to_ajax,
type: "POST",
data: {parent_id: "a"},
success: function ( data ) {
alert(data);
}
});
and in controller:
public function newcomment() {
$parent_id = $this->input->post('parent_id');
echo "please print it: ".$parent_id;
print_r($_POST);
}
$parent_id is empty and $_POST is an empty array.. In the alert I see "please print it: Array ( )" and that's all.
Does someone know why I can't get that "a" in alert from controller?

Your code is working fine for me. May be there is a mistake in URL. Try this code and see if any error message comes.
var url_to_ajax = base_url + "ajaxcalls/newcomment";
$.ajax({
url: url_to_ajax,
type: "POST",
data: {parent_id: "a"},
success: function ( data ) {
alert(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});

IF you are not using url rewrite, use "index.php" with base_url. Try this:
$.ajax({
url: base_url + "index.php/ajaxcalls/newcomment",
type: "POST",
data: {parent_id: "a"},
success: function ( data ) {
alert(data);
}
});

Related

Ajax success does not work without alert message

Ajax success does not work without alert message.
there is no error in the console.
$.ajax({
url: "<?php echo base_url(); ?>Sensor/ConnectionTypeList",
type: "POST",
data: {'model_id': model_id},
dataType: 'json',
success: function (data) {
console.log(data); //not runnig
//alert(''running);
if (document.getElementById("offset")) {
document.getElementById("offset").value = data[0].offset;
}
if (document.getElementById("multiplier")) {
document.getElementById("multiplier").value = data[0].multiplier;
}
if (document.getElementById("func")) {
document.getElementById("func").value = data[0].func;
}
if (document.getElementById("meas_command")) {
document.getElementById("meas_command").value = data[0].meas_command;
}
if (document.getElementById("read_command")) {
document.getElementById("read_command").value = data[0].read_command;
}
},
error: function () {
alert('Error.');
}
});
Is the result type JSON? In that case you need to parse the returned result in order to use it, like this:
$.ajax({
url: "<?php echo base_url(); ?>Sensor/ConnectionTypeList",
type: "POST",
data: {'model_id': model_id},
dataType: 'json',
success: function (data) {
data = JSON.parse(data);
console.log('>>', data);
...
I always use '>>' (or something like that) inside a console.log to make sure you always see a console message, even if the result is empty. Check the console log to see if the result and its type.

Json unable to pass array to php

As the title says, I failed to pass the data array via json ajax to php. I am using codeigniter, what did I do wrong? here is the jQuery code:
function load_page_data1(){
var data = [];
data['val'] = "solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
Here is the php code:
function getdata(){
$parameter = '';
if(isset($_POST))
{
if(isset($_POST['val']))
{
$parameter = $_POST['val'];
} else
{
echo "failed!";
}
}
$this->load->model('Chart');
$this->load->helper('url');
$data1 = $this->Chart->getdata_solid($parameter);
echo json_encode($data1);
}
Final:
Guys, it turn out that the values did passed from jQuery to php, the problem is that I stupidly call the same php function twice within the javascript function, then the second time calling without posting the 'val', so that the php function error and stop.
Thank you all for your answers, at least I learn the different ways to passing data by using jQuery.
Don't make a array if it's not a array just make a object
var data = {};
data.val = "solid_t1";
// equivalent to
data ={val:"solid_t1"};
// equivalent to
data['val'] ="solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
Update 1: if you need to send array you need to make a proper array object like below
Example :
var data=[];
item ={val:'value'};
data.push(item);
var new_data = JSON.stringify(data);
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: new_data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
For Debugging :
May be problem with your server side code .so for the testing purpose comment all the line in function just do this echo json_encode($_POST); and in your ajax success function just add console.log(output); and let me know the result.
create one json object
jsonObj = [];
create array list as per your need
item = {}
item ["val"] = "solid_t1";
push the array list in to the json.
jsonObj.push(item);
Please have a try like this. It is working in my case.
Your full code will be like
function load_page_data1(){
jsonObj = [];
item = {}
item ["val"] = "solid_t1";
jsonObj.push(item);
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: jsonObj,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
The another way to use this is given below.
function load_page_data1(){
var jsonObj = {};
jsonObj["val"] = "solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: jsonObj,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
Instead of var data = []; use var data = {}; to initialize your data. It should solve your problem.
Your data wasn't being passed as json, now it will.
Code will be:
function load_page_data1(){
var data = {};
data['val'] = "solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/welcome/getdata',
data: data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
One more suggestion please use CI input library for post request in controller.
e.g.
$parameter = $this->input->post('val');

$.post not working . no errors are shown

function confirm_reg(id){
if(confirm("Are you sure want to complete")){
$('#'+id).hide(500);
$.post(
'sample.php',
{id6:id},
function(data){
alert(data);
}
);
}
}
sample.php
echo "something";
NO errors are showing in firebug console . even the hide function works . but posting is not working !
Try flollowing:
$.ajax({
type: "POST",
url: url,
data: data, //Data to be sent to server.
success: function(data) {
},
dataType: dataType //Type of data you are expecting from server such as xml, json, html, etc
});

passing javascript object array to ajax

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

jQuery ajax not passing data JSON value

I am having some issues with the jQuery Ajax function and PHP.
I am checking the existance of the nav key in the $_REQUEST variable in PHP with code such as this:
if ($_REQUEST['nav']) {
// do something
} else {
echo 'Please specify NAV.';
}
However the above expression never evaluates as nav is never passed to it and always outputs 'Please specify NAV.'
console.log('paramList: ' + paramList);
$.ajax({
type: 'POST',
url: '/admin/nav_builder/edit.php?act=save&nav_id=<?php echo $nav_id; ?>',
data: {'nav':paramList},
dataType: 'json',
error: function(xhr, err) {
loadLayout();
hideLoader();
hideLoaderPalette();
},
success: function(data){
$('.errorMsg').html(data.html);
hideLoader();
hideLoaderPalette();
}
});
Using the Firefox Firebug plugin I can see that paramList does indeed hold a value, this is:
paramList:
{"section0":{"elem0":{"nav_palette":"text","nav_name":"fdgfdgdfg","nav_url":""},"elem1":{"nav_palette":"category","c_id":"226"}}}
I can't see for the life of my why nav is not being passed to the URL provided to the ajax function.
Try to print first if the "nav" parameter if it has a value.
echo $_REQUEST['nav'];
The other one is that you have used two method in one request.
Just try the following.
$.ajax({
type: 'POST',
url: '/admin/nav_builder/edit.php',
data: {act:'save', nav_id:'<?php echo $nav_id; ?>', nav:paramList},
dataType: 'json',
error: function(xhr, err) {
loadLayout();
hideLoader();
hideLoaderPalette();
},
success: function(data){
$('.errorMsg').html(data.html);
hideLoader();
hideLoaderPalette();
}
});
Try $_POST instead. As you're posting the nav contents.

Categories