Unable to pass the data to php function using Ajax in jquery - php

I am unable to pass the data to a PHP function using ajax in jquery.
function updateinventory(product_code,user_id,id,outlet_id) {
var qtyid = 'qty_'+outlet_id;
//alert(product_code);
var dataString = {pcode:product_code};
var newqty = $('#qty_'+outlet_id).val();
//alert(newqty);
jQuery.ajax({
url: "<?=base_url()?>inventory/updateInventoryQtyFromProduct",
data: dataString,
type: "POST",
dataType: 'json',
success:function(data){
console.log("success"+data);
},
error:function (error){
console.log(error);
}
});
}
and the PHP function is where I am trying to return the $pcode just to check if data is passing here or not.
public function updateInventoryQtyFromProduct()
{
$pcode=$_POST['pcode'];
// $us_id=$_POST['user_id'];
return $pcode;
}

You have to pass like this :
public function updateInventoryQtyFromProduct()
{
$pcode=$_POST['pcode'];
echo json_encode($pcode);
or
echo json_encode(array('pcode'=>$pcode)); //if array need
}

Related

Can't display Ajax value

I have a problem with my ajax, it can't display data from database.
Controller
public function rating() {
$rating = $this->db->select_avg('hasil_rating')
->get('tb_rating')->row_array();
echo json_encode($rating);
}
Ajax
function rate() {
$.ajax({
type: 'POST',
url: '<?php echo base_url()."rate/rating"?>',
dataType: 'json',
success: function(data) {
$('#aaaa').val(data);
}
});
input
<input id="aaaa" type="text" value="">
when I used val() the result is [object Object] and when I used html() the result is empty. But when I use console.log(data) it works.
Just convert json object to string and it will work.
$('#aaaa').val(data.someVar);
For example,
var jsonVal = {val1:'one',val2:'two'};
alert(jsonVal); // it will print [object][object]
alert(jsonVal.val1); // one
alert(jsonVal.val2); // two
alert(JSON.stringify(jsonVal)) // it will print {val1:'one',val2:'two'}
Hope it will help you.
You need to first decode the json in your ajax success.
Use this.
function rate() {
$.ajax({
type: 'POST',
url: '<?php echo base_url()."rate/rating"?>',
dataType: 'json',
success: function(data) {
var d = $.parseJSON(data);
$('#aaaa').val(d.value);
}
});
Using this you can access different values from data and set the value in your html.
Update
In your controller you can return the value using json_encode like
echo json_encode(array("success"=>true,"msg1"=>"test ajax","msg2"=>"test ajax 2"));
In your ajax success function to get the value of msg1 you can use
var d = $.parseJSON(data);
alert(d.msg1); //will return "test ajax"
alert(d.msg2); //will return "test ajax 2"
By this way you can access each and every value from your json object.
You have to require $.pasrseJSON before use the data
function rate() {
$.ajax({
type: 'POST',
url: '<?php echo base_url()."rate/rating"?>',
dataType: 'json',
success: function(data) {
data=$.parseJSON(data);
$('#aaaa').val(data.var_name);
}
});

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');

Jquery ajax parameter is undefined in the PHP script

I'm using jQuery Ajax to send parameters to a PHP script. Below is the Jquery ajax script
jQuery
<script>
$(document).ready(function () {
$("#builder_group").change(function () {
var selected_builder = $(this).val();
alert(selected_builder);
$.ajax({
type: 'POST',
url: 'getGroupzCode.php',
data: 'selected_builder',
datatype: 'json',
success: function (data) {
// Call this function on success
console.log(data);
var yourArray = JSON.parse(data);
console.log(yourArray);
$.each(yourArray, function (index, yourArray) {
$('#builder_group1').append($('<option/>', {
value: yourArray.id,
text: yourArray.name,
}));
});
},
error: function () {
displayDialogBox('Error', err.toString());
}
});
});
});
</script>
When I see in firebug console I see the parametr passed is correct as selected but in the PHP script I see undefined index
PHP
$builder_id=$_POST['selected_builder'];
error_log($builder_id);
data: 'selected_builder',
That is not proper format. You need:
data: { selected_builder: selected_builder }
The below indicates you're receiving a json, is that correct? If so the parameter is "dataType" like below.
dataType: 'json',
If so you are you would use this in your php file:
$encoded = json_encode($yourvariable);
echo $encoded;
Now if this wasn't the case you would call the variable in php by:
$variable = $_POST["selected_builder"];

Jquery .post() not passing data to PHP file

I am trying to pass an array through post to a php file. Here is my function in jQuery:
function callPHP() {
$.post("php/save.php", {
node: node
},
function (responde) {
console.log(responde);
});
}
And my save.php file has following content:
<?php
echo $_POST['node'];
?>
But I get an error that there's an undefined index 'node'. What is it that I am doing wrong?
try following
//define php info and make ajax call
$.ajax({
url: "php/save.php",
type: "POST",
data: { node: node },
cache: false,
success: function (response) {
}
});
Consider the below example. where info is an array
info = [];
info[0] = 'hi';
info[1] = 'hello';
$.ajax({
type: "POST",
data: {info:info},
url: "index.php",
success: function(msg){
$('.answer').html(msg);
}
});
.answer is the class of the element where you want to output your answer.

Get data from php script in javascript

I try to receive a PHP response in my JavaScript.
My PHP looks like this:
some code
if(...) echo "1";
else echo "2";
JavaScript:
function GetChoice() {
var returned="";
$.ajax({
async: false,
cache: false,
url: "http://mydomain.com/script.php",
type: "POST",
dataType:"text",
success: function(data) {
returned = data;
}
});
return returned;
}
var r = GetChoice();
alert(r);
But GetChoice() returns nothing. What's wrong?
UPD: It works if javascript and php script are on the same server. My scripts in different domains.
Try this :
temp1.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function GetChoice() {
var returned = "";
$.ajax({
async: false,
cache: false,
type: "POST",
url: "http://localhost/temp2.php",
data: { name: "John"}
}).done(function( msg ) {
returned = msg;
});
return returned;
}
var r = GetChoice();
alert(r);
</script>
temp2.php
<?php
echo $_REQUEST["name"];
?>
its working....!
try this:
function GetChoice() {
var returned = "";
$.ajax({
async:false,
cache:false,
url:"http://mydomain.com/script.php",
type:"POST",
dataType:"text",
success:function (data) {
alert(data);
}
});
}
The problem is, in your example, $.ajax returns immediately and the next statement, return result;, is executed before the function you passed as success callback was even called.
Here is explanation.
How do I return the response from an asynchronous call?
Luck,
GetChoice() will return nothing before the callback in success runs.
The callback, which is the function you define as the success paramater will not fire until the data have been requested from the server.
This is asyncronous (the A in AJAX) so the rest of the code with continue causing the GetChoice() function to return before the callback has been run
this is the script
<script type="text/javascript">
$.ajax({
async:false,
cache:false,
url:"http://path.com/to/file",
type:"POST",
dataType: "html",
data: 'data',
success: function(data){
alert(data);
}
});
and in your PHP file write this code
<?php
function test()
{
$str = 'This is php file';
return $str;
}
echo test();
?>
Make sure the path to the php file is correct AND add the script in another PHP file. Basically you need 2 files. Just tested this in my editor and works ..
function GetChoice() {
var returned="";
$.ajax({
url: "../script.php",
type: "POST",
success: function(data) {
returned = data;
}
});
return returned;
}
var r = GetChoice();
alert(r);

Categories