I need to change my success when my checkbox get unchecked - javascript

Here is my code:
$(document).ready(function() {
$( ".iCheck-helper" ).on( "click", function(){
var sel = $('.i-check:checked').map(function(_, el) {
// if($(this).is(":checked")){
return $(el).val();
}
}).get();
// alert(sel);
var nme = $('.i-check:checked').map(function() {
// return $(el).val();
return $(this).attr("name");
}).get();
// alert(nme);
var value = this.value;
// this(attir)
var city_name =<?php echo json_encode($cityname) ?>;
var start =<?php echo json_encode($start)?>;
var end =<?php echo json_encode($end)?>;
var room_count =<?php echo json_encode($room_count)?>;
var member_count =<?php echo json_encode($member_count)?>;
var selt_guest =<?php echo json_encode($selt_guest)?>;
var selt_room =<?php echo json_encode($selt_room)?>;
// alert(city_name);
$.ajax({
// alert();
type: "POST",
url: "hotelresults",
data: {
key : sel,
name:nme,
search_city:city_name,
start:start,
end:end,
selt_guest:selt_guest,
selt_room:selt_room,
room_nf:room_count,
guest_nf:member_count,
},
success: function (data) {
$('.hotel_list').html(data);
}
});
});
});
While clicking a checkbox this success function calls.And here sel & name are passed into the controller as in array manner.
If one of my checkbox is unchecked it should pass the remaining values of the array in both sel and name.
And if all the checkboxes are unchecked my sel & name value set to null.
So here,when my values get null or all checkboxes are set unchecked I need to pass another set of data in my Success like as follows.
data: {
search_city:city_name,
start:start,
end:end,
selt_guest:selt_guest,
selt_room:selt_room,
room_nf:room_count,
guest_nf:member_count,
}
And here, I need that .map function as must because without that function my values didn't pass to the controller.

Here, rather than creating object directly in the Ajax call. Intiaite it first in a variable and assign that variable to data in call. Example below:
Var dataToSend = { search_city:city_name, start:start, end:end, selt_guest:selt_guest, selt_room:selt_room, room_nf:room_count, guest_nf:member_count}
Above are the properties which you need in every case.
Now check for optional ones as below:
If(nme && nme.length) {
dataToSend.nme = nme;
}
And same for other variable.
In last. In the Ajax call, assign variable to data, like below:
data: dataToSend
Thanks,
Manish kumar

Related

How to insert multiple values to database table using php?

Plz check this jsfiddle. My results are like this,
http://jsfiddle.net/kz1vfnx2/
i need to store these datas to database(sql server) one by one in each row using PHP Codeigniter. Insert to table looks like
Date Frequency
05-Feb-2019 1st Basic Treatment
12-Mar-2019 2nd Control Treatment
----------------------------------
--------------------------------
when button clicks call the function and insert to datatabase
$('#saveactivityarea').on('click', function(event) { //save new activity area
var act_contractbranch_firstjobdt = "2019-01-01";
var Contractend_firstjobdt = "2020-01-01";
var act_job_freq_daysbtw= "30";
saveschedule(act_contractbranch_firstjobdt,Contractend_firstjobdt,act_job_freq_daysbtw,0);
var contractID = $('#contractID').val();
var act_job_freq_contract = $("#act_job_freq_contract option:selected").val();
$.ajax({
type: "POST",
url: 'activity_submitted',
data: {
//here i need to pass date and frequency. insert to table like one by one row
getcontract_id: contractID,
getcontractbranch_firstjobdt: act_contractbranch_firstjobdt,
//etc....
},
success: function(data) {
alert('success')
}
})
PHP MODAL FUNCTION
$data_jobschedule = array(
'Contract_id' => $this->input->post('getcontract_id'),
'job_freq_id' => $this->input->post('getcontractbranch_freq')
);
$insert_id = 0;
if ($this->db->insert("job_schedule", $data_jobschedule))
$insert_id = $this->db->insert_id();
}
Please find the jQuery Ajax code here
Inside while loop
var dataArray = [];
while(condition) {
details = [];
//do your calculations
details['date'] = date;
details['frequency'] = frequency;
dataArray[] = details;
}
$.ajax({
url: "<?php echo site_url('activity_submitted'); ?>",
data: {dateArray: dataArray},
success: function(data){
alert('success');
},
error: function() { alert("Error."); }
});
In the controller and model, you need to get the data and insert it into the table.
$data = $_REQUEST['dateArray'];
$this->db->insert_batch('mytable', $data);

AJAX returns only last array item

I want to create async AJAX query to check server status when web page finish loading. Unfortunately when it comes to data display from processed PHP, I receive only single value.
JS:
<script>
window.onload = function() {
test();
};
function test()
{
var h = [];
$(".hash td").each(function(){
var hash = $(this).closest('#h').text();
if (hash) {
$.ajax({
url: 'stat.php',
method: 'POST',
async: true,
data: {hs: JSON.stringify(hash)},
success: function(data) {
$('.result').replaceWith(data);
}
});
}
});
}
</script>
PHP:
<?php
require_once ('inc/config.php');
require_once ('inc/libs/functions.php');
if (isset($_POST['hs'])) {
$hash = json_decode($_POST['hs']);
serverstatus($hash);
}
function serverstatus($hash) {
$address = DB::queryFirstRow("SELECT address,hash FROM servers WHERE hash=%s", $hash);
$address_exploded = explode(":", $address['address']);
$ip = $address_exploded[0];
$port = $address_exploded[1];
$status = isServerOnline($ip,$port);
if ($status) {
$s = "Online $ip";
} else {
$s = "Offline";
}
echo $s;
}
?>
I embed result from PHP to a table row. I see that AJAX iterating over the array, but all rows receive same value (last checked element in array).
$('.result') matches all elements with the class result. replaceWith will then replace each of them with the content you provide.
If you want to only affect the .result element within some structure (perhaps the same row?), you need to use find or similar:
function test()
{
var h = [];
$(".hash td").each(function(){
var td = $(this); // <====
var hash = td.closest('#h').text();
var result = td.closest("tr").find(".result"); // <====
if (hash) {
$.ajax({
url: 'stat.php',
method: 'POST',
async: true,
data: {hs: JSON.stringify(hash)},
success: function(data) {
result.replaceWith(data); // <====
}
});
}
});
}
Obviously the
var result = td.closest("tr").find(".result"); // <====
...will need to be tweaked to be what you really want it to be, but that's the idea.
This line in your question suggests an anti-pattern:
var hash = $(this).closest('#h').text();
id values must be unique in the document, so you should never need to find the one "closest" to any given element. If you have more than one id="h" element in the DOM, change it to use a class or data-* attribute instead.
Thank you all for help. My final, obviously very dirty but working code:
function testServerPage()
{
var h = [];
$(".hash li").each(function(){
var hash = $(this).closest('#h').text();
if (hash) {
$.ajax({
url: 'stat.php',
method: 'POST',
//async: true,
data: {hs: JSON.stringify(hash)},
success: function(data) {
$('#' + hash).replaceWith(data);
}
});
}
});
return false;
}
I just added dynamic variable to element:
success: function(data) {
$('#' + hash).replaceWith(data);
}

Sava html attr in php variable

I have list like this
John
Jack (link)
Husam (link)
Koko (link)
Rami (link)
Loay (link)
and i have dropdown list that has all the names above, when i click on link Husam side i want to displayed his parent (Jack) as selected option in dropdown, so i need pass to function getParentId the id of child whose the link clicked, and this id inside , so how i can pass the attr name of to $_GET['childId'] instead of $_GET['childId'] = 4.
I try to save attr of link inside php variable.
Is it or is it not possible?
This is my code in index.php
$_GET['childId'] = 4; // here i don't want to pass 4 i need to pass $(a).attr('name'); from another page
if ($object->getParentId($_GET['childId'])) {
echo "<script>
function changeParent(){
$(document).ready(function(){
$('a').on('click',function() {
var x = $(this).attr('id');
var y = $(this).attr('name');
$.ajax({
type: 'POST',
url: 'http://test.local/Family.php?action=getId',
data: {'childId' : $_GET[childId]},
success: function(msg) {
document.getElementById('names').value = x;
$('#save').show();
}
});
});
});
}
</script>";
}
This what I want to pass it in Family.php (the name of a href)
function getChild($family_tree,$parent){
$list = "<ul class='listSet' style='list-style-type:none'>";
foreach($family_tree[$parent] as $each_child) {
$list .= "<li>" . $each_child[0]." "."<a onclick='changeParent()' id='$parent' name='$each_child[1]' href='#'>".'Change parent'."</a>";
if(isset($family_tree[$each_child[1]])){...
Ok, so in order to do it you have to make some changes in your functionality.
This condition if ($object->getParentId($_GET['childId'])) you should move from index.php to Family.php
Next inside $('a').on('click',function() { change this line data: {'childId' : $_GET[childId]}, to this data: {'childId' : y},
function changeParent(){
$(document).ready(function(){
$('a').on('click',function() {
var x = $(this).attr('id');
var y = $(this).attr('name');
$.ajax({
type: 'POST',
url: 'http://test.local/Family.php?action=getId',
data: {'childId' : y},
success: function(msg) {
document.getElementById('names').value = x;
$('#save').show();
}
});
});
});
}

jQuery argument suddely changes into n.Event object

I have a dropdown on my page,which selected value I take like this:
<select id="campaign" class="form-control">
<option>Choose campaign</option>
<option value="createCampaign">Create new campaign</option>
<?php while($row=$resultForCampaigns->fetch_assoc()){
$campaignName=$row['campaign_name'];
echo "<option value=$campaignName>$campaignName</option>";
}?>
</select>
var campaign = $('#campaign option:selected').val();
But when I'm passing that same campaign value as a argument of new function, and do console.log(campaign) it says:
Here is the whole code:
$(document).ready(function() {
$('#campaign').change(function() {
var campaign = $('#campaign option:selected').val();
console.log(campaign);
if (campaign != 'Choose campaign') {
console.log(campaign);
$('#deleteCampaign').click(function(campaign) {
console.log(campaign);
var r = confirm("Are you absolutely sure you want to delete selected campaign?");
if (r == true) {
var data = {};
data.action2 = "deleteCampaign";
data.campaign = campaign;
$.ajax({
url: "../includes/adapter.php",
type: "POST",
dataType: "JSON",
data: data,
async: true,
success: function() {
if (data) {
console.log(data);
$('#poruka').append('<div class="alert alert-success"><strong>Success!</strong> You have successfully deleted campaign!</div>');
} else {
$('#poruka').append('<div class="alert alert-danger"><strong>Failure!</strong> Something went wrong with deleting your campaign! Please try again</div>');
}
}
});
}
});
}
});
});
So, console.log(campaign) after click on $('#deleteCampaign') turns value of campaign from one that I've gave it, to one that picture represents. Really don't know what's going on, so If anyone could explain me how to get correct value inside function that is tiggered by click, I would be very thankful.
The variable campaign is redefined when you use the same name as a function argument in a lower scope.
Variables are scoped to functions, and function arguments are considered variables, it would be the same as doing
var something = 'stuff';
function go() {
something = 'other stuff';
console.log(something); // obviously "other stuff"
}
The first argument for the click function in jQuery is the event object, you can't pass in anything else.
All you have to do is just remove the argument.
var campaign = $('#campaign option:selected').val();
$('#deleteCampaign').click(function() {
console.log(campaign); // still the value

Unable to change image onChange function on ajax success return

Hi I'm new to this javavascript/ajax. I am trying to create a dropdown that dynamically changes the images by the different options as shown in this Fiddle here but the change function does not seem to be working.
I made sure that I am able to get the data from pictureList but the image source did not change successfully as the fiddle.
$('#selectVariant').change(function () {
var sku = $('#selectVariant :selected').val();
var sessionId="<?php echo $sessionId; ?>";
var dataString='sku='+ sku +'&sessionId='+sessionId;
$.ajax({
type:"post",
url: "<?php echo $base_url; ?>ajax-helper/search_variant.php",
data:dataString,
cache:false,
dataType: "JSON",
success: function(data){
var pictureList = {};
//example of my data list
//var pictureList = {'Apple SKU2': "http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png",
//'Pear1': "http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/pears.png"
//};
$.each(data.productVariantImages,function(i, productVariantImages){
pictureList[data.sku] = this.imagePath;
});
console.log(pictureList);
$('.content img').attr({"src":[pictureList[this.value]]});
}
});
return false;
});
However, when I do test it outside the ajax post, it is able to run.
Instance of this is change in ajax success function scope.
In this line $('.content img').attr({"src":[pictureList[this.value]]}); this
is not the instance of selectVariant element.
The usual practice for this is declare a variable that and use that variable in other scope. try the below code.
$('#selectVariant').change(function () {
var sku = $('#selectVariant :selected').val();
var sessionId="<?php echo $sessionId; ?>";
var dataString='sku='+ sku +'&sessionId='+sessionId;
var that = this;
$.ajax({
type:"post",
url: "<?php echo $base_url; ?>ajax-helper/search_variant.php",
data:dataString,
cache:false,
dataType: "JSON",
success: function(data){
var pictureList = {};
//example of my data list
//var pictureList = {'Apple SKU2': "http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png",
//'Pear1': "http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/pears.png"
//};
$.each(data.productVariantImages,function(i, productVariantImages){
pictureList[data.sku] = this.imagePath;
});
console.log(pictureList);
$('.content img').attr({"src":[pictureList[that.value]]});
}
});
return false;
});

Categories

Resources