remove quotation marks from jquery array - php

In my function I search with jquery all items of a owl carousel and take from the id only the available numbers. Because I only need the ID numbers of the items. I send the ID numbers via ajax to my php controller for further processing.
var slideArray = $('#categoryInterestCarousel_' + categoryIdOld).find('.interestOwl');
//Step 1: initialize the array
var previewIds = [];
//Step 2: Search for all IDs and add only the id to the array
$(function() {
$(slideArray).each(function(index) {
previewIds[index] = $(this).attr('id').replace(/\D/g, '');
});
});
As output I get the following array:
array:3 [
0 => "183"
1 => "198"
2 => "201"
]
I need the array without quotation marks, which it looks like:
array:3 [
0 => 183
1 => 198
2 => 201
]
Send data via ajax:
$.ajax({
type: 'GET',
url: '/categorie/owl/' + categoryIdOld,
data: {
previewIds: previewIds
},
success: function(data) {
//add some data to view
},
error: function(xhqr, staus, message) {
var response = JSON.parse(xhqr.responseText);
var errors = response.errors;
for (var error_key in errors) {
var error = errors[error_key];
_toastr_new(error, "top-full-width", "error", false, '.toastr-notify', 0);
}
}
});
get data on Controller:
public function ajaxOwlItems(Request $request, $id) {
$preview_id = $request->previewIds;
dd($request->previewIds);
}
Where's my mistake? How can I remove the quotation marks?

Like this - you need to cast the string to number - I use +
I took the liberty to streamline the code too - for example no need to use $(slideArray) since it is already a jQuery collection.
let categoryIdOld =3;
const previewIds = $('#categoryInterestCarousel_' + categoryIdOld)
.find('.interestOwl')
.map(function() { return +this.id.replace(/\D/g, ''); })
.get();
console.log(previewIds);
console.log(JSON.stringify(previewIds)); // still numeric
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="categoryInterestCarousel_3">
<span class="interestOwl" id="x183"></span>
<span class="somethingElse" id="x999"></span>
<span class="interestOwl" id="x198"></span>
<span class="interestOwl" id="x201"></span>
</div>

Just add parseInt() around the value:
$(function() {
$(slideArray).each(function(index) {
previewIds[index] = parseInt($(this).attr('id').replace(/\D/g, ''), 10);
});
});

Related

increase number with ajax php and mysql

I need it to fit and I click on a file to increase the number to 1 and saved in the database
I already have the database created and part of the AJAX code ready, in addition to the number YA INCREMENTA, the issue is that I have an update of the page manually instead of only updating the div
Number to update
<span id="'.$rowRE[id_reclamo].'" class="badge badge-primary badge-pill like">'.$rowRE[positivo].'</span>
Function with ajax
$(document).ready(function () {
$('.like').on('click', function () {
var reclamoID = $(this).attr('id');
if (reclamoID) {
$.ajax({
type: 'POST'
, url: 'like.php'
, data: 'reclamo_id=' + reclamoID
, success: function () {}
});
}
else {
alert("error");
}
});
});
php code
$reclamoID=$_POST['reclamo_id'];
$query = $db->query("UPDATE reclamos SET positivo = positivo +1 WHERE id_reclamo = $reclamoID");
//Count total number of rows
$rowCountTabla = $query->num_rows;
I need you NOT to recharge the entire page if not ONLY THE NUMBER
Return the count in the same request you make when you post your data. Something along the lines of:
PHP:
$reclamoID = pg_escape_string($_POST['reclamo_id']);
$results = $db->query("SELECT positivo FROM reclamos WHERE id_reclamo = '".$reclamoID."'");
// Whatever DB wrapper you're using here... this is just a guess.
$count = $results[0]['positivo'];
echo json_encode(array(
'id' => $reclamoID,
'count' => $count
));
Javascript:
$('.like').on('click', function () {
var element = $(this);
var reclamoID = element.attr('id');
if (reclamoID) {
$.post(
'like.php',
{
reclamo_id: reclamoID
},
function (responseData) {
element.text(responseData.count);
},
'json'
);
}
});
ALWAYS sanitize posted data, to prevent injections and other malicious code.

select2 drop-down plugin with auto-populate together with add new record

I'm now working with select2 drop-down plugin. I came situation that I have to add a select2 field which auto populate the existing mail id's in our app. I was able to do so, but I also has to add new mail id's which are not in our app in same field. I do not able work it out. Can any of you please help me out from this...
Here is my view page code.
<input type="hidden" class="select2 to_email w-100" name="to_email[]"
data-role="to_email" data-width="100%" data-placeholder="To" value="">
Js code:
$('body').on('click','[data-button="reply-mail"],[data-click="reply"]', function() {
attach = [];
var $ti = $(this).closest('[data-role="row-list"]').find('[data-role="reply-mail-wrap"]');
var $to_this = $ti.find('[data-role="to_email"]');
var mail_toadr = $ti.find('input[name="to_addr"]').val();
$($to_this).select2({
placeholder: "Search for a contact",
minimumInputLength: 3,
//maximumSelectionLength: 1,
multiple : true,
ajax: {
url: Utils.siteUrl()+'mailbox/get_all_contacts',
type: 'POST',
dataType: 'json',
quietMillis: 250,
data: function (term, page) {
return {
term: term, //search term
page_limit: 100 // page size
};
},
results: function (data, page) {
return { results: data};
}
},
initSelection: function(element, callback) {
return $.getJSON(Utils.siteUrl()+'mailbox/get_all_contacts?email=' + (mail_toadr), null, function(data) {
return callback(data);
});
}
});
});
I know, working example could be better to you, but I'm sorry, I do not know how to do it.
A screen shot for small help:http://awesomescreenshot.com/08264xy485
Kindly help..
I have got a fix for my requirement. If we enter a non-existing value in our field, results: function (data, page) {...} returns an empty array. We can check this as:
results: function (data, page) {
for (var obj in data) {
id = JSON.stringify(data[obj].id);
text = JSON.stringify(data[obj].text);
if (id == '"0"') {
$ti.find('.to_email').select2('val', '<li class="select2-search-choice"><div>'+ text +'</div><a tabindex="-1" class="select2-search-choice-close" onclick="return false;" href="#"></a></li>');
}
}
return { results: data};
}
But, better than this I suggest you to do a check in the area where we fetch result (here: Utils.siteUrl()+'mailbox/get_all_contacts'). I have done this to fix my issue:
function get_all_contacts()
{
// $contacts is the result array from DB.
// $term is the text to search, eg: 111
foreach($contacts as $contact_row) {
$contact_all[] = array('id' => $contact_row['id'], 'text' => $contact_row['primary_email']);
}
if (empty($contact_all)) {
$contact_all = array('0' => array('id' => 'undefinedMAILID_'. $term, 'text' => $term ) );
}
$contact_data['results'] = $contact_all;
send_json_response($contact_all);
}
Getting value in JS:
sel_ids = $('.to_email').select2('val');
console.log(sel_ids);
// console will show - ["value if mail id is existing", "undefinedMAILID_111"]
hope this will help someone.

Returning an array from DB query as JSON and then putting the contents into list elements with jQuery

I have a commenting system I am working on thats is aiming to be like instagrams system.
Currently, I show the last 3 items in a PHP foreach and also have a 'show all button'.
My aim is then that button gets clicked and calls a function which then returns all the comments as an array. I then would need to .prepend() this array as list elements.
Normally an AJAX call to fetch data is fine. But in the past I have only retuned one line values.
I am using Laravel so my function to fetch would be something like:
public function fetch() {
DB:: // SELECT ALL COMMENTS
$commentsArray = array();
foreach ($comments as $comment) {
$commentsArray = (array('commentusername', 'comment'));
}
return Response::json(array(
'success' => true,
'comments' => $commentsArray,
200)
);
}
And then in my jQuery call:
if (data.success) {
$(".comments_"+id).prepend("<li><b>USERNAME:</b> Comment</li>");
}
That prepend woulds as I want, but I need to learn how I should be correctly creating the array, and then how I can loop through them and create the list elements in jQuery.
Note, that PHP function is written here and untested etc.
Thanks.
First, use array_map to get an array of the format you want:
public function fetch() {
DB:: // SELECT ALL COMMENTS
$commentsArray = array_map(function($comment){
return array(
'username' => $comment->commentusername,
'comment' => $comment->comment
);
}, $comments);
return Response::json(array(
'success' => true,
'comments' => $commentsArray
));
}
(I changed commentusername to username for the output array. Also you don't need the 200 in your response)
Now this is what your response will look like:
{
success: true,
comments: [
{username: 'foo', comment: 'comment of foo'},
{username: 'foo', comment: 'comment of foo'}
]
}
Then in your javascript code, do this:
if (data.success) {
for(var i=0; i<data.comments.length; i++){
var comment = data.comments[i];
$(".comments_"+id).prepend("<li><b>"+comment.username+":</b> "+comment.comment+"</li>");
}
}
Also note that if you use HTTP status codes for errors, you can remove success: true and assume that if the response is 200 (ajax success callback) the request has been made successfully.
I could not understand your question, but i m gonna to show you, how you can get json response from script and then can parse that,
// script.php
<?php
$data = array(
array('User' : 'Tiger', 'Comment' : 'Any comment,, '),
array('User' : 'John', 'Comment' : 'Tiger is nice guy !!')
); // In reality data will fetch from Db
header('Content-Type: application/json'); // must be set, and no space between ...pe and ':'
echo json_encode($data);
?>
client_side.js
$.get('script.php', function(data) {
for(i = 0; i < data.length; i++){
$(".comments_"+id).prepend("<li><b>USERNAME :</b> " + data[i].User + " <b> Comment :</b> " + data[i].Comment + "</li>"); // You should use templete here
} // __prepending comments
}, 'json');
Thanks :)
First of all, you need to add your arrays to an array. As you do, you are always just overwrite your variable:
$commentsArray[] = (array('commentusername', 'comment'));
add a [] after your name of variable.
And then in the jQuery:
$.each(data, function(idx, obj) {
$(".comments_"+id).prepend("<li><b>USERNAME:" + obj.commentusername + ", </b> Comment</li>" + obj.comment);
});
NOTE: Don't forget to check and change your id in the loop.

jQuery AJAX Update a dropdown select onChange return an empty string

Can someone tell me what I'am doing wrong here, console.log() returns me an empty string instead of an array ?
I want to update the second selectbox once onChange is triggered on first selectbox but I can't retrieve the data. When I'am doing a var_dump($results) it successfully shows an array of items, but return $results returns me an empty string.
Here how it looks like:
a javascript:
function _getNestedSelectOptions(activeComponent){
$.ajax({
type: "POST",
url: "/backend/categories/get_nested_options/" + activeComponent
}).done(function(html){
console.log(html);
});
}
And this is a php code controllers/backend/categories.php:
public function get_nested_options($cid = FALSE){
if($cid == FALSE)
$cid = $this->activeComponent;
$categoriesResult = $this->categories_model->get_categories_tree_by_com($cid);
$categoriesDropdownOptions = array();
$this->categories_model->get_nested_options($categoriesDropdownOptions, $categoriesResult);
var_dump($categoriesDropdownOptions); // <-- THIS WORKS AND SHOWS AN ARRAY OF ITEMS
//return $categoriesDropdownOptions; // <-- THIS DOES NOT WORKING
}
here is an output on console.log():
array (size=3)
7 => string 'Administrators' ->(length=14)
8 => string 'Managers' ->(length=8)
9 => string 'Users' ->(length=5)
You can try to get json in js, use
In controller:
public function getNestedOptions($cid = FALSE){
if($cid == FALSE)
$cid = $this->activeComponent;
$categoriesResult = $this->categories_model->get_categories_tree_by_com($cid);
$categoriesDropdownOptions = array();
$this->categories_model->getNestedOptions($categoriesDropdownOptions, categoriesResult);
echo json_encode($categoriesDropdownOptions); exit;
}
$.ajax({
dataType: "json",
type: "POST",
url: "/backend/categories/get_nested_options/" + activeComponent
data: data
}).done(function(data){
response = jQuery.parseJSON(data);
console.log(response);
});
you will get data in json format.
I managed to work it out by helps of #KA_lin (jQuery.parseJSON() didn't work, idk why) and #RameshMhetre, so thank you guys for your helps.
This is an AJAX in categories.js:
function _getNestedSelectOptions(activeComponent, targetName){
// Url in proper JSON format with datas
var url = "/backend/categories/get_nested_options/";
// Target selectbox to apply modifications on it
var ddb = $(targetName);
// Save first dummy/null option
var top = ddb.find('option:first');
$.ajax({
type: 'POST',
url: url + activeComponent,
dataType: 'json',
beforeSend: function(){
// Disable selectbox
ddb.prop('disabled', true);
},
success: function(data){
// Insert saved first dummy/null option
ddb.empty().append(top);
$.each(data, function (index, value) {
// Append html data to target dropdown element
ddb.append('<option val="'+ value.id +'">'+ value.title +'</option>');
});
// Re-enable selectbox
ddb.prop('disabled', false);
}
});
}
controllers/backend/categories.php:
public function get_nested_options($cid = FALSE){
if($cid == FALSE)
$cid = $this->activeComponent;
// Get an array of properly constructed parents and childs
$categoriesResult = $this->categories_model->get_categories_tree_by_com($cid);
// Prepare an array of dropdown option values (without keys)
$categoriesDropdownOptions = array();
// Fill in an array with appropriate values for use with form_dropdown($array)
$this->categories_model->get_nested_options($categoriesDropdownOptions, $categoriesResult);
// Prepare an array for JSON output (with keys)
$results = array();
// Modify a raw array with specific keys for use in JSON
foreach($categoriesDropdownOptions as $id => $title){
$results[] = array(
'id' => $id,
'title' => $title
);
}
// Set a proper page content and output JSON results
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($results));
}
And the views/backend/categories/form.php:
<fieldset>
<legend>Attributes</legend>
<label class="control-label" for="formCatCid">
Component name:
<div class="controls">
<?php
$componentDropdownExtra = 'class="span12" onChange="categories.getNestedSelectOptions(this.value, formCatPid);"';
echo form_dropdown('formCatCid', $componentDropdownOptions, set_value('formCatCid', $formCatCid), $componentDropdownExtra);
?>
</div>
</label>
<label class="control-label" for="formCatPid">
Category parent:
<div class="controls">
<?php
$categoriesDropdownExtra = 'class="span12"';
echo form_dropdown('formCatPid', $categoriesDropdownOptions, set_value('formCatPid', $formCatPid), $categoriesDropdownExtra);
?>
</div>
</label>
</fieldset>

Parse json data into variables and submit to a function on each iteration

I created a php script that generates the json response
this is the example of the output:
[[],{"idgps_unit":"2","lat":"40","lon":"40","name":"ML350","notes":"Andrew","dt":"2012-10-29 19:43:09","serial":"3602152","speed":"44","odometer":"208.49"},{"idgps_unit":"1","lat":"42","lon":"39","name":"unit1","notes":"fake unit 1","dt":"2012-10-18 18:16:37","serial":"12345","speed":"0","odometer":"0.16"}]
This is how I form the response in PHP:
$data[] = array();
foreach ($list->arrayList as $key => $value) {
$unit = new Unit();
$unit = $value;
//create array for json output
$data[] = array('idgps_unit' => $unit->idgps_unit, 'lat' => $unit->lat,
'lon' => $unit->lon, 'name' => $unit->name, 'notes' => $unit->notes,
'dt' => $unit->dt, 'serial' => $unit->serial, 'speed' => $unit->speed,
'odometer' => $unit->odometer);
}
echo json_encode($data);
Now, in JS I did this:
function getCheckedUnits() {
jQuery(function($) {
$.ajax( {
url : "json.php?action=get",
type : "GET",
success : function(data) {
var jsonData = JSON.parse(data);
///PARSE VALUES AND SUBMIT TO A FUNCTION :: START
var C_longitude = 0;
var C_name = 0;
var C_idgps_unit = 0;
var C_serial = 0;
var C_speed= 0;
var C_notes= 0;
var C_dt = 0;
var C_time = 0;
var C_odometer = 0;
initialize(C_longitude,C_name,C_idgps_unit, C_serial,C_speed, C_notes, C_dt, C_time, C_odometer);
///PARSE VALUES AND SUBMIT TO A FUNCTION :: END
}
});
});
}
I need to parse the json reponce into values
Assuming that JSON.parse(data) only gets the associative array in the JSON response, you should be able to get the values in the JSON data like so:
var i = 1;
var C_longitude = jsonData[i]["lon"];
var C_name = jsonData[i]["name"];
Assuming that the first empty array is not removed by JSON.parse(), i = 1 would get the first batch of data and i = 2 would get the second.
The parsed JSON behaves the same way as if it was defined in JavaScript
If you put dataType: "json" in the ajax settings it will return you a json object than you don't need to parse it again. So this would look like:
function getCheckedUnits() {
jQuery(function($) {
$.ajax( {
url : "json.php?action=get",
type : "GET",
dataType: "json"
success : function(data) {
}
});
});
}
However you could also use your own option but than just use the parseJSON function so var jsonData = jQuery.parseJSON(data);

Categories