4

I have HTML checkbox and I'm trying to check it using the script I received as an ajax response. Here is my HTML:

<form class="form-vertical sms-settings-form">
    <div class="form-group">
        <div data-toggle="tooltip" title="SMS to the customer at the time of sale." class="form-group opt-transport">
               <label for="sale-sms">Sale SMS</label>
               <input type="checkbox" id="sale-sms" data-toggle="toggle" data-on="Send" data-off="Don't Sent">
         </div>
        <textarea data-toggle="tooltip" class="form-control" id="sale-sms-content"></textarea>
    </div>

    <button type="button" class="btn btn-success sms-settings-btn">Save Settings</button>
</form>

Here is my AJAX request.

$(document).ready(function(){
    $.post("ajax-req-handler.php", {key: "load-saved-settings"}, function(data){ $(".exec-ajax-script").html(data); });
});

Here is my ajax-req-handler.php

$sql = "SELECT * FROM settings";
$result = $conn->query($sql);
if(num_rows($result)>0){
    while($row=$result->fetch_assoc()){
        $id = $row['id'];
        $setting_name = $row['name'];
        if($id == 1 && $setting_name == 'sale-sms') $sms_content = $row['value'];
        if($id == 2 && $setting_name == 'send-sms') $send_sms = $row['value'];

    }
} ?>
<script type="text/javascript">
    $(document).ready(function(){
        $(".sms-settings-form #sale-sms").prop(<?php echo ($send_sms == 1) ? "'checked', 'checked'" : ""; ?>);
        $(".sms-settings-form textarea").val("<?php echo $sms_content; ?>");
    });

</script> <?php

And Here is the code that I'm getting as AJAX resopnse

<script type="text/javascript">
    $(document).ready(function(){
        $(".sms-settings-form #sale-sms").prop('checked', 'checked');
        $(".sms-settings-form textarea").val("Hello [name], Your mobile number is [mobile]. your total amount is Rs. [total] out of which you paid Rs. [paid] and your due amount is [due] for the bill number # [bill] on [date] ");
    });

</script> 

The response seems Ok but still, it's not setting the value of my checkbox to checked. I tried copying the response and pasted in my 1st file (file where checkbox is defined and ajax request is initiated). It's working there. The problem is only with ajax response

9
  • Note that ".sms-settings-form #sale-sms" is redundant if your HTML is valid - IDs are unique, so you can just do "#sale-sms". Commented Apr 2, 2018 at 6:23
  • maybe the document.ready will not trigger since this is an ajax request Commented Apr 2, 2018 at 6:25
  • @CertainPerformance I tried removing the class .sms-settings-form but this didn't work Commented Apr 2, 2018 at 6:27
  • @zainulabdeen then your HTML is invalid. Make sure there is only ever exactly one element matching a particular ID string in a document. Commented Apr 2, 2018 at 6:28
  • @Shwrk I already tried removing document.ready from my ajax response but the problem remains Commented Apr 2, 2018 at 6:29

3 Answers 3

1

Untested, but put all of your code in Javascript instead of injecting it into the HTML dom.

$.ajax( {
  url: 'ajax-req-handler.php',
  data: { key: 'load-saved-settings' },
  dataType: 'json'
} ).done( function( data ) {

  if( data.send_sms === 1 ) {
    $(".sms-settings-form #sale-sms").prop('checked', true);
  }

  $(".sms-settings-form textarea").val( data.textarea );

} );

And for PHP; instead do.

$sql = "SELECT * FROM settings";
$result = $conn->query($sql);
if(num_rows($result)>0){
  while($row=$result->fetch_assoc()){
      $id = $row['id'];
      $setting_name = $row['name'];
      if($id == 1 && $setting_name == 'sale-sms') $sms_content = $row['value'];
      if($id == 2 && $setting_name == 'send-sms') $send_sms = $row['value'];

  }
}

echo json_encode( array(
  'send_sms' => $send_sms,
  'textarea' => $sms_content
) );
Sign up to request clarification or add additional context in comments.

4 Comments

Nice. this improved my code. but unfortunately didn't work.
Thank you for putting your efforts. but I already tried prop('checked', true);
Hmm, I just tested the code I gave you and it works flawlessly. What version of jQuery are you using?
Your code is okay. I finally detected where the problem is. There is something wrong with my code. Now, I'm Going to answer my own question
1

The problem Here is not that the script is not adding checked attribute to the <input type='checkbox'>. script is working as expected and adding checked attribute. The problem is it's not just a checkbox instead it's toggle switch where <input type='checkbox'> is set to display: none by default and also it adds and remove some classes to it's self defined div with class='toggle' whenever clicked, to show whether the switch is On or Off. So, doing this $(".sms-settings-form #sale-sms").attr('checked', true); is not enough because this will only check the checkbox but it will not effect the user interface, The toggle switch will still appear to be 'Off' even though it's not. To effect the UI we need to add and remove some classes from .toggle Here is the code that will work:

$(".sms-settings-form #sale-sms").attr('checked', true);
$(".sms-settings-form textarea").val("Hello [name], Your mobile number is [mobile]. your total amount is Rs. [total] out of which you paid Rs. [paid] and your due amount is [due] for the bill number # [bill] on [date] ");
$(".toggle").addClass('btn-primary');
$(".toggle").removeClass('btn-default');
$(".toggle").removeClass('off');

1 Comment

Yes, This is the solution and it is working now. The reason why my own answer is not accepted is that the StackOverflow allows you to accept your answer after 2 days.
0

I think there is problem with ajax-req-handler.php

You have while loop, and must be processing multiple records. If you are getting multiple records, then document ready section written in jquery will execute according to last record in the data set.

Please provide sample data, to review it accordingly.

1 Comment

But there's nothing wrong with the script I'm getting as ajax response.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.