Ajax and php Question - php

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);
}
}
);

Related

Submit form with POST/GET using AJAX

At present I have a like/dislike function on my website, which submits SQL to a database on POST, and uses GET to retrieve the product ID and the product category, so after clicking like it currently refreshes and the link appears as:
"/index.php?id=106&category=Entertainment"
I've been looking at AJAX and figured out how to use it to submit SQL to the database without having to refresh, but I can not get it to submit when I need to submit GET variables too. I'm wondering if anyone knows anything about this as I've been trying everything and haven't been successful. Currently the code for this function looks like the following:
Index.html:
<form class="form-horizontal" action="?id=' . $productData->getID() . '&category=' . $productData->getPcategory() . '" method="post">
<button id="like" type="submit" name="like" value="like" class="btn btn-success" onclick="javascript:return like();"><i class="glyphicon glyphicon-thumbs-up"></i></button>
</form>
Index.php:
if (isset($_POST["like"])) {
$productDataSet = new productDataSet();
$productDataSet->addLike();
$likeDislike = "Product has been added to your <b>likes</b>.";
}
AJAX Function (works in other areas of my website where there are no GET variables needed):
function like()
{
$.ajax({
url: "index.php",
context: document.body
}).done(function() {
});
return false;
}
I know I need to add this code in order for the script to be able to read the GET variables on POST but I don't know what to add, any help would be greatly appreciated.
Thanks.
Generally this is quite a simple task, all you need is to configure an event handler, assuming you're using jQuery (Which you appear to be) the following should do for your javascript:
$(document).on('click', 'a[data-ajax-submission]', function(e)
{
var link = $(this);
var action = link.attr('data-ajax-action');
var id = link.attr('data-resource-id');
if(action == undefined || id == undefined)
{
return;
}
e.preventDefault();
$.ajax({
url: yourUrl, // Will need to set, could also use a data attribute again
type: 'POST',
data: {
action: action,
id: id
},
dataType: 'json',
context: document.body
}).always(function(response)
{
// Do stuff here
})
});
This will cause clicking any element with a data-ajax-submission attribute to trigger this event.
We then take an action, and an id from the other data attributes and send them to the sever as POST data in the ajax request, usage example below:
<a data-ajax-submission data-ajax-action="resource-like" data-resource-id="1">Like</a>
I have used the term "resource" as a placeholder, this could be "product" "category" whatever.
Then in PHP you can just handle it like any other form request:
if(isset($_POST['action']) && $_POST['action'] == 'resource-like')
{
// Check for an ID & any other validation
// Persist, do stuff, etc...
die(json_encode(array(
'success' => $success
)));
}
This is a flexible solution, and should allow you to perform several tasks without having to further modify the JavaScript aspect.
It's worth noting, that typically for like, dislike, vote etc... behavior, you will need to limit the voting to one per visitor, usually achieved by setting a cookie.
Let me know if you have any follow up questions etc...
I'm not sure I understand the problem, but if you want to submit GET and POST variables at the same time, you can try this dirty trick :
$.post( "someFile.php?var1=value1&var2=value2", {
var3 : value3 ,
var4 : value4 })
In PHP, read :
$_GET['var1']
$_GET['var2']
$_POST['var3']
$_POST['var4']

ajax $_POST data then redirect to new page

I have been going crazy for the last 2 weeks trying to get this to work. I am calling a MySQL Db, and displaying the data in a table. Along the way I am creating href links that DELETE and EDIT the records. The delete pulls an alert and stays on the same page. The EDIT link will POST data then redirect to editDocument.php
Here is my PHP:
<?php
foreach ($query as $row){
$id = $row['document_id'];
echo ('<tr>');
echo ('<td>' . $row [clientName] . '</td>');
echo ('<td>' . $row [documentNum] . '</td>');
echo "<td><a href='**** I NEED CODE HERE ****'>Edit</a>";
echo " / ";
echo "<a href='#' onclick='deleteDocument( {$id} );'>Delete</a></td>";
// this calls Javascript function deleteDocument(id) stays on same page
echo ('</tr>');
} //end foreach
?>
I tried (without success) the AJAX method:
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: 'edit_id='edit_id,
success: function(response){
$('#result').html(response);
}
});
}
</script>
I have been using <? print_r($_POST); ?> on editDocument.php to see if the id has POSTed.
I realize that jQuery/AJAX is what I need to use. I am not sure if I need to use onclick, .bind, .submit, etc.
Here are the parameters for the code I need:
POSTs the $id value: $_POST[id] = $id
Redirects to editDocument.php (where I will use $_POST[id]).
Does not affect other <a> OR any other tags on the page.
I want AJAX to "virtually" create any <form> if needed. I do not
want to put them in my PHP code.
I do not want to use a button.
I do not want to use $_GET.
I don't know what I am missing. I have been searching stackoverflow.com and other sites. I have been trying sample code. I think that I "can't see the forest through the trees." Maybe a different set of eyes. Please help.
Thank you in advance.
UPDATE:
According to Dany Caissy, I don't need to use AJAX. I just need to $_POST[id] = $id; and redirect to editDocument.php. I will then use a query on editDocument.php to create a sticky form.
AJAX is used when you need to communicate with the database without reloading the page because of a certain user action on your site.
In your case, you want to redirect your page, after you modify the database using AJAX, it makes little sense.
What you should do is put your data in a form, your form's action should lead to your EditDocument, and this page will handle your POST/GET parameters and do whatever database interaction that you need to get done.
In short : If ever you think you need to redirect the user after an AJAX call, you don't need AJAX.
You have a SyntaxError: Unexpected identifier in your $.ajax(); request here
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: 'edit_id='edit_id,
success: function(response){
$('#result').html(response);
}
});
}
</script>
it should be like this
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: {edit_id: edit_id},
success: function(response){
$('#result').html(response);
}
});
}
</script>
note the 'edit_id='edit_id, i changed, well for a start if you wanted it to be a string it would be like this 'edit_id = ' + edit_id but its common to use a object like this {edit_id: edit_id} or {'edit_id': edit_id}
and you could also use a form for the edit button like this
<form action="editDocument.php" method="POST">
<input type="hidden" name="edit_id" value="272727-example" />
<!-- for each data you need use a <input type="hidden" /> -->
<input type="submit" value="Edit" />
</form>
or in Javascript you could do this
document.location = 'editDocument.php?edit_id=' + edit_id;
That will automatically redirect the user
Given your comment, I think you might be looking for something like this:
Edit
$(document).ready(function() {
$('.editLink').click(function(e) {
e.preventDefault();
var $link = $(this);
$('<form/>', { action: 'editdocument.php', method: 'POST' })
.append('<input/>', {type:hidden, value: $link.data('id') })
.appendTo('body')
.submit();
});
});
Now, I don't necessarily agree with this approach. If your user has permission to edit the item with the given id, it shouldn't matter whether they access it directly (like via a bookmark) or by clicking the link on the list. Your desired approach also prevents the user from opening links in new tabs, which I personally find extremely annoying.
Edit - Another idea:
Maybe when the user clicks an edit link, it pops up an edit form with the details of the item to be edited (details retrieved as JSON via ajax if necessary). Not a new page, just something like a jQuery modal over the top of the list page. When the user hits submit, post all of the edited data via ajax, and update the sql database. I think that would be a little more user-friendly method that meets your requirements.
I was facing the same issue with you. I also wanted to redirect to a new page after ajax post.
So what is did was just changed the success: callback to this
success: function(resp) {
document.location.href = newURL; //redirect to the url you want
}
I'm aware that it defies the whole purpose of ajax. But i had to get the value from a couple of select boxes, and instead of a traditional submit button i had a custom anchore link with custom styling in it. So in a hurry i found this to be a viable solution.

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

Validate before post

I have this little code (part of my registration code) :
<?php
if (#$_POST['Submit'] == 'Register'){
if (strcmp(md5($_POST['user_code']),$_SESSION['ckey']))
{
die("Invalid code entered. Please enter the correct code as shown in the Image");
}
}
?>
<form name="form1" id="signupForm" method="post" action="register.php" style="padding:5px;">
<div class="reg_left">Security code:</div>
<div class="reg_right"><input name="user_code" type="text" size="10"> <img src="pngimg.php" align="middle" width="100" height="40"></div>
<div><input type="submit" name="Submit" class="submit" value="<?php echo $gomb_reg;?>"></div>
</form>
Unfortunately this is check if code is valid after post the form data. I would like to check before posting.
So I think I must use jQuery validation plugin (btw I use jQuery to validate the other fields like email, user, password). But as I'm not an expert in jQuery, I need help to write that php code above in jQuery.
Thank you.
I believe the basic jist would be:
Hook a function to the submit element
That JS function sends the user_code value to PHP script
The PHP script checks the value and and outputs (returns) a bool (or json)
The JS function allows the post if a good value is returned
(Note: Since the jQuery AJAX function do not stop the execution of the script, you'll have to stop the form from submitting, then submit the form in the AJAX callback.)
Look at the jQuery docs for
.post
or
.getJSON, use those function to sent the 'user_code' to be checked.
You can keep most of your php code the same, but you'll want to check for the request header type.
I'm pretty sure jQuery sends the X-Requested-With : XMLHttpRequest but I'm not entirely sure and its late, so to somewhat modify your php script it would look something like this
if (#$_POST['submit'] == 'Register') {
if (strcmp(md5($_POST['user_code']),$_SESSION['ckey']))
{
// check if the request was from an ajax call
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'){
//if it is an ajax request we need to send back a json encoded array
$response = array('success' => 'true', 'message' => 'Invalid code';
// now we encode the array and echo it back
echo json_encode($response);
// exit the script for safety
exit();
} else {
// if the request wasn't ajax the respond business as usual
die("Invalid code entered. Please enter the correct code as shown in the Image");
}
}
}
As for the jQuery code it would probably look something like this:
$(document).ready(function(){
// this creates an event handler on the form submit
$('#signUpForm').submit(function(){
// you'll need to give your user_code input an id of user_code
var user_code = $('#user_code').val();
// I like to use the jQuery $.ajax method since it gives you more controll
$.ajax({
// send a post request
type : 'POST',
// the url you'll be sending the request too
url: 'register.php',
// the type of data you're expecting back
// i prefer json since its easier to work with for me
dataType : 'json',
// the data you want to send which would be your user_code data
// send this in a name/value pair
data : 'user_code=' + user_code + '&submit=Register',
// the success function is called when the ajax call has been
// completed, not whether the user_code matches the $_SESSION['ckey']
// the data variable will contain your json data
success : function(data, textStatus){
// since we json encoded the php array it will
// look something like this
//{ success : 'true', message : 'incorrect code'}
if(data.success == 'true'){
// what you plan on doing if the code is correct
alert(data.message);
} else {
// what you do if the code is incorrect
alert(data.message);
}
}
});
// stop the form from submitting
return false;
});
});
I think that should just about do it. the $.ajax method has a few other call back functions such as onError, complete and similar messages that are worth looking into here. The $.ajax method is a little daunting at first, but after using it a few times, I now prefer it over the other ajax methods they have ($.load,$.get, $.getJSON, or $.post)

Categories