-1

how do I use the value of console.log to change an image without reloading a page image in my css dynamically?

      function reply_click(clicked_id){
    $(function() {
        $.ajaxSetup({
           headers: {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
           }
        });
        console.log('attached');
        $('#openButton').on('click', function(data) {
            console.log('clicked');
            $.ajax({
              type: "POST",
              url: "/MYUrl",
                data: { _token: $('meta[name="csrf-token"]').attr('content') }
            })
           .done(function(data){
                console.log(data);
            })
            .fail(function(data){
                console.log('Error:', data);
            });
        });
    });
}

I put the image I want to update from my blade.php

    <div class="inputbutton">
    <span class="text">TEXT</span>
    <input type="submit" class="btTxt submit" value=""  id="TEXT" onclick="reply_click(this.id)">
    </div>

my css file

div.inputbutton input {
background: url('/img/myimg.png') no-repeat;
cursor: pointer;
width: 100px;
height: 130px;
border: none;
background-size: 100%;
}

1 Answers1

0

You need a way of identifying which image you want to change, e.g. with an id tag. If there was <img id="image1" src="old.jpg"> then you would add the following line of code.

  .done(function(data){
            console.log(data);
            $('#image1').attr('src',data);
    })

EDIT: You need to be sure that data returns a valid image URI, which you could do either by either a) using jquery-validate to check the syntax is correct or b) checking the file actually exists e.g. by making a test AJAX call to the new image address.

EDIT 2: Now you’ve shown you’re actually trying to change a bg image it should be:

$('.inputbutton input').css("background-image", "url("+data+")");
lufc
  • 1,965
  • 2
  • 15
  • 19
  • Can you paste the console.log result for data and the image tag you're trying to update? – lufc May 07 '18 at 01:59
  • I don't see the image which you're trying to update. Where is it? Also the URL being returned by data is relative so you need to check it's valid for the page from which you're calling it. If using Laravel blade you could use the `$('#image1').attr('src','{{url('/')}}'+data);` – lufc May 07 '18 at 02:13
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/170506/discussion-between-theflash-and-user1491032). –  May 07 '18 at 02:34
  • error: Uncaught ReferenceError: reply_click is not defined      at HTMLInputElement.onclick –  May 07 '18 at 13:41
  • This is a new question. – lufc May 07 '18 at 14:34