Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

Creating Dynamic Success Messages in Laravel from json structure

creating dynamic msg using given json structure
creating dynamic msg using given json structure contain key value pair
Dynamically display message in dropdown
Display different dynamic display message in same modal using append
how to print any json data in blade file

creating dynamic msg using given json structure

Step1: server json response code

   return response()->json([
                            'message' => "task disapprove 
                      successfully", 
                            'success' => true,
                            'prices' => $priceData, 
                            'influencer' =>$request->slug,
                            'publisher' =>$request->user_name,     
          ]);
Enter fullscreen mode Exit fullscreen mode
{
    "message": "Task disapproved successfully",
    "success": true,
    "prices": {
        "face_price": "24",
        "youtube_price": "69"
    },
    "influencer": "sample-influencer",
    "publisher": "sample-publisher"
}
Enter fullscreen mode Exit fullscreen mode

step2: after success get server json data in blade page using jquery
How to append data in h1 tag of popup modal from give json nested array

$.ajax({
            url: 'add_summary', // Replace with the actual route URL
            type: 'POST',
            data: formData,
            success: function(response) {  
            var prices = response.prices;
            var influencer = response.influencer;
            var publisher = response.publisher;   
            $(buttonId).text('Added').attr('disabled', true); 
            console.log('Prices:', prices);
            console.log('Influencer:', influencer);
            console.log('Publisher:', publisher);
            $('#addmycart').modal('show');
            $('#addsmycart').html(`
            <h5 class="text-center" style="margin: 0; color: red;">
                Publisher ${publisher} has successfully added an influencer ${influencer} for Facebook with a rate of $${prices.face_price} per post
                and for YouTube with a rate of $${prices.youtube_price} per post. Please check in the cart.
            </h5>
        `);
Enter fullscreen mode Exit fullscreen mode

step3: popup modal in laravel

<div id="addmycart" class="modal fade" role="dialog">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-header bg-light">
                                    <button type="button" class="close" data-dismiss="modal"> Success Message&times;</button>
                                    <br>                                    
                                </div>
                                <center> <div class="modal-body">
                                    <h5 id="addsmycart" class="text-center" style="margin:0; color:red;"> </h5>
                                </div></center>
                            </div>
                        </div>
                    </div>
Enter fullscreen mode Exit fullscreen mode

Output

Image description

creating dynamic msg using given json structure contain key value pair

Step1: server json response code

    return response()->json([
                        'message' => "task disapprove successfully", 
                        'success' => true,
                        'prices' => $priceData, 
                        'influencer' =>$request->slug,
                        'publisher' =>$request->user_name,  
                    ]);
Enter fullscreen mode Exit fullscreen mode
{
    "message": "Task disapproved successfully",
    "success": true,
    "prices": [
        {"social_site": "face", "price": "60"},
        {"social_site": "youtube", "price": "67"}
      {"social_site":"face","price":"34"}
    ],
    "influencer": "rajesh ",
    "publisher": "rakeshdev"
}
Enter fullscreen mode Exit fullscreen mode

step2: after success get server json data in blade page using jquery

How to append data in h1 tag of popup modal from give json nested array contain key value pair
how to get data from nested json array using for loop

     success: function(data) {
           // Handle the response from the server
           console.log(data);
           var html = '';
           if (data.success) {    
            $('#share-social').modal('hide');
            var prices = data.prices;
        var influencer = data.influencer;
        var publisher = data.publisher; 

        console.log('add prices success click ho rha ha', prices);
        var socialSiteCount;
        if (prices && Array.isArray(prices.prices)) {
    // Calculate the number of social sites
    var socialSiteCount = prices.prices.length;


    console.log('Number of social sites:', socialSiteCount);
        } else {
            console.log('Prices is not an object with a "prices" array or is undefined.');
        }

let htmlCode = ` <h5 class="text-center" style="margin: 10px 0; color: red;">
                Publisher ${publisher} has successfully added an influencer ${influencer} for follwing sites with pricerate given below . Please check in the cart.
            </h5>`;
            for (let i = 0; i < socialSiteCount; i++) {
    const entry = prices.prices[i];
    const socialSite = entry.social_site;
    const price = entry.price;

    const socialSiteText = socialSite === 'face' ? `${socialSite}book` : socialSite;
    htmlCode += `<p class="text-center" style="margin: 2px 0; color: blue;">
        Social Site: ${socialSiteText}, Price: $${price} per post.
    </p>`;
}
            console.log('Influencer:', influencer);
            console.log('Publisher:', publisher);
            console.log('add success success click ho rha ha');
            $('#approve-modal').modal('show');
            $('#approvessmycart').html(`
            ${htmlCode}
               `);

           }
           else 
           {

           }
         },
Enter fullscreen mode Exit fullscreen mode

Image description

Image description
while inspect price:array(3) right click and copy object
we get json structure format

{
    "prices": [
        {
            "social_site": "twitter",
            "price": "60"
        },
        {
            "social_site": "youtube",
            "price": "67"
        },
        {
            "social_site": "face",
            "price": "34"
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

step3: popup modal in laravel

 <div id="approve-modal" class="modal fade" role="dialog">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-header bg-light">
                                    <button type="button" class="close" data-dismiss="modal"> Message&times;</button>
                                    <br>                                    
                                </div>
                                <center> <div class="modal-body">
                                    <h5 id="approvessmycart" class="text-center" style="margin:0; color:red;"></h5>
                                </div></center>
                            </div>
                        </div>
                    </div>
Enter fullscreen mode Exit fullscreen mode

Output

Image description

Dynamically display message in dropdown

// JavaScript
if (data.success) {
  $('#share-social').modal('hide');
  var prices = data.prices;
  var influencer = data.influencer;
  var publisher = data.publisher;

  console.log('add prices success click ho rha ha', prices);
  var socialSiteCount;

  if (prices && Array.isArray(prices.prices)) {
    // Calculate the number of social sites
    socialSiteCount = prices.prices.length;

    console.log('Number of social sites:', socialSiteCount);

    // Get the dropdown element
    var dropdown = document.getElementById("socialSiteDropdown");

    // Clear existing options
    dropdown.innerHTML = '<option value="" disabled selected>Select a social site</option>';

    // Loop through the social sites and add options to the dropdown
    for (let i = 0; i < socialSiteCount; i++) {
      const entry = prices.prices[i];
      const socialSite = entry.social_site;
      const socialSiteText = socialSite === 'face' ? `${socialSite}book` : socialSite;

      // Create an option element
      var option = document.createElement("option");
      option.value = socialSite;
      option.text = socialSiteText;

      // Append the option to the dropdown
      dropdown.add(option);
    }
  } else {
    console.log('Prices is not an object with a "prices" array or is undefined.');
  }

  // ... Rest of your code
}
Enter fullscreen mode Exit fullscreen mode

Display different dynamic display message in same modal using append

<div id="cannotupdate" class="modal fade" role="dialog">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-header bg-light">
                                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                                    <br>                                    
                                </div>
                                <center> <div class="modal-body">
                                    <h5 id="updateno" class="text-center" style="margin:0; color:red;"> </h5>
                                </div></center>
                            </div>
                        </div>
                    </div>
Enter fullscreen mode Exit fullscreen mode
        let htmlCode = ` <h5 class="text-center" style="margin: 10px 0; color: red;">
             please put correct url in ${platform} field.
            </h5>`;            

    $('#cannotupdate').modal('show');
    $('#updateno').html(htmlCode);
Enter fullscreen mode Exit fullscreen mode
for (var platform in socialUrls) {
    if (socialUrls.hasOwnProperty(platform)) {
        if (!validateSocialUrl(socialUrls[platform], platform)) {

            let htmlCode = ` <h5 class="text-center" style="margin: 10px 0; color: red;">
             please put correct url in ${platform} field.
            </h5>`;            

    $('#cannotupdate').modal('show');
    $('#updateno').html(htmlCode);
            // If validation fails for any platform, set isValid to false
            isValid = false;
            break; // No need to continue checking other platforms
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
let htmlCode = ` <h5 class="text-center" style="margin: 10px 0; color: red;">
             Cannot update data facebook price is assigned .
            </h5>`;           
    $('#cannotupdate').modal('show');
    $('#updateno').html(htmlCode);
Enter fullscreen mode Exit fullscreen mode
if (!url) {
for (var i = 0; i < socialPlatforms.length; i++) {
    var platformObj = socialPlatforms[i];
    var platforms = platformObj.platform;
    var elementId = platformObj.elementId;
    var price = $(elementId).text();   
        if (platform === platforms && containsDigits(price)) {
            console.log("data comes")
            let htmlCode = ` <h5 class="text-center" style="margin: 10px 0; color: red;">
             Cannot update data facebook price is assigned .
            </h5>`;           
    $('#cannotupdate').modal('show');
    $('#updateno').html(htmlCode);
    return false;
        }          
    }
    return true; 
}
Enter fullscreen mode Exit fullscreen mode

how to print any json data in blade file

my json format {
    "person1": {
        "name": "Alice",
        "age": 30
    },
    "person2": {
        "name": "Bob",
        "age": 25
    }
}
Enter fullscreen mode Exit fullscreen mode

solution

// In your controller
$data = json_decode('{
    "person1": {
        "name": "Alice",
        "age": 30
    },
    "person2": {
        "name": "Bob",
        "age": 25
    }
}', true);


return view('your.blade.view', ['jsonData' => $data]);
Enter fullscreen mode Exit fullscreen mode

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Display JSON Data</title>
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>

<div id="jsonDataContainer"></div>

<script>
    $(document).ready(function () {
        // Get the JSON data passed from the controller
        var jsonData = @json($jsonData);

        // Loop through the JSON data and display it
        $.each(jsonData, function (key, value) {
            $('#jsonDataContainer').append('<p><strong>' + key + '</strong>: ' + value.name + ' - Age: ' + value.age + '</p>');
        });
    });
</script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

=================or=================

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Display JSON Data</title>
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>

<div id="jsonDataContainer">
    @foreach($jsonData as $key => $person)
        <div>
            <strong>Name:</strong> {{ $person['name'] }}<br>
            <strong>Age:</strong> {{ $person['age'] }}
        </div>
    @endforeach
</div>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Attractive style dynamic success msg

button

 cardContent += '<button class="btn btn-danger tasks-approve" data-id="' + item.id + '"';
Enter fullscreen mode Exit fullscreen mode

Image description

server side

 public function tasksapprove(Request $request)
           {
            Log::info($request);
            $input = $request->all();
            Log::info(' sharemysuggestion via AJAX:', $request->all());      
         $id=$request->id;        
      $shareingdata= DB::connection('payments')->table("sharedatas")->where('id',$id)->first();
      $publisher_name=$shareingdata->user_name;
      $influencer_name=$shareingdata->pay_influencer_name;
      $sharemytask= DB::connection('payments')->table("sharedatas")->where('id',$id)->update(array('publisher_status' =>'Approve','publisher_date' => now()));
                       return response()->json([
                           'message' => "task disapprove successfully", 
                           'success' => "task disapprove successfully", 
                           'publisher' => $publisher_name, 
                           'influencer' => $influencer_name,
             ]);

        }
Enter fullscreen mode Exit fullscreen mode

After success in ajax route

 success: function(data) {
          var sharedata = data.sharedata;                    
                console.log('sharedata:', sharedata); 
                var influencer_name = data.influencer;             
              var publisher_name = data.publisher;

              $('#approve-modal').modal('show'); 
              $('#approvessmycart').empty();

              $('#approvessmycart').append('<div style="color: black;font-family: Arial, sans-serif; margin-left: 10px;  padding: 10px; border-radius: 5px;">' +
                                '<b>publisher ' + publisher_name + '</b> approved <b>influencer ' + influencer_name + '</b> successfully' +
                '</div>');

                console.log('view-button ka data aata hain');              

        },
Enter fullscreen mode Exit fullscreen mode
<div id="approve-modal" class="modal fade" role="dialog">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-header" style="background-color:#045f11;">
                                    <button type="button" style="color:white;" class="close"  data-dismiss="modal"> &times;</button>
                                    <br>                                    
                                </div>
                                <center> <div class="modal-body" style="background-color:#95de954f;">
                                <div id="success-message" class="success-message">
                        <i class="fas fa-check-circle fa-3x" style="color: green;"></i>
                        <h5  class="text-center" style="margin-top: 10px; color: green;">Approved</h5>
                        <h5 id="approvessmycart" class="text-center" style="margin-top: 10px; color: green;"></h5>
                    </div>
                                </div></center>
                            </div>
                        </div>
                    </div>
Enter fullscreen mode Exit fullscreen mode

Image description

     <div id="modification-modal" class="modal fade" role="dialog">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-header" style="background-color:#d1e50a;">
                                    <button type="button" style="color:black;" class="close"  data-dismiss="modal"> &times;</button>
                                    <br>                                    
                                </div>
                                <center> <div class="modal-body" style="background-color:#dade95ad;">
                                <div id="success-message" class="success-message">
                                <i class="fas fa-edit fa-3x" style="color: orange;"></i>
                        <h5  class="text-center" style="margin-top: 10px; color: orange;">Modification</h5>
                        <h5 id="modificationmsg" class="text-center" style="margin-top: 10px; color: green;"></h5>
                    </div>
                                </div></center>
                            </div>
                        </div>
                    </div>
Enter fullscreen mode Exit fullscreen mode

Image description

Summary

creating dynamic msg using given json structure
How to append data in h1 tag of popup modal from give json nested array
creating dynamic msg using given json structure contain key value pair
How to append data in h1 tag of popup modal from give json nested array contain key value pair
how to get data from nested json array using for loop
calculates the number of social sites by getting the length of the prices array.
loop iterates through each entry in the prices array
For each entry, it extracts social_site and price
Dynamically display message in dropdown
get value of dropdown using id
calculates the number of social sites by getting the length of the prices array to apply in for loop
For each entry, it extracts social_site and price
append social_site and price in dropdown option and value
Display different dynamic display message in same modal using append

Top comments (0)