Adding values to serialised Array Jquery - javascript

Im trying to add data to a preserialised array. Its not working. Anyone spot why?
$("#show-friends").live("click", function() {
var friendSelector = $("#jfmfs-container").data('jfmfs');
var sendArr = $(friendSelector).serializeArray();
sendArr.push({ name: "userid", value: "<?php echo $userId;?>" });
sendArr.push({ name: "fid", value: "<?php echo $fid;?>" });
$.post({
url:'test.php',
data: sendArr,
});
});
Edit: I changed my code to:
$("#show-friends").live("click", function() {
var friendSelector = $("#jfmfs-container").data('jfmfs');
var sendArr = friendSelector.serializeArray();
$.post({
url:'test.php',
data: "name=<?php echo $userId;?>&fid=<?php echo $fid;?>&jsondata="+sendArr,
});
});
However I get a error friendSelector.serializeArray is not a function

Your $post call is incorrect. You don't pass an object like you would for $.ajax. You pass the url, then the data (if any), and then a callback (if you want).
It should be:
$.post('test.php', sendArr);
Or with $.ajax:
$.ajax({
url:'test.php',
data: sendArr,
type: 'POST'
});
EDIT: When you do $("#jfmfs-container").data('jfmfs'), this is return you the value of the jfmfs data. friendSelector.serializeArray doesn't work, because friendSelector is whatever the data was, not a jQuery object.

Related

Ajax select list

I want to retrive the result of this kind of data list with CakePHP 3
<?= $this->Form->select('notif_message',
[ 'oui' => 'oui', 'non' => 'non'], array('id' => 'notifmess')); ?>
<?= $this->Form->hidden('notifmessage', ['value' => $notif_message]) ;?>
The goal is when a user chosse a value, an Ajax call to this controller be done
public function notifmessage() // mise à jour des paramètres de notifications 0 = non, 1 = oui
{
if ($this->request->is('ajax')) {
$notifmessage = $this->request->data('notifmessage');
if($notifmessage == 'oui')
{
$new_notif_message = 'non';
}
else
{
$new_notif_message = 'oui';
}
$query = $this->Settings->query()
->update()
->set(['notif_message' => $new_notif_message])
->where(['user_id' => $this->Auth->user('username') ])
->execute();
$this->response->body($new_notif_message);
return $this->response;
}
}
And i would like to do this call in Ajax without reloading , i have this script
<script type="text/javascript">
$(document).ready(function() {
$('.notif_message').change(function(){
$.ajax({
type: 'POST',
url: '/settings-notif_message',
data: 'select.notif_message' + val,
success: function(data) {
alert('ok');
},
error: function(data) {
alert('fail');
}
});
});
});
</script>
he doesn't work, nothing happend but i don't know why, i don't have any message in log, i can't debug without indication what doesn't not work
Thanks
In yout javascript you should use $('#notifmess').change(… or $('[notif_message]').change(… instead of $('.notif_message').change(….
In CakePHP the first argument of the select method will be used as the name attribute of the select tag.
Update:
In your controller you are retrieving the value of $_POST['notifmessage'], which is the name of the hidden input field.
To get the user's choice you either should use $this->request->data('notif_message'); in the controller, or setting up the ajax request to send the data with notifmessage like so:
$('[name="notif_message"]').change(function(){
$.ajax({
type: 'POST',
url: '/settings-notif_message',
data: {'notifmessage' : this.value},
success: function(data) {
// To change selected value to the one got from the server
$('#notifmess').val(data);
alert('ok');
},
error: function(data) {
alert('fail');
}
});
});
(Where in this case this is referring to <select> tag.)
i'm close to success: my ajax call is working, database update is working , i juste need to put the 'selected' to the other , i'm trying with this jquery code
<script type="text/javascript">
$(document).ready(function() {
$('#notifmess').change(function(){
var id = $('#notifmess').val();
$.ajax({
type: 'POST',
url: '/instatux/settings-notif_message',
data: {'id' : id},
success: function(data){
$('#notifmess option[value="'+data.id+'"]').prop('selected', true);
},
error: function(data)
{
alert('fail');
}
});
});
});

How to put response of an AJAX in SPAN?

i want to post an input and select to an php site using ajax and get the result displayed in a span using the success function.
After searching, I can't get it really done, below is my code so far:
<span id="span_to_post_response"></span>
$(document).on("click", "#btn_to_click", function () {
var form_to_send_in_var = $("#form_to_serialize").serialize();
$.post('<?php echo base_url();?>api/mySite',form_to_send_in_var);
});
Where do I put my success function?
Instead of using .post function,Try using something like this
jQuery.ajax({
url: '<?php echo base_url();?>api/mySite',
type: 'POST',
data: {
// Send the data you want
// email: jQuery('.address').val()
},
success: function(data){
jQuery('#span_to_post_response').text(data);
},
error: function() {
jQuery('#span_to_post_response').text('Sorry, an error occurred.');
}
});

AJAX jquery json sending array to php

I'm trying to send a associative array via AJAX $.post to php. Here's my code:
var request = {
action: "add",
requestor: req_id,
...
}
var reqDetails = $("#request_details").val();
switch(reqDetails){
case 1:
request[note] = $("#note").val();
break;
...
}
if(oldRequest()){
request[previousID] = $("old_id").val();
}
$('#req_button').toggleClass('active');
$.post("scripts/add_request.php", {
request_arr: JSON.stringify(request)
}, function(data){
console.log(data);
$('#req_button').toggleClass('active');
}, 'json');
And i'm simply trying to read the received data in my php script:
echo json_decode($_POST["request_arr"]);
But it's not working. I'm a newbie to js, I can't figure out what I'm doing wrong.
Check below link for your reference
Sending an array to php from JavaScript/jQuery
Step 1
$.ajax({
type: "POST",
url: "parse_array.php",
data:{ array : JSON.stringify(array) },
dataType: "json",
success: function(data) {
alert(data.reply);
}
});
Step 2
You php file looks like this:
<?php
$array = json_decode($_POST['array']);
print_r($array); //for debugging purposes only
$response = array();
if(isset($array[$blah]))
$response['reply']="Success";
else
$response['reply']="Failure";
echo json_encode($response);
Step 3
The success function
success: function(data) {
console.log(data.reply);
alert(data.reply);
}
You are already using "json" as dataType, so you shouldn't apply 'stringify' operation on your data.
Instead of request_arr: JSON.stringify(request), can you try request_arr: request directly?

Bootstrap 2.2.1 Typeahead

PHP, returns a JSON encoded array
$this->load->model('car_model', 'cars');
$result = $this->cars->searchBrand($this->input->post('query'));
$this->output->set_status_header(200);
$this->output->set_header('Content-type: application/json');
$output = array();
foreach($result as $r)
$output['options'][$r->brandID] = $r->brandName;
print json_encode($output);
Outputs: {"options":{"9":"Audi","10":"Austin","11":"Austin Healey"}}
JS updated:
$(".searchcarBrands").typeahead({
source: function(query, typeahead) {
$.ajax({
url: site_url + '/cars/search_brand/'+query,
success: function(data) {
typeahead.process(data);
},
dataType: "json"
});
},
onselect: function(item) {
$("#someID").val(item.id);
}
});
UPDATE: Uncaught TypeError: Object function (){return a.apply(c,e.concat(k.call(arguments)))} has no method 'process'
If I type just 'A' then typeahead shows me only the first letter of each result (a bunch of A letters). If I type a second letter I see nothing anymore.
I've tried JSON.parse on the data or using data.options but no luck.
What am I doing wrong?
I've been battling this for the last day with Bootstrap 2.2.1. No matter what I did, it would not work. For me, I always got the process undefined error unless I put a breakpoint in the process function (maybe just because FireBug was open?).
Anyway, as a patch I re-downloaded Bootstrap with typeahead omitted, got the typeahead from here:
https://gist.github.com/2712048
And used this code:
$(document).ready(function() {
$('input[name=artist]').typeahead({
'source': function (typeahead) {
return $.get('/7d/search-artist.php', { 'artist': typeahead.query }, function (data) {
return typeahead.process(data);
});
},
'items': 3,
'minLength': 3
},'json')
});
My server returns this (for 'Bo'):
["Bo","Bo Burnham","Bo Diddley","Bo Bruce","Bo Carter",
"Eddie Bo","Bo Bice","Bo Kaspers Orkester","Bo Saris","Bo Ningen"]
Of course, now it ignores my minLength, but it will get me through the day. Hope this helps.
EDIT: Found the solution here:
Bootstrap 2.2 Typeahead Issue
Using the typeahead included with Bootstrap 2.2.1, the code should read:
$(document).ready(function() {
$('input[name=artist]').typeahead({
'source': function (query,typeahead) {
return $.get('/search-artist.php', { 'artist': encodeURIComponent(query) }, function (data) {
return typeahead(data);
});
},
'items': 3,
'minLength': 3
},'json')
});
Here's what I do to facilitate remote data sources with bootstrap's typeahead:
$("#search").typeahead({
source: function(typeahead, query) {
$.ajax({
url: "<?php echo base_url();?>customers/search/"+query,
success: function(data) {
typeahead.process(data);
},
dataType: "json"
});
},
onselect: function(item) {
$("#someID").val(item.id);
}
});
And then you just need to make sure your JSON-encoded arrays contain a value index for the label and an id field to set your hidden id afterwards, so like:
$this->load->model('car_model', 'cars');
$brands = $this->cars->searchBrand($this->uri->segment(4));
$output = array();
foreach($brands->result() as $r) {
$item['value'] = $r->brandName;
$item['id'] = $r->brandID;
$output[] = $item;
}
echo json_encode($output);
exit;
$.post is asynchronous, so you can't user return in it. That doesn't return anything.

jQuery: how to refresh javascript value on select event?

I have such code:
var regions = [{'label': 'array', 'value': '1'}]; //default values
$("#auto1").select({
regions = jQuery.parseJSON( //updating process
$.ajax({
type: 'POST',
url: '/ajax/place/',
data: { country: value }
})
);
return false;
});
$("#auto2").some_func({
initialValues: regions, //here must be updated values, but it's not
});
I think it is understandable from above code: when page loaded, element #auto2 has default values, but when I select smth from #auto1 it must be updated, but it's not.
How can I update the values corresponding to data value.
Thanks!
$("#auto1").select({
regions = jQuery.parseJSON( //updating process
$.ajax({
type: 'POST',
url: '/ajax/place/',
data: { country: value },
success: function( data ) {
//trying yo update values, after successfull response
//some cool code is here or calling a function to update values
},
error: function( data ) {
//error to update
}
}
})
);
return false;
});
Your problem is with how you are trying to get your ajax data back. ajax calls are asyncrynous, which means they will not hold up the code until they return. Because of this jQuery.ajax allows for you to tie into success and failure callbacks which fire depending on if the ajax response returned a success or failure code. You need to parse your data in the success callback and store it in a variable at a scope where your some_func method can see it
var regions = [{'label': 'array', 'value': '1'}]; //default values
$("#auto1").select({
$.ajax({
type: 'POST',
url: '/ajax/place/',
data: { country: value },
success: function(data){
regions = jQuery.parseJSON(data);
}
});
return false;
});
$("#auto2").some_func({
initialValues: regions
});

Categories