Adding AJAX to a working PHP form - php

I have a working PHP registration form that goes through $_POST[] requests to check user inputs.
Username length (3-20)
Username availability
Username /^[A-Za-z0-9_]+$/
etc.
Rather than have it take you to a whole new page to display errors, I want a live request to call for the errors from register.php so they will appear in a div on the registration.
<div id="errors">" . $usernameErrors . "</div>
I've been trying to read up on AJAX but have noticed most codes involve utilizing $_GET[].
What will I have to do to get my current forms integrated with AJAX?
My Current Basic Registration Form Logic:
<form method="post" action="register.php">
<input type="text" name="username" id="username" required />
$usernameErrors
</form>
And register.php contains all of the checks already.

If you're using jQuery, it's pretty simple.
<script type='text/javascript'>
$.post('/register.php',
{username: $('#username').val()
// insert values of other fields here
},
function(response) {
// update your div with errors
$('#errors').html(response);
})
</script>
You should invoke this code, for example, when user changes username in registration form. It will happen in background and update page asynchronously.
Your register.php script should, in this case, emit only errors, not the whole page, or you will see unexpected results. :-)

In order to simplify ajax, you can use jQuery (a very powerful JS lib).
Add jquery***.js to your project and refer it on your page:
<< script type="text/javascript" src="#js/jquery-ui-1.8.16.custom.min.js" />
Then, you create the javascript function that will make the ajax call.
On the ajax call, you specify the php file to call and the function to handle the return of php(callback). On this callback function, you add the error message to body.
function verifyForm(){
$.ajax({
type: "POST",
url: "register.php",
data: "username=NAME_GOT_FROM_FORM_&location=Boston"
}).done(function( returned ) { //the callback
$('#errors').html(returned); // add the string returned to div id=errors
});
}

So, the crux of the problem as you're asking it seems to be that you're (correctly) using a POST request on your register form, but your tutorials all want to use GET. Here's a discussion about the difference between the two methods:
http://thinkvitamin.com/code/the-definitive-guide-to-get-vs-post/
If you're actually registering the user with AJAX (rather than just validating) you should be submitting the AJAX request as a POST. If you're using jQuery, the answer has already been given. If you're not using jQuery, then look for the XMLHttpRequest object in your tutorial, and where its "open" method is called (reference here: http://www.w3.org/TR/XMLHttpRequest/). The first parameter of that function is a request method--change it to "post" rather than "get", and the request will be treated like a POST, which register.php expects.
That being said, it sounds like you just want AJAX to validate the form. In that case, GET is the correct verb to use--all you want to do with AJAX is check data against the database, not actually make a change to data. I would suggest that you actually write a new PHP script like validate_registration.php that will perform only the validation logic in register.php, and then return a JSON array of errors (which would be empty if no errors occurred). You can activate/deactivate your form submit button based on that return value, and let the user submit the form just like your old workflow if everything is okay.
The tl;dr here is that you should read up on what makes $_GET and $_POST different, and then write an AJAX-specific validation script so that you're separating the data-retrieval part of your process from the data-insertion part. Once you understand the difference, the rest should follow.

Related

Wordpress search results in modal

I am complete php/js newbie and i got stuck on something that i cant figure out.
I have page at www.test.com/page with a search form that calls www.test.com/results like this:
<form method="post" action="https://www.test.com/results">
<input type="text" placeholder="Enter URL:" required="">
<button>Search</button>
</form>
Form gets URL that the user typed in, passes it to /results, the line ($url = $_POST['url'];) is where it is analyzed and results are displayed.
But, i would want the search results to open in (bootstrap) modal instead of new page. I know this can be done with AJAX but i am complete newbie and am looking for most dirty simple solution that would make it work.
Again, sorry if this is too "newbie" type of question, i am still learning.
Yes, you can use jQuery and AJAX to control the form submit. So something akin to the code example below should do the trick:
$('#myForm').on('submit', function(event) {
$.post('https://www.test.com/results', { URL: "some_url.com" }, function(data) {
// Render the results onto your modal anyway you want with data
// retrieved from server here
$("#my-modal-object").html(data);
}).error(function() {
// Handle the event when the call to "/results" fails
alert("Yikes! Call to /results failed!");
});
// Prevents default browser behaviour which submits the form
// then routes to another page, if specified
event.preventDefault();
});
Short explanation:
We attached a "submit" event listener to your form object and performed a POST AJAX request to your server endpoint /results. Server passes back the processed search results into the callback function of $.post and renders it onto your modal object. You may also change the 2nd argument of $.post, i.e. { URL: "some_url.com" } to whatever data object you want to pass to your server.
This should help you get started with rendering your search results onto your modal element instead of navigating to a new page.

Using AJAX to POST data to PHP database, then refresh

Currently I have a button:
<ul>
<li><button onclick="display('1')">1</button></li>
<li><button onclick="display('2')">2</button></li>
<li><button onclick="display('3')">3</button></li>
</ul>
That when pressed, calls a javascript function, and displays PHP based on which button is pressed using AJAX. I figured this out all on my own. The AJAX gets a PHP file with a postgres query that outputs a table of data to a div.
Now I want to be able to add, via form, new data and have it refresh (without reloading the page, yannknow?). I've tried a couple of things, and have hit roadblocks every time.
My initial idea was to have the form submit the data using a javascript function and AJAX, then call my "display()" function after the query to reload the content. I just can't figure it out using GoogleFu.
Based on my current idea, I'd like help with the following:
How do I pass the form data to a javascript function.
How do I use POST to pass that data to PHP using AJAX?
I'm super new to javascript and AJAX. I've looked into jquery as it seems like that's the way to go, but I can't figure it out. If there's a better way to do this, I'm open to suggestions. Please forgive any misuse of nomenclature.
EDIT: Once I solve this problem..., I'll have all the tools needed to finish the project preliminarily.
This example is copied directly from the jQuery API docs for $.post. When in doubt, first place to look is in the API
http://api.jquery.com/jQuery.post/
Example: send form data using ajax requests
$.post("test.php", $("#testform").serialize(), function(data){
/* success- do something with returned data*/
});
Now extend the concept further and wrap the post in a submit handler for the form
$("#testform").submit(function(){
/* code from above, changing form selector to "this" */
$.post("test.php", $(this).serialize(), function(data){
/* success- do something with returned data*/
});
/* prevent browser default submit*/
return false;
})
Refer to jQuery.post method. It does what you want (sends AJAX request with POST data).
To grab values from inputs, use val() method for nodes that have value (textarea, input, .. )

Ajax Reading from a Database

I'm developing a website/database solution which gives the administrator the option to sign into the webpage and perform actions on the database.
Currently they can add/delete/run pre-defined queries, however to 'edit' records in a table, I would like them to specify the primary key (ID) and then have ajax read in the values associated with that record and allow them to be changed.
What's the best way to go about this?
as stratton suggested you have to use jquery/html on frontend and php/mysql on backend that will have the logic to handle the data you send and retrieve result that will be sent back to the user.
ex.
have a form that will send the id to search:
<form>
<input type="text" id="data" name="data"/>
<--send button-->
</form>
I suggest then to use jquery to send the form via ajax like this:
$(sendbutton).click(function(e){
e.preventDefault();
s.ajax({
url: 'urlofyouphppage',
type: 'post',
data : {data: $("#data").val(), action: 'search_thing'}
success: function(data){
//the response from the php page to insert somewhere.
//beware that if you use json you will have to decode via parseJSON.
}
});
});
On you php side you will have to parse the post and then perform the action
<?php
if($_POST['action'] == 'search_thing'){
$id = $_POST['data'];
//query for searching
//format the result data
echo $result; //or json_encode($result); if you want to use json
}
?>
This way you can create multiple logic step by setting each time a different action, and the anwer can be full html code that contains the "next step" to perform.
make an ajax request (use jQuery) to a php script that reads from the database and outputs the return value in whatever format you prefer (html, json) then display it in the front end with javascript

How to identify the use of Ajax in jQuery?

I want to make a form that uses jQuery's ajax function to submit the data, but to be functional when javascript is disabled. So I need a way to know, in the server-side script (PHP), weather the request came from ajax or from simply submiting the form.
HTML:
<form id="form_1" method="post" action="process.php">
jQuery:
$.ajax({
type: "POST",
url: "process.php",
data: $("#form_1").serialize(),
cache: false,
success: function(msg){alert(msg)}
});
So I would like to check in process.php if it was called from jQuery or from submiting the form. Note that I serialize the data, I don't want to use an URL parameter, like '&ajax=1'. Thanks!
Automatically, requests made with XMLHTTPRequest (like those made with jQuery's AJAX suite) have the X-Requested-With header set to XMLHTTPRequest. You can check for the presence of this header.
if (
isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
($_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHTTPRequest')
) {
// request is AJAX
}
You can check for the presence of $_SERVER['HTTP_X_REQUESTED_WITH']. jQuery will send this header with AJAX calls.
The jQuery serialize() method won't serialize (and therefore provide a value for) any submit buttons contained within the form, but submitting the form using one of these will do so. You can check for the existence of that value using PHP and handle appropriately.
I know you don't want to use a url parameter, but it might be the only way you can determine where the call came from.
You can construct data manually and add an AJAX only parameter, and then check for it in PHP.
I would suggest you add a field to your form when it is submited via ajax just before the ajax call. So you can serialize your form and send it as the data containing your ajax=1 for example
The server has no guaranteed way to know what mechanism the client used to make a request. Any request that you can make via JQuery or any other kind of page load can be spoofed by another client to look exactly the same; the server would have no clue.
A client that isn't trying to spoof the result will generally send some clues to the server, in the form of the UserAgent string, and so on, but none of these clues will tell the server anything about whether it's being called via Ajax or not.
Therefore the only route you have to tell the server where the request is coming from is in the URL, and the easiest way to do that is to add an extra parameter. I know you don't want to do this, but it is the best answer to your question.
The alternative option is to have a different action URL for the form if it is called via Javascript. You can toggle the URL easily in JQuery when the page is loaded, and because it is done in Javascript, if JS is disabled then the form will post to the default URL, and you'll be able to generate you non-JS page load.
The final solution is not to do anything different on the server; render the page exactly the same whichever route the user comes in via, and instead have the JQuery code accept the that page code and extract the relevant parts of it for use in the Ajax context.
I hope that helps.
There is a much simpler way to achieve this. Use something similar for jQuery:
$("form").submit(function(){
/*ajax request*/
return false;
}
The return false; does the "magic". If you have JS enabled, then the submit button won't submit the regular way; you can process data via jQuery and send it with AJAX. If you have JS disabled, therefore this function is not called and the form is submitted as usual.

Form auto submit ajax not working

I'm passing some variable from one file to another php file that contains a form via jQuery ajax. On The form page where data is being passed to have the following code in it, The values are getting passed in properly and and fields are getting populated with the correct entries, i'm able to very this with firebug response, but page is not automatically submitting. Is their anything i should be looking for that is preventing form from auto submitting. If i access the form page directly, i can see auto submit works.
<?php
$title = $_POST['title'];
$wrapper = $_POST['wrapper'];?>
<form action="test.php" method="post" id="publish">
<input type="text" value="<?php echo $title ?>" name="title">
<textarea name="wrapper"><?php echo $wrapper?></textarea>
<input type="submit" value="Submit">
</form>
<script>
window.onload = function(){
document.getElementById('publish').submit();
}
</script>
ajax code that is sending the values looks like this
$.ajax({
type: "POST",
url: "process.php",
data: {
title: 'test',
wrapper: 'testing123'
},
success: function(msg){
alert( "Data Saved: " + msg );
}
});
Spot the difference:
getElementById('publishForm')
id="publish"
From what I see the auto submit is linked to the 'publishForm'
However, your form Id is "publish"
This is probably the cause of the code not working.
Perhaps you should show us the caller code instead of the handler code. Most likely what you're dealing with is the JS not being run during the AJAX call - the PHP page processing is server side.
You could look into sending the form using PHP Curl instead of JS? That would probably address the issue where it works loaded directly, but fails when called from another page.
As far as I understood, that HTML is being loaded through AJAX, right? If so, then window.onload will not be fired since the page was already loaded (AJAX doesn't count). Just do this:
<script type="text/javascript">
document.getElementById('publish').submit();
</script>
EDIT
To break this down:
Your code on SourcePage.php(I made up this name for reference) is posting data to process.php via an AJAX request
process.php then injects "title" & "wrapper" into the html markup and returns html with some javascript to SourcePage.php
You're then expecting that displaying the resulting string (msg) of the returned html on SourcePage.php will get the javascript in that string to execute.
To get this working, you'll need to do a few things.
Parse out the incoming javascript from the html.
Inject the incoming parsed HTML into SourcePage.php's markup.
Pass the parsed out JavaScript into JavaScript's eval function.
Doing this should bring the page from the process.php and successfully execute the JavaScript code on SourcePage.php.
If you were expecting that the JavaScript would run on the server, then I'm afraid you're mistaken as the server(php runtime) will not execute the JavaScript on the server. Perhaps a redirect on the server will accomplish your goal (whatever that may be).
Original
Try this out: http://jsfiddle.net/NiceGuy4263/eJLMS/

Categories