Interaction between client and server using ajax and json response - php

I have a website, that I am building that allows consumers to order food. The user will search by their Postal code (UK) such as A1 1AA for example. Once they search by their postal code, the restaurants that deliver to their area will appear.
I am currently working on the checkout page, and i want to stop users from inputting a postal code that, that said restaurant does not deliver too. I would like to do this the moment the user presses enter on the postal code field.
I just have no idea how to do this, i have put together some ajax following a number of posts (see below,very first time using ajax so please forgive me if its sloppy) to do this,i know it is not complete but i have no idea where to go from here.
I have a string url with the users area and postal code, within it. and i also have a database with the postal codes the restaurants delivers to, i would like to do something along the lines of if the restaurant does not deliver to the postal code entered echo "Sorry, This restaurant does not deliver to A1. ".
I have tried to achieve this using both AJAX and Jquery
Code
<div id="container">
<form id="myform" name='myForm'>
<input type="text" id='doorno' name="doorno" value="" placeholder="e.g. 2a" min="1" >
<input type="text" id='addlin1' name="addlin1" value="" placeholder="e.g. Brunel Hall">
<input type="text" id='addlin2' name="addlin2" value="" ><br>
<input type="text" id='city' name="city" value="" >
<input type="text" id='postal' name="postal" value="" placeholder=""><br>
</form>
<div id='ajaxDiv' style="background-color:red">Your result will display here</div>
$(function() {
$("#container").keypress(function (e) {
if (e.which == 13) {
e.preventDefault(); // this prevents the default action of a enter
$.post('ajax-example.php',$("#myform").serialize() , function(response) {
$('#ajaxDiv').html(response); // this will echo any response from ajax file
});
}
});
});
I have just tried it in Jquery. It work almost perfectly apart from it doesn't work on keypress but onclick, but i don't know how i would do something along the lines of if $_POST['postal'] is not equal to $postcode( users postcode variable from string url)/ the postcodes the restaurant delivers to column in my db
$(function(){
$('input[name="postal"]').click(function(){
alert('Hello...!');
});
$('#city').keypress(function (e) {
var key = e.which;
if(key == 13) // the enter key code
{
$('input[name = postal]').click();
return false;
}
});
});

As far as I understand, here you are trying to add a keypress handler on the input field.
This handler will make a post request and will validate whether deliver is possible in the specified postal code.
If that's the case then it would be better to use blur handler instead of keypress.
Because keypress will trigger server request for every key pressed, i.e. if user enters 5 digit postal code e.g. AA110 then 5 times post request will be sent which is unnecessary.

For jQuery; You may want to try this approach and see if it does what you want:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script type="text/javascript">
(function($) {
$(document).ready(function(){
$(document).keypress(function(e) {
if(e.which == 13) {
if($(":focus").get(0) == $('input[name = postal]').get(0) ){
// DO WHATEVER YOU WANT TO DO HERE
// BECAUSE ENTER WAS PRESSED INSIDE OF THE FIELD WITH THE NAME postal
// FOR TESTING... ALERT SOMETHING...
alert("Sure, you pressed the Enter Key inside of the Postal Field...");
}
}
});
});
})(jQuery);
</script>
You can test and Fiddle it out here: https://jsfiddle.net/csqsLmxh/
OK, so here's how it all ties together.
JAVASCRIPT: JQUERY
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script type="text/javascript">
(function($) {
$(document).ready(function(){
$(document).keypress(function(e) {
if(e.which == 13) {
if($(":focus").get(0) == $('input[name = postal]').get(0) ){
// SEND OUT AN AJAX REQUEST TO THE PHP-SCRIPT ON THE SERVER
// HERE WE ARE SIMPLY SAYING:
// ONCE THE USER FINISHES TYPING INSIDE THE POSTAL FIELD & HITS ENTER
// GO TO THE SERVER AND ASK THE SCRIPT: ajax.processor.php TO USE THE
// POSTED POSTAL CODE & CITY TO SEARCH FOR THE NEAREST AVAILABLE RESTAURANT...
// IN THIS CASE WE USE JSON, JUST IN CASE WE MAY WANT TO SEND BACK A COLLECTION OF DATA...
// AND SO OUR AJAX GOES LIKE THIS:
$.ajax({
url: "./ajax-processor.php",
dataType: "json", //<== CHANGE TO "HTML" IF YOU ARE EXPECTING HTML DATA.
cache: false,
type: "POST",
data: ({
postal : $("#postal").val(),
city : $("#city").val()
}),
success: function (data, textStatus, jqXHR) {
// IF OUR AJAX CALL SUCCEEDS AND THUS RETURNS SOME RESULTS
// IN THIS CASE JSON, WE CAN USE IT TO UPDATE THE #ajaxDiv...
// HOWEVER IF WE ARE EXPECTING JUST HTML WE WILL GO A DIFFERENT ROUTE IN THE SUCCESS HANDLER...
// PLEASE, NOTE THAT YOU MAY NOT HAVE BOTH JSON & HTML SIMULTANEOUSLY
// THIS IS AN "EITHER-OR" CASE HERE:
// SO IF YOU EXPECT HTML, YOU ARE ADVISED TO
// EITHER DELETE OR COMMENT-OUT FROM THE BEGINNING
// TO THE END OF JSON HANDLING LOGIC BELOW & VICE-VERSA
if(data){
// ##BEGINNING OF JSON HANDLING...## //
if(data.restaurant){
var output = "<em>Restaurant: </em><strong>" + data.restaurant + "</strong>";
output += "<br /><em>Take-Away: </em><strong>" + data.takeAway + "</strong>";
$("#ajaxDiv").html(output );
}
// ## END OF JSON HANDLING... ## //
// ##BEGINNING OF HTML HANDLING...## //
$("#ajaxDiv").html(data); <== JUST UPDATE THE DIV WITH THE RAW DATA FROM THE RESPONSE... IT IS EITHER HTML OR STRING OR NUMERIC DATA...
// ##END OF HTML HANDLING...## //
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('The following error occured: ' + textStatus, errorThrown);
},
complete: function (jqXHR, textStatus) {
}
});
}
}
});
});
})(jQuery);
</script>
HTML
<html>
<body>
<div id="container">
<form id="myform" name='myForm'>
<input type="text" id='doorno' name="doorno" value="" placeholder="e.g. 2a" min="1" >
<input type="text" id='addlin1' name="addlin1" value="" placeholder="e.g. Brunel Hall">
<input type="text" id='addlin2' name="addlin2" value="" ><br>
<input type="text" id='city' name="city" value="" >
<input type="text" id='postal' name="postal" value="" placeholder=""><br>
</form>
<div id='ajaxDiv' style="background-color:red">Your result will display here</div>
</body>
</html>
PHP
<?php
// FILENAME: ajax-processors.php <== MUST MATCH THE URL WE DECLARED IN THE AJAX DEFINITION (JS)
$postal = isset($_POST['postal']) ? htmlspecialchars(trim($_POST['postal'])) : null;
$city = isset($_POST['city']) ? htmlspecialchars(trim($_POST['city'])) : null;
// RUN YOUR QUERIES AND DO ALL YOUR MAGIC USING THE POSTED $postal & $city
// TO DETERMINE WHICH DATA ARE RELEVANT TO BE RETURNED...
// ASSUMING IN THE END YOUR QUERIES RETURNED SAY 2 RESULTS LIKE Derby Inn, Kings Pizza.
// YOU CAN THEN BUNDLE THE RESULTS INTO AN ARRAY (IF IT IS NOT ALREADY AN ARRAY OR OBJECT) LIKE SO:
$arrResponse = array(
"restaurant" => "Derby Inn",
"takeAway" => "Kings Pizza",
);
// HOWEVER, THIS IS NOT NECESSARY IF YOU ARE SENDING BACK ONLY A STRING VALUE...
// IN THE CASE OF A STRING VALUE (SAY, JUST "Kings Pizza")
// YOU COULD JUST DO IT OTHERWISE. LIKE THIS:
/* die("Kings Pizza"); */
// IF YOU DID IT LIKE THIS, BE SURE TO CHANGE YOUR THE "dataType" ATTRIBUTE
// IN YOUR AJAX FROM *JSON* TO **HTML** AND ALSO TO HANDLE THE SUCCESS
// CALLBACK DIFFERENTLY... ***SEE THE JAVASCRIPT SECTION FOR COMMENTS***
// NOW WE ARE DONE... ALL WE NEED DO IS SEND THIS RESPONSE BACK TO THE SCRIPT AS JSON LIKE SO:
die( json_encode($arrResponse));
// ALTHOUGH THERE ARE NO REAL QUERIES HERE OR ANY PROCESSING LOGIC,
// THIS SCRIPT WILL STILL RUN & SEND BACK JSON DATA TO THE JAVASCRIPT
// DOUBT IT? THEN TRY IT....

After talking to you what I understood is that you have successfully done
On pressing enter you sent a query to database
Then from database you sent process it and send error message if postal codes do not match
Now you want to know .howt to process no delivery error message sent from database inside the post callback function so as to provide alert or notification to user
For that purpose I have put down a small example
create two files Example.php and Example.html in root directory and copy each of the files content from here to inside them now in browser type
localhost/Example.htmlpress enter notice each time you run the file the output changes.
Data from php to html page is sent using json format which will be useful to you in future a lot.First data to be sent is inserted into an associative array
then it is encode into json format using json_encode() function in server side
JSON.parse() method is used to parse the json format data obtained here the value of json object is accessed using jsonobjectname.keyName to get the value sent from server.
Here in case
var returned = JSON.parse(data)
console.log(returned.Key);
these lines explains it
And by the way when associative array is converted into json format it looks like this
$result = array("Key"=>"1");
echo json_encode($result);
{"Key":"1"}
Here is document of json_encode function
Another thing I used random variable generator function rand() to simulate both true and false conditions for the loop .
Example.php
<?php
$trueorfalse = rand(0, 1);
if($trueorfalse){//your condition if there is delivery
$result = array("Key"=>"1");
echo json_encode($result);
}else{//your condition if there is no delivery
$result = array("Key"=>"0");
echo json_encode($result);
}
?>
Example.html
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$.post("/NTD.php",function(data){
console.log(data);
var returned = JSON.parse(data)
console.log(returned.Key);
if(returned.Key==0){
$("#NotifcationDiv").html("There is no shipping to your region");
alert(returned["Key"]+"No delivery");
}
})
});
</script>
</head>
<body>
<p id="NotifcationDiv"></p>
</body>
</html>
Disclaimer:Sorry for being late I saw the OP question and worded a simple example of json and php interaction from server to client and I only so the another answer posted down later only

Related

AJAX\JQUERY: Update MYSQL database with form data without refreshing

Ok, so I've gotten most of this thing done.. Now comes, for me, the hard part. This is untreaded territory for me.
How do I update my mysql database, with form data, without having the page refresh? I presume you use AJAX and\or Jquery to do this- but I don't quite grasp the examples being given.
Can anybody please tell me how to perform this task within this context?
So this is my form:
<form name="checklist" id="checklist" class="checklist">
<?php // Loop through query results
while($row = mysql_fetch_array($result))
{
$entry = $row['Entry'];
$CID = $row['CID'];
$checked =$row['Checked'];
// echo $CID;
echo "<input type=\"text\" value=\"$entry\" name=\"textfield$CID;\" id=\"textfield$CID;\" onchange=\"showUser(this.value)\" />";
echo "<input type=\"checkbox\" value=\"\" name=\"checkbox$CID;\" id=\"checkbox$CID;\" value=\"$checked\"".(($checked == '1')? ' checked="checked"' : '')." />";
echo "<br>";
}
?>
<div id="dynamicInput"></div>
<input type="submit" id="checklistSubmit" name="checklistSubmit" class="checklist-submit"> <input type="button" id="CompleteAll" name="CompleteAll" value="Check All" onclick="javascript:checkAll('checklist', true);"><input type="button" id="UncheckAll" name="UncheckAll" value="Uncheck All" onclick="javascript:checkAll('checklist', false);">
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');"></form>
It is populated from the database based on the users session_id, however if the user wants to create a new list item (or is a new visitor period) he can click the button "Add another text input" and a new form element will generate.
All updates to the database need to be done through AJAX\JQUERY and not through a post which will refresh the page.
I really need help on this one. Getting my head around this kind of... Updating method kind of hurts!
Thanks.
You will need to catch the click of the button. And make sure you stop propagation.
$('checklistSubmit').click(function(e) {
$(e).stopPropagation();
$.post({
url: 'checklist.php'
data: $('#checklist').serialize(),
dataType: 'html'
success: function(data, status, jqXHR) {
$('div.successmessage').html(data);
//your success callback function
}
error: function() {
//your error callback function
}
});
});
That's just something I worked up off the top of my head. Should give you the basic idea. I'd be happy to elaborate more if need be.
Check out jQuery's documentation of $.post for all the nitty gritty details.
http://api.jquery.com/jQuery.post/
Edit:
I changed it to use jquery's serialize method. Forgot about it originally.
More Elaboration:
Basically when the submit button is clicked it will call the function specified. You want to do a stop propagation so that the form will not submit by bubbling up the DOM and doing a normal submit.
The $.post is a shorthand version of $.ajax({ type: 'post'});
So all you do is specify the url you want to post to, pass the form data and in php it will come in just like any other request. So then you process the POST data, save your changes in the database or whatever else and send back JSON data as I have it specified. You could also send back HTML or XML. jQuery's documentation shows the possible datatypes.
In your success function will get back data as the first parameter. So whatever you specified as the data type coming back you simply use it how you need to. So let's say you wanted to return some html as a success message. All you would need to do is take the data in the success function and place it where you wanted to in the DOM with .append() or something like that.
Clear as mud?
You need two scripts here: one that runs the AJAX (better to use a framework, jQuery is one of the easiest for me) and a PHP script that gets the Post data and does the database update.
I'm not going to give you a full source (because this is not the place for that), but a guide. In jQuery you can do something like this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() { // DOM is ready
$("form#checklist").submit(function(evt) {
evt.preventDefault(); // Avoid the "submit" to work, we'll do this manually
var data = new Array();
var dynamicInputs = $("input,select", $(this)); // All inputs and selects in the scope of "$(this)" (the form)
dynamicInputs.each(function() {
// Here "$(this)" is every input and select
var object_name = $(this).attr('name');
var object_value = $(this).attr('value');
data[object_name] = object_value; // Add to an associative array
});
// Now data is fully populated, now we can send it to the PHP
// Documentation: http://api.jquery.com/jQuery.post/
$.post("http://localhost/script.php", data, function(response) {
alert('The PHP returned: ' + response);
});
});
});
</script>
Then take the values from $_POST in PHP (or any other webserver scripting engine) and do your thing to update the DB. Change the URL and the data array to your needs.
Remember that data can be like this: { input1 : value1, input2 : value2 } and the PHP will get something like $_POST['input1'] = value1 and $_POST['input2'] = value2.
This is how i post form data using jquery
$.ajax({
url: 'http://example.com',
type: 'GET',
data: $('#checklist').serialize(),
cache: false,
}).done(function (response) {
/* It worked */
}).fail(function () {
/* It didnt worked */
});
Hope this helps, let me know how you get on!

PHP + AJAX - Pass Current $_GET Variables So Far

I have a page where users fill out $_GET data for some options. I'd like to pass these $_GET variables using AJAX to a .php script. But my issue is how do I pass those $_GET variables they filled out so far, without refreshing the page?
Here is my code so far.
$.ajax({
type: "GET",
url: "serverside script to process on data",
data:{name:youwant}, // Here is where I want to take what the user has filled out so
// far, and place it here all without refreshing the page
success: function(data){
alert("return here if success")
}
})
First of all, drop this task into small ones:
1) Get/process variables in JavaScript
2) Send them to PHP
3) Parse/handle the ones
4) Depending on result send respond back to JavaScript
5) Handle that respond and display a message to user
Take a look at this example,
Let's assume that jquery.js is loaded.
Assume that we want to send the values of the inputs we have - email and password.
<script type="text/javascript">
$("#Send").click(function(){
$.ajax({
type : "GET",
//Look carefully:
data : {
// it'll be PHP vars // This is JS vars
email : $("#email").val(),
password : $("#password").val()
},
success : function(respondFromPHP){
alert(respondFromPHP);
}
});
});
</script>
<input type="text" id="email" />
<input type="password" id="password" />
<br />
<button id="Send">Send to php</button>
In your php script, just handle vars you get, like this:
<?php
print_r($_GET); // will print smth like Array("email" => "foo", "password" => "bar")
// Then create function so that you can simplify handling of the vars.
// Like this:
function validate_password($password){}
function validate_email($email){}
I don't know your code, but you can have a form, but instead of submit it, you put a onsubmit method to a javascript function. In that function you gather all variables and pass it through ajax.
Example: <form name="form1" method="get" onSubmit="return send()">
<script>
function send() {
$.ajax(...);
return false;
}
</script>
You can use seralize function to send in $.ajax data field

Ajax request inside ajax request fails - reloads the whole page again

So, basicly what I'm trying to achieve:
In index.php
I would enter products code to search for products information and it's images (that query is run in open_first.php, called via ajax post request).
It works just perfect..
When open_first.php is loaded, it displays me some images I can select from (when I click on the image, it's relevant checkbox get's checked containing the image id).
This works too, just fine.
BUT,
If I enter a code in the field: "productCodeCopy" and click on "confirmCodeCopy" -button it reloads the whole page, I mean index.php and everything I've entered is lost and I'm back in the starting point again. I don't understand why it does so. I suppose it has something to do with the fact, that the second ajax request is made from a dynamically created page (open_first.php)?? Do I miss something I should POST too?? Or what's the problem, this is really frustrating me since I've tried to fix this for hours now.
Note:
Jquery is loaded in index.php, open_first.php and open_second.php, I've just ignored that to keep the code simpler.
FILE: index.php (the "starting point")
<!-- head -->
<script type="text/javascript">
$(document).ready(function() {
$("#confirmCode").on('click', function(){
var productCode = $("#productCode").val();
$.ajax({
url: 'open_first.php',
type: "POST",
data: ({code: productCode}),
success: function(data){
$("#found").html(data);
},
error: _alertError
});
function _alertError() {
alert('error on request');
}
});
});
</script>
<!-- body -->
<input type="text" class="textfields" id="productCode" name="productCode" value="YT-6212">
<input type="button" class="admin-buttons green" name="confirmCode" id="confirmCode" value="Search">
<div id="found"></div>
FILE open_first.php
<script type="text/javascript">
$(function() {
$("#foundImage").on('click', function(){
$('#foundImage').toggleClass("foundImage-selected foundImage");
var myID = $('#foundImage').data('image-id');
var checkBox = $('input[id=selectedImages-'+myID+']');
checkBox.prop("checked", !checkBox.prop("checked"));
});
$("#confirmCodeCopy").on('click', function(){
var checkedItems = $('input:checkbox[name="selectedImages[]"]:checked');
// this code here reloads the whole page / view (as in "index.php")
$.ajax({
url: 'open_second.php',
type: "POST",
data: ({checked: checkedItems, copyTo: productCodeCopy, code: "<?php echo $_POST['code']; ?>"}),
success: function(data){
$("#copyToProducts").append(data);
},
error: _alertError
});
/*
// the code below runs just fine when I hit the button "confirmCodeCopy"
alert('Fuu');
return false;
*/
});
function _alertError() {
alert('error');
}
});
</script>
<!--BODY-->
<!-- these are dynamically generated from php, just to simplify we have checkbox that contains value "1" to be posted in ajax -->
<div class="foundImage" id="foundImage" data-image-id="1"><img src="image.jpg"><input type="checkbox" id="selectedImages-1" name="selectedImages[]" value="1" style="display: none;"></div>
<label for="productCodeCopy">Products code</label>
<input type="text" class="textfields" id="productCodeCopy" name="productCodeCopy">
<br /><br />
<label for="confirmCodeCopy"> </label>
<input type="button" class="admin-buttons green" name="confirmCodeCopy" id="confirmCodeCopy" value="Search">
<div id="copyToProducts"></div>
open_second.php only prints out POST variables for now, so nothing special yet.
SOLVED
So ok, I solved it. With dumdum's help.
I removed the line:
$('input:checkbox[name="selectedImages[]"]:checked');
And added this:
var checkedItems = new Array();
var productToCopy = $('#productCodeCopy').val();
$("input:checkbox[name=selectedImages[]]:checked").each(function() {
checkedItems.push($(this).val());
});
Since there was no form element present, it didn't get the field values unless "manually retrieved" via .val() -function.. Stupid me..
I don't know how much this affected but I changed also:
data: ({checked: checkedItems, copyTo: productCodeCopy"})
To
data: {"checked": checkedItems, "copyTo": productToCopy}
So now it's working just fine :) Cool!
WHen you apply event hander to a button or a link to do ajax...always prevent the browser default processing of the click on that element
There are 2 ways. Using either preventDefault() or returning false from handler
$("#confirmCodeCopy").on('click', function(event){
/* method one*/
event.preventDefault();
/* handler code here*/
/* method 2*/
return false;
})
The same is true for adding a submit handler to a form to do ajax with form data rather than having the form redirect to it's action url
your code $('input:checkbox[name="selectedImages[]"]:checked'); is returning undefined making the json data in the ajax call invalid. Check you selector there.

jQuery json loop with ajax call for php function

I'm new to Javascript. The code for a jQuery-ajax-php-cooperation does strange things. It works - sometimes.
This is what I want to do:
make some settings in a form (works)
read JSON-file after pressing submit-button (works)
loop the JSON-items, extract the values of each item and form a parameter-string (problem is here: loop is not (always) executed in the button-pressed-function)
send parameter-string built from each items values to PHP-file (works if loop is entered)
receive the response from the PHP-file (html-tag) (works)
update a form element with the response value (not yet implemented, actually show an alert with the PHP-response for debugging purposes)
The JSON file is valid (tested).
The HTML-Page is valid HTML5 (tested).
The PHP-script works and returns a valid HTML-Image-Tag (tested).
When I press the button, no responses from the PHP-file are displayed in the alert I implemented for debugging purposes. But this works:
reload page
open Firebug
set breakpoint at loop-begin
skip one statement forward
reload page
the loop is entered, all works fine
I can close Firebug and the loop is performed properly.
The javascript code
<script type="text/javascript">
$(document).ready(function () {
//click event of submit button
$('#generator').click(function(){
// GET variables
var datafile = "my.json";
var logo = false;
// if checkbox is checked
if( $('#logo').attr('checked')){
logo = true;
};
// read data from json file
$.getJSON(datafile,function(data){
//iterate through the data-sets
for(var i=0; i < data.length; i++) {
// get the response from server for each data-set
$.ajax({
type: 'POST',
async: false,
cache:false,
url: 'myfile.php',
data: 'param1='+data[i].field1+'&param2='+data[i].field2+'&logo='+logo,
success: function(response){
//$('#imgdisplay').html(response);
// alert only for debugging purposes
alert(response);}
}); // end of ajax-call
}; // end of for-loop
} ); // end of getJSON
}); // end of button.click
}); // end of document.ready
</script>
(sorry for bad intented formatting)
I use a for-loop, could not get an each()-loop to work properly.
And this is the form:
<form name="settings">
<label>Source file</label>
<select id="datasource" name="datasource">
<option value="extract">Extract</option>
<option value="filter">Filter</option>
</select><br />
<label>Logo</label>
<input type="checkbox" id="logo" name="logo" value="ON"/><br />
<p> </p>
<input type="submit" value="Start Generator" id="generator" name="generator" />
</form>
<div id="imgdisplay" class="imgdisplay"></div>
What causes this strange behavior? How can I solve it?
Try to return false from the anonymous click method
$('#generator').click(function(){
....
return false;
}
This will ensure that the click will not post your form

Ajax and php Question

Finally got my domain checker working. Now the question is I have a form (search-domains) when user types and submits at the moment it passes the query to process.php and that out puts:
echo "$Domain is/isn't available"
What I want is this to return on my results page (the results page also has a search form on it so if someone searches there it would display on same page). At the moment when user clicks it passes http://example.com/process.php?domain=domain.com(etc...).
What i think i need is Ajax to pull this url before it goes to process.php then ajax runs the query process sends result back to ajax an it outputs on the results page. Also I have another php script which displays the domain with different tlds and displays id they are available or not. So i also need ajax to run this and display aswell.
I am very new to ajax but looking for tutorials but most of them are for displaying success messages after contact forms and the like. If someone could point me in the right direction id much appreciate it.
EDIT
This is what i have but itsd still re-directing me to process.php
HTML
<form method="get" id="form">
<input type="text" class="searchdomains" onclick="if (this.value =='Domain Name Search...'){this.value=''}" value="Domain Name Search..." name="domain" id="search-domain-input">
<input type="image" src="<?php bloginfo('template_url'); ?>/inc/img/btn_up_search.png" class="search" name="Search" id="Submit">
</form>
JQuery
$.ajax(
{
type: 'GET',
url : "http://example.com/process.php?domain=",
// here you pass js object in convention: { 'query_string' : 'its value' }
data : { 'domain' : $('#search-domain-input').val() },
success: function (data) {
$("#results").html(data);
}
}
);
PHP
if(isset($avail)){
echo '<p>'.$avail.' is available to be registered</p>'
} else {
echo '<p>'.$avail.' is taken register with us for price</p>'
}
Thanks
Joe
in jquery (http://jquery.com/) you can make ajax requests by using the function :
$.ajax(
{
url : "url to fetch",
success: function (data) {
// data is variable that is returned from server as HTML by default, or you can use JSON format
$("#content").html(data);
}
}
);
If you dont want to use jquery javascript library, you need to create xmlhttprequest object and make helper functions for it, which i do not recommend, since jquery can be used for more stuff than just ajax calls.
EDIT :
#comment
simply create process.php where you will accept "domain" as query string - which will check if the domain exists, if not it should echo <p>'$result.'is/isn't available</p>, than in $.ajax({...}); pass that url and "data" will be available to you.
To pass GET params with $.ajax() you can use the following setting:
$.ajax(
{
type: 'GET',
url : "url to fetch",
// here you pass js object in convention: { 'query_string' : 'its value' }
data : { 'domain' : $('#domain_name_input_field').val() },
success: function (data) {
// data is variable that is returned from server as HTML by default, or you can use JSON format
$("#content").html(data);
}
}
);

Categories