Search code examples
phpjqueryajaxhttp-post

send post with ajax


hi guys i been trying to send a post value using ajax this is my pages:

I have a page that is the modal modal_image.php with this code:

var image;
function addImage() {
    $.ajax({
        url:'registration.php',
        data:{image:document.getElementById('output').src},
        type:'POST',
        success:function (data){
            if(!data.error){
                document.getElementById('userImage').src=document.getElementById('output').src;
                image=document.getElementById('userImage').src;
                $("#try").text(image);
            }
        }
    });
}

and this my registration.php page:

<p><?php echo $_POST['image'];?></p>
<p id="try"></p>

i have showed u a limit of the code...

when I open the modal and upload the photos the 'p' element with the id=try is working and I can see the image src

but the first p with the post value I see an error

the image that show the error


Solution

  • Consider the following code.

    function addImage(source) {
      $.post('registration.php', {
        image: source
      }, function(data) {
        if (!data.error) {
          $('#userImage').attr("src", source);
          $("#try").text($('#userImage').attr("src"));
        }
      });
    }
    
    addImage($("#output").attr("src"));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <img id="output" src="https://dummyimage.com/200x100/ccc/fff.png&text=TEST" />
    <p id="try"></p>

    You can pass in the URL String that you want to Add into your Function. This way, it can be a bit more dynamic and you now have the data easily available to the whole function.