Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax not working properly when I tried to call it on same page again

I have a PHP page which has two sections (top and bottom). The top section has a table where I have options to Edit the data.

Once the Edit button is pressed, the content is loaded at the bottom of page and the user can change the data.

Here is part of my PHP page:

            <div id="product_entry_<?php echo $id?>" class="product_entry_<?php echo $id?>">
                <tr>
                    <td><font size=2px><?php echo $date?></font></td>
                    <td><font size=2px><?php echo $ProductName?></font></td>
                    <td><font size=2px><?php echo $Category.' / '.$SubCategory?></font></td>
                    <td><font size=2px><?php echo $MRP.' / '.$Price?></font></td>
                    <td><button type="submit" class="btn btn-primary btn-xs" style="padding:2px 2px;font-size: 9px;line-height: 10px;" onClick="DirectPromoteSubmit(<?php echo $id?>)">Promote</button></td>
                    <td><button type="submit" class="btn btn-primary btn-xs" style="padding:2px 2px;font-size: 9px;line-height: 10px;" onClick="RePromoteSubmit(<?php echo $id?>)">Edit</button></td>
                    <td><button type="submit" class="btn btn-primary btn-xs" style="padding:2px 2px;font-size: 9px;line-height: 10px;" onClick="DelPromoteSubmit(<?php echo $id?>)">X</button></td>
                </tr>
            </div>

            <!-- page where data is loaded -->
            <div class="box box-warning" id="RePromoteReplace">
             ....some html content here...
            </div> 

Here is my Javascript:

            function RePromoteSubmit(id){
                //alert('got into Edit Promotions');
                var dataString = "id="+ id;
                alert(dataString);
                if(dataString=='')
                {
                    alert('Some Problem Occurred, Please try Again');
                }
                else
                {
                //alert('into post');
                $.ajax({
                    type: "POST",
                    url: "SellerPanel/post_repromote.php",
                    data: dataString,
                    cache: false,
                    success: function(html){
                        //$("#tweet").val('');
                        //$("#preview").hide();
                        $("#RePromoteReplace").replaceWith(html);
                        alert('Product Successfully Loaded!!! Edit(Optional) & Click Promote Button in bottom section')
                    }
                    });
                }return false;
                } 

Here is my PHP page which loads the bottom section - post_repromote.php:

            <?php
            include("../dbconnection.php");
            include("session.php");
            if(!isset($_SESSION))
            {
                session_start();
            }

            $id=$_POST['id'];

            $query1=mysqli_query($con,"select promotiondata from sellerpromotions where id=$id");
            while($row=mysqli_fetch_array($query1))
                {
                .....some code here.....
                }
            ?>
                        <div class="box box-warning">
                            <div class="box-header">
                            <h3 class="box-title">Fill Product Details</h3>
                            </div><!-- /.box-header -->
                            <div class="box-body">

                        <!-- <form role="form " name="PromoteForm"> -->
                        <div>
                                <!-- text input -->
                            <table class="table">
                                ....some data here from query..
                            </table>        

                            <div class="box-header with-border">
                                        <h3 class="box-title">Upload your Product Image</h3>
                            </div><!-- /.box-header -->
                            <div class="box-body no-padding">
                                <div id='preview'>
                                    <?php if ($uploadid){ ?>
                                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src=<?php echo "SellerPanel/uploads/".$imagename?> id="<?php echo $uploadid?>" alt="User Image" class='preview' style='width:340px;height:200px;border-color:black'/>
                                    <?php } 
                                    ?>
                                </div>    
                                <?php 

                                    include ("index_photo.php");

                                ?>

                                <!-- <span class="users-list-date">Yesterday</span> -->

                            </div><!-- /.box-body -->
                            <div class="box-footer">
                                <button type="submit" class="btn btn-primary" onClick="PromoteSubmit()">Promote</button>
                            </div>
                    </div>
                            </div><!-- /.box-body -->
                        </div><!-- /.box -->
            <?php }
            ?>

The problem I'am facing:

  • I'am able to load the data when I press the Edit button first.
  • When I press it again, I'm not able to load the new data unless I refresh the page and click the Edit button again.

I tried to read the id in JS and printed it, I found that id is being passed correctly.

Any help would be very much appreciated.

Thanks in advance!

JS after using solution:

            function RePromoteSubmit(id){
            //alert('got into Edit Promotions');
            var dataString = "id="+ id;
            alert(dataString);
            function getRandomInt() {
                return Math.floor(Math.random() * Math.pow(10,6));
            }
            //var url = "SellerPanel/post_repromote.php?"+getRandomInt();
            //alert ("url is: "+ url);
            if(dataString=='')
            {
                alert('Some Problem Occurred, Please try Again');
            }
            else
            {
            //alert('into post');
            $.ajax({
                type: "POST",
                url: "SellerPanel/post_repromote.php?rnd="+getRandomInt();
                data: dataString,
                cache: false,
                success: function(html){
                    //$("#tweet").val('');
                    //$("#preview").hide();
                    $("#RePromoteReplace").replaceWith(html);
                    alert('Product Successfully Loaded!!! Edit(Optional) & Click Promote Button in bottom section')
                }
                });
            }return false;
            }
like image 581
Amandeep Singh Avatar asked Apr 21 '15 15:04

Amandeep Singh


People also ask

How do I know if AJAX code is working?

You need to attach . ajaxStop() to the document to detect when all AJAX requests get completed. Use global: false option in the AJAX requests if you don't want to detect by . ajaxStop() .

What happens when one AJAX call is still running and you send an another AJAX call before the data of first AJAX call comes back?

Since Ajax calls are asynchronous, the application will not 'pause' until an ajax call is complete, and simply start the next call immediately. JQuery offers a handler that is called when the call is successful, and another one if an error occurs during the call.

What does an AJAX call return?

ajax() (and various ajax shortcut methods) returns a jqXHR object, which is a superset of the browser's native XMLHttpRequest object and implements inter alia the Promise interface.


2 Answers

Try changing your callback to use .html() instead of replaceWith(): (in your original code)

 success: function(html){
       //$("#tweet").val('');
       //$("#preview").hide();
         $("#RePromoteReplace").html(html);
         alert('Product Successfully Loaded!!! Edit(Optional) & Click Promote Button in bottom section')
  }

I also recommend changing your selector to a class instead of an ID, you can do this by just adding an extra class in your HTML:

<div class="box box-warning promoReplace" id="RePromoteReplace">

and then updating the selector in your success callback:

$(".promoReplace").html(html);

Sidenote: For debugging, its usually easier to use console.log() instead of alert() (when using ajax, you usually would have the console open anyway)

like image 59
Michael Doye Avatar answered Oct 12 '22 23:10

Michael Doye


Your AJAX response is getting cached by the browser due to some server setting or page header. Easiest way to disable this is to append some randomly generated parameter to your url every time you send a request.

The function getRandomInt will generate a 6 digit random number. If you want to have more/less digits, change the second argument passed to Math.pow.

function getRandomInt() {
      return Math.floor(Math.random() * Math.pow(10,6));
}
//then, inside your ajax function, use:
    url: "SellerPanel/post_repromote.php?rnd="+getRandomInt(),
like image 35
Sidd Avatar answered Oct 12 '22 23:10

Sidd