[AJAX] PHP and HTML

rward

Senior Member
Joined
Oct 26, 2007
Messages
865
Everything you need.....

Use the code SBSP provided.
Use your php debugger and set a breakpoint on line 3 of checkinput.php
.
Use developer tools and put a breakpoint in the index.php file in the xmlhttp.onreadystatechange function (the lines with "if (xmlhttp.readyState == 4 && xmlhttp.status == 200)" )

Also put breakpoints on the first lines of each javascript function.

Run the script and as soon as you submit the form you should hit the javascript breakpoint. Step through this and see what happens. When you get to the xmlhttp.send function then your php debugger should kick in as it's sent the info to the php script.
tell the developer tools debugger to continue running, it'll carry on doing "nothing" (waiting around).
Step through the php code and when it returns then your javascript debugger should "magically" wake up again as it's now got something to do - handle the received data.
Check what's in the different variables returned, etc.


Currently the php script is returning a string. You could have it return anything.
Most likely you want it to return a json array of data that you can then work with in your javascript.
 

Thor

Honorary Master
Joined
Jun 5, 2014
Messages
44,236
I want to roll up and cry in a corner somewhere
 

Necropolis

Executive Member
Joined
Feb 26, 2007
Messages
8,401
I want to roll up and cry in a corner somewhere

Thanks for sharing that with us.

Maybe programming isn't for you if you aren't willing to put the effort in to learn how to do something yourself.
 

Thor

Honorary Master
Joined
Jun 5, 2014
Messages
44,236
Thanks for sharing that with us.

Maybe programming isn't for you if you aren't willing to put the effort in to learn how to do something yourself.

a bit fcked up if you ask me,concidering that I am still at it, just said it breaks my soul. It's day 2 of learning so... f0k u
 

Thor

Honorary Master
Joined
Jun 5, 2014
Messages
44,236
If I want to load the result of the php file using Ajax into $html

Can I do it like this:

PHP:
<?php
$html = <<<EOD
<div>SOME HTML <?php echo $var1 </div>
<div>SOME HTML <?php echo $var2 ?></div>
<div>SOME HTML <?php echo $var3 ?></div>
<div>SOME HTML <?php echo $var4 ?></div>
<div>SOME HTML <?php echo $var5 ?></div>
<div>SOME HTML <?php echo $var6 ?></div>
<div>SOME HTML <?php echo $var7 ?></div>
<div>SOME HTML <?php echo $var8 ?></div>
<div>SOME HTML <?php echo $var9 ?></div>
<div>SOME HTML <?php echo $var10 ?></div>
<div>SOME HTML <?php echo $var11 ?></div>
<div>SOME HTML <?php echo $var12 ?></div>
<div>SOME HTML <?php echo $var13 ?></div>
<div>SOME HTML <?php echo $var14 ?></div>
etc etc etc
EOD;

$return = array( 
    'success' => true, 
    'data' => $html 
); 

return json_encode($return);
?>

And then in the Ajax call $html:

HTML:
html(response.data);
 

rward

Senior Member
Joined
Oct 26, 2007
Messages
865
Did you try it?

What happened?

What you have there looks about right, you probably want to have a div with class ajax-data and $('.ajax-data').val(response.data);
 

MagicDude4Eva

Banned
Joined
Apr 2, 2008
Messages
6,479
For the love of all things sacred, use jQuery/Ajax and don't use document.* notation - this is just painful and old-style.

You would probably do something like this - probably missed some brackets

PHP:
	    $.ajax({ 
	        type: "POST", 
	        url: '/myphp file',
	        data: {Stick in anything - i.e. variable1, variable2 etc},
	        dataType: "html",
	        cache: false,
	        async: true,
	        success: function(aResponse) {
	          var response = $.trim(aResponse);
	          
	          $('#MYDIV').html(response)

              // Optional pull out other stuff
	          var mysection1 = $(response).find('#Section1').html();
	          if(mysection1.length > 0) {
	            $('#MYSECTION1').html(refreshSection1HTML);
	          }
	        }
	      });

BTW - I would stick the above into a proper JS file (you do need jquery) - and you will then have access to pretty much everything you like. You would then just bind your button to a click-event (http://api.jquery.com/bind/), calling your function
PHP:
(function ($, document, window) {

	var I_CAN_HAZ_VARIABLES = -1;
	
	function loadStuff() {
		
	    $.ajax({ 
	    .....
	      });
	}
	
}(jQuery, document, window));
 
Last edited:

Darko

Senior Member
Joined
Jul 9, 2008
Messages
627
The php "return" should be an echo, not a return. Don't echo anything else in that page. Use concatenation to append the variable values.

Why are you returning HTML anyway? Since you're already using php, then just use the php to repeat your result set on your html page and print out the rows.
 

rorz0r

Executive Member
Joined
Feb 10, 2006
Messages
7,968
Honestly just get *some* AJAX working from any of the samples above or from pretty much any beginner tutorial. You will see your requirement is not at all unique. Basically just google jQuery/AJAX.

I would maybe just add that binding to the "onBlur" event on your form text fields will get it to trigger when the person "leaves" a field (blur being the opposite of focus). This would probably achieve what you want. onChange will cause a request almost every time a person types a character.
 

IndigoIdentity

Expert Member
Joined
May 10, 2010
Messages
1,964
I can't figure out how to achieve this.

Let me try to help with a simple example. So make a new directory and in it create these 3 files:

Code for index.html

HTML:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Contacts</title>
  </head>
  <body>
    <!-- Form Response -->
    <p id="response" style="display: none;"></p>
    <!-- Form -->
    <form>
      <label for="name">Enter a name:</label><br/>
      <input type="text" id="name" /><br/>
      <label for="number">Enter a number:</label><br/>
      <input type="text" id="number" /><br/>
      <button type="button" id="processForm">Process</button>
    </form>
    <!-- Scripts -->
    <script src="https://code.jquery.com/jquery-1.12.2.js" type="text/javascript"></script>
    <script src="ajax_request.js" type="text/javascript"></script>
  </body>
</html>


Code for ajax_request.js
Code:
$(document).ready(function() {
  // When the button is clicked
  $('#processForm').on( 'click', function () {
    // Hide the response during form processing
    $('#response').hide();
    // Show the response when it exists and enable the button
    // Store the values of val1 and val2
    var contacts = {};
    contacts.name = $('#name').val();
    contacts.number = $('#number').val();
    /*
     * Load JSON-encoded data from the server using a GET HTTP request.
     * (http://api.jquery.com/jquery.getjson)
     * Using the shorthand version:
     */
    var url = 'ajax_response.php?name='+contacts.name+'&number='+contacts.number;
    $.getJSON(url, function(response) {
      console.log(response);
      // Valid response
      if (response.status) {
        $('#response').text(response.desc).css('color','green').show();
      }
      // Invalid response
      else {
        $('#response').text(response.desc).css('color','red').show();
      }
    }).fail(function( jqxhr, textStatus, error ) {
      // It failed - check the url
      var err = textStatus + ", " + error;
      alert( "Request Failed: " + err );
    });
  });
});


Code for ajax_response.php
PHP:
<?php
// The request was valid
if (isset($_GET['name']) && isset($_GET['name'])) {
  // Helps us to return some feedback
  function doResponse($status, $desc) {
    $response['status'] = $status;
    $response['desc'] = $desc;
    echo json_encode($response);
    exit;
  }
  // Lets have a response so open an array for that
  $response = array();
  // For sanity sake a bit of validation in the user input
  $contacts['name'] = htmlspecialchars($_GET['name']);
  $contacts['number'] = htmlspecialchars($_GET['number']);
  if (strlen($contacts['name']) == 0) {
    doResponse(FALSE, 'Name is required');
  } elseif (strlen($contacts['name']) == 0) {
    doResponse(FALSE, 'Number is required');
  }
  // Some random gibberish to represent your server side processing
  $existingContacts = array(
    'Bob'=>'082123',
    'Frank'=>'082321'
  );
  // After checking the dataset, it seems that the value already exists
  if (array_key_exists($contacts['name'], $existingContacts) 
      && in_array($contacts['number'], $existingContacts)) {
    doResponse(FALSE, 'Contact already exists');
  }
  // We got this far so let us call it a success
  else {
    doResponse(TRUE, 'Contact successfully added');
  }
}
// The request was invalid
else {
  // So throw a 500
  header('HTTP/1.1 500 Internal Server Error');
  header('Content-Type: application/json; charset=UTF-8');
  $response['ERROR'] = 'ERROR';
  $response['code'] = 1337;
  die(json_encode($response));
}

So what happens here is when you "submit" the form it will capture the form values and query the PHP for a response.

There is a little bit of validation that takes place, so if you do not enter any input then it will display an error relating to this.

It then goes on to check the user input against existing data to ensure that the input is unique. If that is the case then it will display a success message:

Screenshot from 2016-03-25 00-14-57.png

I tried to comment the code out so that it would make more sense for you to understand what is going on. Hopefully that will get you on the right track in terms of understanding things, if you have any questions about the code I've shown here as an example then feel free to ask ;)
 
Last edited:

Swa

Honorary Master
Joined
May 4, 2012
Messages
31,217
Are you using the right trigger events? I don't know if you're past this stage yet but you can't "submit" the form in the standard way. You have to use the onclick event to submit the fields through the xhttp response and then return false at the end. First decide what your php should return whether it's pre-formatted html, variables that you will use to create it with javascript or javascript itself that will be executed. Decide if you want to use jquery (probably easier for a beginner) or standard javascript functions.

Then remember to also have a fallback to standard forms and a way for your php to differentiate between that and ajax. And please don't use the stupid "#" as an action for your form.
 
Top