When I make an ajax call, I get the ID of my input and I add the id to my json data.
I need to get this id to use it id my success function.
IE : In data id = 1, i need in success to get .qte1
If you have any idea... :)
$('#action-button').click(function() {
$.ajax({
type: 'POST',
url: 'get_qty.php',
data: {
'id': $('input[name=qte]').val(),
},
success: function(data) {
$(".qte").html("");
$(".qte").append(data);
}
});
return false;
});
If I understood you correctly you can just concat the value as such
var data = JSON.parse(data);
var $div = "#qte" + data.id;
$($div).html("test");
I have converted to json object because if you don't have access to the php file this at least converts from string to object. Make sure you are using a #to call a specific div not a class.
This is my PHP:
header('Content-type: application/json');
$arr = array("id"=> $_POST['id'],"qty"=> "1");
echo json_encode($arr);
Related
I have post the data and return the value with json_encode and get that in ajax success stage. but i can't out that data value in specific input. Here is my html input. The return value are show in console and alert box as below.
{"status":"0","data":[{"user_id":"1","start_time":"00:00:00","end_time":"01:00:00","date_select":"2017-03-23","admin_flag":"0","interview_plan_staff_id":"1","interview_plan_staff_name":"Administrator","user_name":"\u304a\u306a\u307e\u30481"},{"user_id":"31","start_time":"00:00:00","end_time":"01:00:00","date_select":"2017-03-23","admin_flag":"0","interview_plan_staff_id":"1","interview_plan_staff_name":"Administrator","user_name":"uchida"}]}
<input type="text" id="admin_id" class="form-control">
Here is my ajax
function cal_click(cal_date){
var calDate = cal_date
var date_format = calDate.replace(/-/g, "/");
var base_url = <?php base_url(); ?>
$.ajax({
type: "post",
url: "<?php echo base_url('Admin_top/getcal');?>",
data: {calDate:calDate},
cache: false,
async: false,
success: function(result){
console.log(result);
alert(result);
}
});
}
Use JSON.parse to get specific input from result
function cal_click(cal_date){
var calDate = cal_date
var date_format = calDate.replace(/-/g, "/");
var base_url = <?php base_url(); ?>
$.ajax({
type: "post",
url: "<?php echo base_url('Admin_top/getcal');?>",
data: {calDate:calDate},
cache: false,
async: false,
success: function(result){
console.log(result);
var obj = JSON.parse(result);
alert(obj.status);
//alert(result);
var user_id = [];
var start_time = [];
for (i = 0; i < obj.data.length; i++) {
user_id[i] = obj.data[i].user_id;
start_time[i] = obj.data[i].start_time;
}
alert(' First user '+user_id[0]+' Second User '+ user_id[1]+' First start_time '+start_time[0]+' Second start_time '+ start_time[1] );
}
});
}
Use a each loop to get the ids,result is a object that has a data array:
$.each(result.data,function(i,v){
console.log(v.user_id);
//$('.admin_id').val(v.user_id);//use val to append the value, note you have multiple ids so you need multiple inputs
});
if this doesn't work then you return a string not json so you need to convert it to json using:
var result = JSON.parse(result);
Read Following posts you will get idea about json parsing
Parse JSON from JQuery.ajax success data
how to parse json data with jquery / javascript?
and you can try looping like this
var parsedJson = $.parseJSON(json);
$(parsedJson).each(function(index, element) {
console.log(element.status);
$(element.data).each(function(k,v) {
console.log(v.user_id);
});
});
When in an AJAX callback, you can use result.data to access the array of objects being returned. You can work with these like you would any other Javascript object. You may need to deserialize the JSON first.
To accomplish what you're trying to do, the following code would do the trick, although it will only use the very first object in the array as you only have one text box.
var responseObj = JSON.parse(result);
document.getElementById('admin_id').value = responseObj.data[0].user_id;
The following coding is the out come of a php page show:
user_list.php:
$myarray=array();
$myjson = json_encode($myarray);
echo $myuser->searchUser($myjson);
and the result of html is:
[{"userID":"1","username":"\u9ec3\u9ec3\u9ec3",
"sex":"F","password":"1bbd886460827015e5d605ed44252251",
"emails":"test#test.com","regdate":"2015-11-03 00:00:00",
"dob":"1994-11-02","educationID":"6","positionID":"1",
"home":"12341234","mobile":"21800000",
"address":"AC2 5\F Rm5501","grade":"Y1",
"status":"0","office_tel":"41234123",
"inviter":null,"inviter_relation":null,"believe":"0",
"remark":null}]
At I know, here is a array not an object. So how i can get those data in other page like this?
$(".edituser").click(function () {
var user = $(this).data("id");
$.ajax({
url:"user_list.php",
data:"userID="+user,
type : "POST",
dataType: "json",
success:function(data){
**console.log(data);**
},
error:function(xhr){
alert('Ajax request fail');
}
});
});
How get i get the data in ajax? thx
To get userID value, you can use:
var userID = data[0].userID;
or
var userID = data[0]['userID'];
Hi I am getting the following error when I call action in controller from ajax.
Undefined index : value.
This is my code in Document Ready
unique function is to create array of unique elements.
var modules =[];
var action = [];
var max_limit=[];
var details ={};
$(".btn-small").click(function()
{
modules = unique(modules);
action = unique(action);
limit = unique(limit);
details['id'] = id;
details['cost'] = sum;
details['modules'] = modules;
details['action'] = action;
details['limit'] = limit;
jsonString = JSON.stringify(details);
$.ajax({
url: "<?php echo Yii::app()->createUrl('/xxxxxxxx/actionDemo'); ?>",
data: {'value':jsonString },
type: 'post',
dataType:'json',
success: function() {
alert("st");
},
error: function(){
alert("Error: Could not delete");
}
});
This is my code in action in Controller :
public function actionDemo() {
$val = $_POST['value'];
var_dump($val);
die();
}
It means that "value" is not in you post data. Try to dump your POST and see what is going on.
This is probably because you are sending a JSON, so you POST will contain a JSON instead of an Array.
I think this will help you,
If you are sending JSON to server side you need to specify contentType in AJAX request. dataType:'json' says that what kind of response you expect from server.
Or else you can directly pass "data: {'value':details}," in AJAX without converting into JSON.
How do I use AJAX to return a variable in PHP? I am currently using echo in my controller to display a price on dropdown .change in a div called price.
However I have a hidden field which I need to return the row id to on change. How do I assign the return var in jQuery so that I can echo it in my hidden field?
jQuery
$(document).ready(function() {
$('#pricingEngine').change(function() {
var query = $("#pricingEngine").serialize();
$('#price').fadeOut(500).addClass('ajax-loading');
$.ajax({
type: "POST",
url: "store/PricingEngine",
data: query,
success: function(data)
{
$('#price').removeClass('ajax-loading').html('$' + data).fadeIn(500);
}
});
return false;
});
});
Controller
function PricingEngine()
{
//print_r($_POST);
$this->load->model('M_Pricing');
$post_options = array(
'X_SIZE' => $this->input->post('X_SIZE'),
'X_PAPER' => $this->input->post('X_PAPER'),
'X_COLOR' => $this->input->post('X_COLOR'),
'X_QTY' => $this->input->post('X_QTY'),
'O_RC' => $this->input->post('O_RC')
);
$data = $this->M_Pricing->ajax_price_engine($post_options);
foreach($data as $pData) {
echo number_format($pData->F_PRICE / 1000,2);
return $ProductById = $pData->businesscards_id;
}
}
View
Here is my hidden field I want to pass the VAR to every-time the form is changed.
" />
Thanks for the help!
Well.. One option would be to return a JSON object. To create a JSON object in PHP, you start with an array of values and you execute json_encode($arr). This will return a JSON string.
$arr = array(
'stack'=>'overflow',
'key'=>'value'
);
echo json_encode($arr);
{"stack":"overflow","key":"value"}
Now in your jQuery, you'll have to tell your $.ajax call that you are expecting some JSON return values, so you specify another parameter - dataType : 'json'. Now your returned values in the success function will be a normal JavaScript object.
$.ajax({
type: "POST",
url: "...",
data: query,
dataType: 'json',
success: function(data){
console.log(data.stack); // overflow
console.log(data.key); // value
}
});
echo json_encode($RESPONDE);
exit();
The exit is not to display other things except answer. RESPONDE is good to be array or object.
You can access it at
success: function(data)
{ data }
data is the responde array or whatever you echo..
For example...
echo json_encode(array('some_key'=>'yesss')); exit();
at jquery
success: function(data){ alert(data.some_key); }
if u are returning only single value from php respone to ajax then u can set it hidden feild using val method
$("#hidden_fld").val(return_val);
Im trying to retrieve some data from JSON object which holds location information such as streetname, postcode etc. But nothing is being retrieved when i try and put it in my div. Can anybody see where im going wrong with this?
This is my ajax code to request and retrieve the data
var criterion = document.getElementById("address").value;
$.ajax({
url: 'process.php',
type: 'GET',
data: 'address='+ criterion,
success: function(data)
{
$('#txtHint').html(data);
$.each(data, function(i,value)
{
var str = "Postcode: ";
str += value.postcode;
$('#txtHint').html(str);
});
//alert("Postcode: " + data.postcode);
},
error: function(e)
{
//called when there is an error
console.log(e.message);
alert("error");
}
});
When this is run in the broswer is just says "Postcode: undefined".
This is the php code to select the data from the database.
$sql="SELECT * FROM carparktest WHERE postcode LIKE '".$search."%'";
$result = mysql_query($sql);
while($r = mysql_fetch_assoc($result)) $rows[] = $r;
echo json_encode($rows), "\n"; //Puts each row onto a new line in the json data
You are missing the data type:
$.ajax({
dataType: 'json'
})
You can use also the $.getJSON
EDIT: example of JSON
$.getJSON('process.php', { address: criterion } function(data) {
//do what you need with the data
alert(data);
}).error(function() { alert("error"); });
Just look at what your code is doing.
First, put the data directly into the #txtHint box.
Then, for each data element, create the string "Postcode: "+value.postcode (without even checking if value.postcode exists - it probably doesn't) and overwrite the html in #txtHint with it.
End result: the script is doing exactly what you told it to do.
Remove that loop thing, and see what you get.
Does your JSON data represent multiple rows containing the same object structure? Please alert the data object in your success function and post it so we can help you debug it.
Use the
dataType: 'json'
param in your ajax call
or use $.getJSON() Which will automatically convert JSON data into a JS object.
You can also convert the JSON response into JS object yourself using $.parseJSON() inside success callback like this
data = $.parseJSON(data);
This works for me on your site:
function showCarPark(){
var criterion = $('#address').val();
// Assuming this does something, it's yours ;)
codeAddress(criterion);
$.ajax({
url: 'process.php',
type: 'GET',
dataType: 'json',
data: {
address: criterion
},
success: function(data)
{
$("#txtHint").html("");
$.each(data, function(k,v)
{
$("#txtHint").append("Postcode: " + v.postcode + "<br/>");
});
},
error: function(e)
{
alert(e.message);
}
});
}