skip to Main Content

I have 2 divs: one is a data from php variable:

<div id="data"><?php echo "$strstr"?></div>

Second is the div for ajax request:

<div id="divButton">[CLICK ME]</div>

Here is js code:

$("#divButton").on("click", function() { 
    $.ajax({ 
        type: "POST",
        url: "test.php",
        dataType: "json",
        data: {simpledata:12345},
        success : function(data) { 
        if (data.code == 200) 
            console.log("Success!");
        else console.log("Error!");
        }
});

And finally php code:

<?php 
$strstr = "A"; 
if ($_POST) { 
    $strstr = $strstr."A"; 
}
?>

As you can see I need dynamic update of first div, by clicking on second div.
What am I doing wrong?

2

Answers


  1. HTML code Should be

    <div id="data"><?php echo "$strstr"?></div>
    
    <div id="divButton">[CLICK ME]</div>
    

    Ajax Call Code

    $("#divButton").on("click", function() { 
        $.ajax({ 
            type: "POST",
            url: "test.php",
            data: {simpledata:12345},
            success : function(data) { 
                  $("#data").html(data);
            },
            error : function() { 
                  console.log("Error!");
            }
    });
    

    test.php Code Should be

    <?php 
    $strstr = "A"; 
    if ($_POST) { 
        $strstr = $strstr."A"; 
    }
    echo $strstr;
    //It is advisable that do not close php tag 
    
    Login or Signup to reply.
  2. You can’t change the value of $strstr variable by just updating the value of it in you if condition. You need to make an action in your ajax when return is success. Like this

    $("#divButton").on("click", function() { 
        $.ajax({ 
            type: "POST",
            url: "test.php",
            dataType: "json",
            data: {simpledata:12345},
            success : function(data) { 
                 $('#data').text(data)
            }
        });
    });
    

    And in your php if condition you must return a string like this

    <?php 
      $strstr = "A"; 
      if ($_POST) { 
        $strstr = $strstr."A"; 
    
         echo json_encode($strstr );
      }
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search