kalu1
kalu1

Reputation: 53

php, css, javascript: click on image -> change the image -> call function

I'd like to have 4 images. After click on the image, it will change to different image and call function. I already have it and it works, but only separately.

Code for changing image. (I put code only for one image):

<form method="post" action="index.php" name="loginform">
<script>
function prvni(img) 
{
   img.src = "img/green/green_0.jpg";
   document.getElementById("image2").src = "img/red/red_0.jpg";
   document.getElementById("image3").src = "img/red/red_0.jpg";
}
</script>   
<img src="img/red/red_0.jpg" id="image1" onclick=prvni(this) />
</form>

Code for calling function via button (type=submit):

<form method="post" action="index.php" name="loginform">
    <input id="user_drink" class="login_input" type="text" name="user_drink" ?> required /><br>
    <input type="submit"  name="pridat" value="přidat" id="button"/><br>
</form>

and code from different file:

elseif (isset($_POST["pridat"])) {
$this->myfunction();

When I try to change type submit to image, it doesn't work.

Maybe my codes above are not a good way.

Could you help me how to do it (click on image -> change the image -> call function)

Thank you

Upvotes: 1

Views: 700

Answers (2)

kalu1
kalu1

Reputation: 53

Thank you tima

now I'm able to change the image. Unfortunately I don't know how to call function with your code from another file.

Which part from your php code call the function?

Is there something which fulfill IF condition from different php file below?

if (isset($_POST['data'])) {
$this->myfunction();

Basically I need use image as button, but I want to change image after click on. There will be 4 images for 4 options. When I click one of them image will change and via function write value to mySQL. If I click on another one image will change (First clicked image will change back) and to mySQL will write value for this actual image. myfunction() from my previous post do mySQL and it is working, so i don't need help with it. I mentioned it for better understanding of my problem)

Thank you so much, I am really new (two weeks) with php, JS etc. Lukas

Upvotes: 0

tima
tima

Reputation: 1513

The only way you can call a php function from javascript is to use Ajax to send a post or get request after changing the image.

See this CodePen for the client side.

And in your php file:

// read the data
$mydata = $_POST['data'];

// perform actions

// return if needed
header('Content-Type: application/json');
echo json_encode(array('returnData' => 'myOtherData'));

Upvotes: 1

Related Questions