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
Related
I have 2 js files and i want to pass 2 variables from file1.js to file2.js. What i have done until now is to send these 2 variables from file1.js in a 3rd file file3.php with ajax using this:
$('#replace').click(function(){
var replacement = cur;
var replacement2 = cur2;
$.ajax({
url: DOMAIN_NAME+"file3.php",
type: "post",
data: {replacement: replacement, replacement2 : replacement2},
success:function(data){
console.log(data);
},
error:function(){
alert('Something Went Wrong');
},
});
});
In my file3.php:
if(isset($_POST['replacement']) && isset($_POST['replacement2']){
$a = $_POST['replacement'];
$b = $_POST['replacement2'];
}
<input type="hidden" id="af" value="<?=$a;?>">
<input type="hidden" id="bf" value="<?=$b;?>">
In my File2.js:
var a = $('#af').val();
var b = $('#bf').val();
i can see that in the network the ajax passes the variable with a status 200 OK but in the php file my variables doesn't pass. So the file2.js can't get the values. What i am doing wrong??
Let's say you have this simple form:
<form id="my_form">
<input type="text" name="a_field" id="a_field">
<input type="text" name="b_field" id="b_field">
<button id="submit_form">Submit</button>
</form>
The jquery script file (#1) for this form can be named "script1.js" and can look like that:
$(document).ready(function(){
$('#submit_form').on('click').function(e){
e.preventDefault();
var formData = $('#my_form').serialize();
$.ajax({
type: 'POST',
url: 'my_ajax.php',
data: formData
});
});
});
Notice that I serialized the form to be quicker... (If you want you can specify which variables you want to pass to ajax)
Here is an example of my_ajax.php:
<?php
session_start();
if(isset($_SESSION["a_var"])){unset($_SESSION["a_var"]);}
if(isset($_SESSION["b_var"])){unset($_SESSION["b_var"]);}
if(isset($_POST["a_field"])){$a_field=htmlspecialchars($_POST["a_field"]);}else{$a_field=""; exit();}
if(isset($_POST["b_field"])){$b_field=htmlspecialchars($_POST["b_field"]);}else{$b_field=""; exit();}
$_SESSION["a_var"] = $a_field;
$_SESSION["b_var"] = $b_field;
?>
With the above file, we created two php sessions based to the input-field values that we acquired from our html form.
Now the "tricky" part:
Your SECOND js file (#2) must be given an extension .php and NOT .js
It will however execute any javascript code if of course that code is enclosed in "script" tags
Let's name that file "script2.js.php" -which can be like that:
<?php
session_start();
if(isset($_SESSION["a_var"])){$value_a = $_SESSION["a_var"];}else{$value_a="";}
if(isset($_SESSION["b_var"])){$value_b = $_SESSION["b_var"];}else{$value_b="";}
?>
<script>/*...include jquery here (if necessary)...*/</script>
<script>
$(document).ready(function(){
//jquery is NOT necessary for my example
//I just included it in case you need to do other tasks...
var valueA = '<?php echo $value_a; ?>';
var valueB = '<?php echo $value_b; ?>';
//Now you can do anything with these values... For example, you could alert them:
alert('Value A: '+valueA+' - Value B: '+valueB);
});
</script>
One last thing:
While to include a js file to your html page you do:
<script src="http://www.example.com/scripts/yourscript.js"></script>
To include the "js.php" file you must do it by using the php "include" function:
This is how I would suggest to pass variables from one js file to another by using php sessions!
My example is quite "basic" and could take a lot of "polishing" work regarding functionality and security... But should give you an idea as of how to start...
Hope that helps you and/or others...
<input id="u1" class="username">
<input id="u2" class="username">
<input id="u3" class="username">
...
How to fetch input value with "username" class and send with ajax jquery to php page.
i want to recive data like simple array or simple json. (i need INPUT values and not ids)
var inputValues = [];
$('input.username').each(function() { inputValues.push($(this).val()); });
// Do whatever you want with the inputValues array
I find it best to use jQuery's built in serialize method. It sends the form data just like a normal for submit would. You simply give jQuery the id of your form and it takes care of the rest. You can even grab the forms action if you would like.
$.ajax({
url: "test.php",
type: "POST",
data: $("#your-form").serialize(),
success: function(data){
//alert response from server
alert(data);
}
});
var values = new Array();
$('.username').each(function(){
values.push( $(this).val());
});
I am trying to use jquery's form plugin from http://www.malsup.com/jquery/form/#ajaxSubmit and .ajaxsubmit to submit my data in a form however I am not really sure what .ajaxsubmit is passing and how I can read this in my php file.
I have a validate function
function validate(formData, jqForm, options) {
alert('About to submit: \n\n' + queryString);
return true;
}
that shows queryString which is
first=testfirstname&last=testlastname&age=90
when I use .ajaxsubmit, nothing happens as listed in my script below.
$(document).ready(function() {
var options = {
target: '#output1',
beforeSubmit: validate,
success: showResponse
};
//submission
$('#myForm').submit(function() {
$(this).ajaxSubmit(options);
return false;
});
});
My form is
<form action="comment.php" method="post" id="myForm">
I was wondering what format is the data being sent, would I do something with
$_REQUEST['first'];
and also how would I also pass in an addition value from the $_SESSION?
Thanks
As far as I know, the jQuery plugin actually sends the plugin data as POST-data to PHP (similar to setting method="post" on your <form> tag). You can access it like this:
$_POST['name_of_field_in_form'];
The name_of_field_in_form is just the name of a field, for example if you have this code <input name="email" type="text" />, you could access it via $_POST['email'];.
About your second query, not sure what you mean, but you can use session_start(); to create a session and after that $_SESSION acts like a 'normal' array.
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);
}
}
);
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)