简体   繁体   中英

How to sort PHP loop without page refresh using JQUERY

I am trying to send variables using ajax to php page so when I click a button, the sent variable will update to the page without refreshing it.

I have a button called #toshow and when clicked, it will send ?show=okay as a post.

$('#toshow' ).click( function( e ) {
  $.post('?show=okay')
  .done(function(data) {
  });
});

and on my php

if(isset($_POST['show']) && $_POST['show']) {
  echo $_POST['show'];
}

I click the button, but it doesn't show the text 'okay'. What else do I need to add to make this work?

Thank you!

Whatever you print with echo in PHP wil be available (if no error occurs) in the JavaScript data variable in the callback of .done() function. So you need to implement this callback to display the returned text where you need it to be displayed.

Example:

.done(function(data) {
    document.write(data);
});

Also, the way you send the show parameter to the server (as a part of URL) is a GET method, not POST. If you want to use the POST method, pass the data as the second argument of the $.post() function:

$.post('', {
    show: 'okay'
})
    .done(...)

You are sending "show" variable in query part of URL, then, you must retrieve it from $_GET global variable ... check ...

$('#toshow' ).click( function( e ) {
  $.post('', {"show": "okay"})
  .done(function(data) {
      console.log(data);
  });
});

https://api.jquery.com/jquery.post/#jQuery-post-url-data-success-dataType

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM