javascript - $_POST without refreshing -
i got associative array use generate images. these images want select 2 or more pictures 1 random. code works got 2 questions:
how can improve code? , how can use json or else site doesn't refresh after submit?
<style> .check { opacity: 0.5; color: #996; } </style> <script> function getrandomint( min, max ) { return math.floor( math.random() * (max - min + 1) ) + min; } function debug() { console.log( $( "img.check" )[0] ); } $( document ).ready( function() { $( "form" ).submit( function() { var images = $( "img.check" ); if( images.length > 0 ) { $( "input[name=images]" ).attr( "value", $( images[getrandomint( 0, images.length )] ).data( "id" ) ); return true; } else { alert( 'kein bild ausgewählt.' ); return false; } } ); $( 'form img' ).click( function() { $( ).toggleclass( 'check' ); } ); } ); </script> </head> <body> <?php $random = [ 'key1' => 'https://static.pexels.com/photos/4952/sky-beach-vacation-summer.jpeg', 'key2' => 'https://static.pexels.com/photos/1852/dawn-landscape-mountains-nature.jpg', 'key3' => 'https://static.pexels.com/photos/33109/fall-autumn-red-season.jpg', 'key4' => 'https://static.pexels.com/photos/12567/photo-1444703686981-a3abbc4d4fe3.jpeg', 'key5' => 'https://static.pexels.com/photos/2757/books-magazines-building-school.jpg', ]; ?> <form method="post"> <input type="hidden" name="images"> <?php foreach ($random $key => $val) { echo '<h1>$key</h1>'; echo '<img src="'.$val.'" width="100px" height="100px" data-id="'.$key.'"">'; } ?> <button type="submit" name="submit" class="btn btn-default">submit</button> </form> <?php if (isset($_post['images'])) { echo '<img src="' . $random[$_post['images']] . '" />'; } ?>
you can use ajax returns associate array json format. example
use jquery this
$.post('yourphpscript.php', function(data) { data // associated array }, 'json');
Comments
Post a Comment