Pushing data into in array Ajax - javascript

I have the following code where I make a loop to get data and send that data to a select .
I'm trying to save this data in an array and then display that data in a select
apparently the error comes from the line newOptions.push ({v.c_group: v.c_codigo_group}); since it asks me for a string , I think
here my code.
case <?php echo "'".$row["c_codigo_producto"]."'"; ?>:
$("#divhidden").first().show("fast", function() {});
var newOptions = {};
$.ajax({
data: {
'valor': valor
},
url: 'JSON/search_group.php',
type: 'POST',
dataType: 'json',
cache: false,
success: function(data) {
$.each(data, function(k, v) {
newOptions.push({ v.c_group : v.c_codigo_group });
});
},
async: false,
});
var $el = $('#grupo');
$el.html(' ');
$.each(newOptions, function(key, value) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
break;
<?php } ?>

Related

Show option as selected in each loop

I am rendering all the option of the select box through an ajax call inside $(document).ready() function.
I have a PHP variable at the top of the page which is initialized with 1 like
$expert_id = 1;
Now here is my code
$(document).ready(function(){
$.ajax({
type: "POST",
url: "<?php echo base_url('insoadmin/experts/all_experts');?>",
dataType: "json",
success: function(data, page) {
$.each(data, function(i, item) {
//console.log(data[i].expert_name);
$('#expert').append($('<option>', {
value: data[i].expert_id,
text : data[i].expert_name,
}));
});
}
});
});
While appending all the option to my expert select box I want to check if data[i].expert_id is equal to my php variable or not, if it is equal to my PHP variable then it should be selected.
How can I achieve that?
Use selected property/attribute while creating jQuery object(<option>)
Refer jQuery( html [, ownerDocument ] )
var data = [{
expert_id: 1,
expert_name: 'rayon'
}, {
expert_id: 2,
expert_name: 'bye'
}];
var expert_id = 2;
$.each(data, function(i, item) {
$('#expert').append($('<option>', {
value: data[i].expert_id,
text: data[i].expert_name,
selected: expert_id === data[i].expert_id
}));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="" id="expert"></select>
Fiddle Demo
Have you tried like this:
$(document).ready(function(){
$.ajax({
type: "POST",
url: "<?php echo base_url('insoadmin/experts/all_experts');?>",
dataType: "json",
success: function(data, page) {
$.each(data, function(i, item) {
//console.log(data[i].expert_name);
$('#expert').append($('<option>', {
value: data[i].expert_id,
text : data[i].expert_name,
}));
});
var expert_id = '<?php echo $expert_id ; ?>';
$('#expert').val(expert_id); //setting the value of select box
}
});
});
Define at top:
<span id="foo"><?php echo $expert_id; ?></span>
Add in the script
<script>
$(document).ready(function(){
$.ajax({
type: "POST",
url: "<?php echo base_url('insoadmin/experts/all_experts');?>",
dataType: "json",
success: function(data, page) {
$.each(data, function(i, item) {
//console.log(data[i].expert_name);
$('#expert').append($('<option>', {
value: data[i].expert_id,
text : data[i].expert_name,
var foo=$('#foo').html();
if(foo==data[i].expert_id){
//do something
}
}));
});
}
});
});
</script>

How to get values from associative array using Javascript

I have a PHP script that outputs a JSON associative array when an ajax call is made to it.
The first key and value in the array (["status" : "failed"]) shows the status.
The second key and value (["message" : "Invalid Input"]) shows the message.
So i need to first run a check whether the status is "failed", if it is, get the corresponding error message and vice versa.
The problem is how do I get the second key and value pair to get the message.
Here's the JavaScript I'm utilizing:
var frmdata = new FormData($('#order-form')[0]);
$.ajax({
type: "POST",
dataType: "json",
url: 'classes/validate.php',
cache: false,
contentType: false,
processData: false,
data: frmdata,
success: function(data) {
$.each( data, function( key, value ) {
if (key == "status") {
if (value == "failed") {
} else if (value == "success") {
}
}
});
}
});
Here's the PHP script;
public function outputJSON($status, $message)
{
$this->json_output["status"] = $status;
$this->json_output["message"] = $message;
$json = json_encode($this->json_output, true);
return $json;
}
Try this:
public function outputJSON($status, $message) {
$json = json_encode(array('status'=>$status,'message'=>$message));
return $json;
}
var frmdata = new FormData($('#order-form')[0]);
$.ajax({
type: "POST",
dataType: "json",
url: 'classes/validate.php',
cache: false,
contentType: false,
processData: false,
data: frmdata,
success: function(data) {
if (data.status === 'failed') {
alert(data.message);
} else {
//data.status is success
}
}
});

Send extra parameters with ajax chosen

I'm currently using the chosen JQuery plugin :
http://harvesthq.github.io/chosen/
with this complement (to add an Ajax request) :
https://github.com/meltingice/ajax-chosen
I would like to know if anyone has ever been able to send extra parameters to the ajax function.
For now it only sends the letters in the input, but I would like to send an extra id.
Here's what i'm doing:
$("#mySelect").ajaxChosen({
minTermLength: 2,
type: "GET",
url: "/Orders/ajax_getBundleItems",
dataType: "json",
error: onItemChosenFail
},
function (data)
{
var terms = {};
$.each(data, function (i, val) {
terms[i] = val;
});
return terms;
});
I'm using the CakePHP Framework, here's my ajax function:
public function ajax_getBundleItems($term = null) {
$this->layout = false;
echo "<pre>";
var_dump($this->request->data);
var_dump($this->params['url']['term']);
echo "</pre>";
}
$this->params['url']['term'] gives me the letters in the input, and I would like $this->request->data to be an id.
Regards
you can pass it in url parameter like this:
var id = 123;
$("#mySelect").ajaxChosen({
minTermLength: 2,
type: "GET",
url: "/Orders/ajax_getBundleItems?Id="+id,
dataType: "json",
error: onItemChosenFail
},
function (data)
{
var terms = {};
$.each(data, function (i, val) {
terms[i] = val;
});
return terms;
});
or
var MyId = 23;
$("#mySelect").ajaxChosen({
minTermLength: 2,
type: "GET",
url: "/Orders/ajax_getBundleItems",
dataType: "json",
data: { id:MyId },
error: onItemChosenFail
},
function (data)
{
var terms = {};
$.each(data, function (i, val) {
terms[i] = val;
});
return terms;
});
you can pass here you Id from some variable
This is the actual answer, using the BeforeSend option:
$('select[name=element_id]', '#f-load-tc').ajaxChosen({
type: 'GET',
url: 'dynamic_url',
dataType: 'json',
afterTypeDelay: 300,
allow_single_deselect: true,
no_results_text: "No results matched",
beforeSend: function(xhr, opts) {
opts.url += '&category_id='+$category.val();
},
},
function (data) {
console.log(data);
var terms = {};
$.each(data, function (i, val) {
terms[i] = val;
});
return terms;
});

How to access success data out of success block in jquery

jQuery.validator.addMethod("uniquerheading", function(value, element) {
var data = false;
$action_name = 'checkunquieannoucementheading';
var url = '<?php echo "$module_name/$controller_name/checkunquieannoucementheading"; ?>';
$.ajax({
url: url,
type: 'get',
data: {
"txt_heading":value
},
success: function(data) {
// Display list on the page by replacing the content on existing, get from the controller-action
return data;
}
});
}, "Annoucement heading already used");
Working Code...Just use async: false
jQuery.validator.addMethod("uniquerheading", function(value, element) {
$action_name = 'checkunquieannoucementheading';
var response = false;
var url = '<?php echo "$module_name/$controller_name/checkunquieannoucementheading"; ?>';
$.ajax({
url: url,
type: 'get',
data: {
"txt_heading":value
},
success: function(data) {
// Display list on the page by replacing the content on existing, get from the controller-action
response = data;
},
async: false
})
return response;
}, "Annoucement heading already used");

Assigning ajax call return value to an var with jquery

How can I assign a variable(var) to a json object which is returned from ajax call to the server? I need to access that object in the rest of the body.
For example, I've try this, I don't know it's correct.
var selectValues=$(document).ready(function() {
$.ajax({
type: "POST",
url: "http://10.0.2.2/mobileajax/callajax.php",
data: ({name: theName}),
cache: false,
dataType: "text",
success: onSuccess
});
})
var $vendor = $('select.mobile-vendor');
var $model = $('select.model');
$vendor.change(
function() {
$model.empty().append(function() {
var output = '';
$.each(selectValues[$vendor.val()], function(key, value) {
output += '<option>' + key + '</option>';
});
return output;
});
}).change();
// bonus: how to access the download link
$model.change(function() {
$('a#download-link').attr('href', selectValues[$vendor.val()][$model.val()]).show();
});
Note that, variable selectValues is used in the rest of the body.
I think you should do the whole code inside the $(document).ready(function() function and then make the ajax call synchronous. Because now the ajax call will be made when the document is ready, but the other code will be run directly without waiting for the document to be ready. Also the ajax call is asynchronous by default, so you should make it synchronous and assign the selectValues variable inside the success function of the ajax call. It will become something like this:
$(document).ready(function() {
var selectValues;
$.ajax({
type: "POST",
url: "http://10.0.2.2/mobileajax/callajax.php",
data: ({name: theName}),
cache: false,
dataType: "text",
async: false,
success: function(data) {
selectValues = data
}
});
var $vendor = $('select.mobile-vendor');
var $model = $('select.model');
$vendor.change(
function() {
$model.empty().append(function() {
var output = '';
$.each(selectValues[$vendor.val()], function(key, value) {
output += '<option>' + key + '</option>';
});
return output;
});
}).change();
// bonus: how to access the download link
$model.change(function() {
$('a#download-link').attr('href', selectValues[$vendor.val()][$model.val()]).show();
});
})
you have to define the var outside the document ready scope like this:
var selectValues;
$(document).ready(function() {
// ajax
});
in the onSuccess function you can define the selectValues = data or something like that
$.ajax({
type: "POST",
url: "http://10.0.2.2/mobileajax/callajax.php",
data: ({name: theName}),
cache: false,
dataType: "text",
success: function (result){
var selectValues=result;
}
});
try this.
Here is how we extract the returned information from our (xml) ajax calls:
$.ajax ({
type: "POST",
url: "something.cgi?someparam=whatever",
data: "key=val&key2=val2",
dataType: "xml", // you use json, but I don't think it matters
success: function (data) {
if ($("error", data).text() === "") {
// I could assign $("error", data).text() to a var just here
// This gets the "error" parameter out of the returned xml or
// json, here contained in "data"
}
[snip the rest]
Another way to do this is to add the rest of your code in the success callback lik this:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "http://10.0.2.2/mobileajax/callajax.php",
data: ({name: theName}),
cache: false,
dataType: "text",
async: false,
success: function(selectValues) {
var $vendor = $('select.mobile-vendor');
var $model = $('select.model');
$vendor.change(
function() {
$model.empty().append(function() {
var output = '';
$.each(selectValues[$vendor.val()], function(key, value) {
output += '<option>' + key + '</option>';
});
return output;
});
}).change();
// bonus: how to access the download link
$model.change(function() {
$('a#download-link').attr('href', selectValues[$vendor.val()][$model.val()]).show();
});
}
});
})

Categories

Resources