I have a form that is using php to email myself with enquiries. I have some jquery that is filling in details into a div,
How can I pass the Jquery var to PHP via ajax? (I've read that that is the best way?)
Here's how's it's emailing me with php:
<? if(isset($_POST['submit'])) {
$to = "rob#domain.com";
$header = 'From: rob#domain.com';
$subject = "Quotation";
$enquiry_first_name = $_POST['enquiryfirstname'];
$enquiry_last_name = $_POST['enquirylastname'];
$enquiry_title = $_POST['enquirytitle'];
$enquiry_organisation = $_POST['enquiryorganisation'];
$enquiry_address = $_POST['enquiryaddress'];
$enquiry_country = $_POST['enquirycountry'];
$enquiry_email_address = $_POST['enquiryemailaddress'];
$enquiry_telephone = $_POST['enquirytelephone'];
$enquiry_additional_comments = $_POST['enquiryadditionalcomments'];
$body = "You have an quote request from the website:
Name: $enquiry_title $enquiry_first_name $enquiry_last_name
Type of organisation: $enquiry_organisation
Address: $enquiry_address, $enquiry_country
E-Mail: $enquiry_email_address
Tel: $enquiry_telephone
Comments: $enquiry_additional_comments
Kind regards";
mail($to, $subject, $body, $header);
echo "Thank you for your enquiry.";
} ?>
Here's the jquery that is outputting data into a div:
function makeSummary() {
var summary = [];
$steps.not(":last").each(function (i, step) {
$step = $(step);
summary.push('<p><b>' + $step.data('name') + '</b></p>');
var $ch = $step.find('input[type="checkbox"]:checked');
if (!$ch.length) {
summary.push('<p>No items selected</p>');
} else {
$ch.each(function (i, ch) {
summary.push('<p>' + $(ch).val() + '</p>');
});
}
});
return summary.join('');
}
1) Make a hidden input field.
2) Pass the jQuery var content to the hidden input field
$('.selector').change(function(){
//replace the value here.
});
3) Get it in php with $_POST['hiddenname']
E: Here is an example: http://jsfiddle.net/yLuNu/4/
It's using a dropdown to store a value in a hidden field. You can use any output and store it inside of the hidden field.
E2: Since I didn't really get what you want to pass to the hiddenfield: If you have a function and only want the output to save inside the hiddenfield:
What exactly do you want to pass to your script? I saw a checkbox so I thought you wanna use the change func. In case you only want to return the output of a function
$('input#hiddenfield').val($VAR)
while var is the output of your function. Just add this at the end of your existing func..
Just use AJAX and render a hidden input to your form, before submitting it.
Javascript:
$.ajax({
url:'/my/url',
type: 'POST',
dataType: 'json',
data: {
"some-var": "some-value"
},
context: $('form#my-form'), // now use $(this) inside event functions
complete: function(jqXHR, textStatus) {
console.log(jqXHR.responseText);
//this function gets called every time (not only on success or error)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR.responseText);
//do something if call fails!
},
success: function(data, textStatus, jqXHR) {
if(data && data.value) {
if($(this).find("#my-field").length) {
$(this).find("#my-field").val(data.value);
}
else {
$hidden = $("<input>")
.attr("type", "hidden")
.attr("name", "my-field")
.val(data.value);
$(this).append($hidden);
}
//submit form
$(this).submit();
}
}
});
And you AJAX processing PHP File qould look like this.
PHP:
<?php
$data = array(
"value" => "default"
);
if($_POST["some-var"]=="some-value") {
$data = array(
"value" => "something"
);
}
echo json_encode($data);
?>
Just to give you an idea how to solve this!
You will need to do some validation and filtering by yourself!
Related
My javascript code:
function _(selector){
return document.querySelector(selector);
}
function submitForm(){
var data = {
name: _("#name").value,
email: _("#email").value,
message: _("#message").value
}
var output = JSON.stringify(data)
var ajax = new XMLHttpRequest();
ajax.open( "POST", "/PATH" );
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
console.log('success')
} else {
console.log('fail')
}
}
console.log(output)
ajax.send(output);
}
When im trying do this with static data,it's work :
<?php
$name = "mateusz";
$to = "kaawkamateusz#gmail.com";
$subject = "kucharz";
$message = "message";
mail($to, $subject, $message);
?>
but, on example :
$name = $_POST["name"];
doesn't work.
Im trying use JSON but again, idk how get value from AJAX form in PHP.
Im never use PHP before, need help :)
EDIT
print_r show :
Array
(
[{"name":"asd","email":"asd#gmail_com","message":"12"}] =>
)
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
You say you are sending URL encoded form data …
var output = JSON.stringify(data)
… but your data is JSON encoded.
To URL form encode it use URLSearchParams.
var data = {
name: "Example Name",
email: "example#example.com",
message: "This is a message"
}
var output = new URLSearchParams(data);
console.log(output.toString());
Note limited browser support. Consider using a polyfill.
Alternatively, set the correct content type for JSON and rewrite the PHP since JSON is not supported for $_POST.
I'm really lost on how to return a value previously submitted to a PHP file with AJAX jquery. I am just starting to learn jquery so I am still struggling with concepts a bit.
Here is my code for jquery:
$('#button2').click(function(e) {
$.post("status.php",
{name: $('#name').val(),
email: $('#email').val()},
function(data){
$('#message').html(data);
});
return false;
});
$('#button3').click(function(e){
$.get({
url: "status.php",
data: 'information=',
success: function(data) {
$('#content').data(data); },
datatype: "text"
});
return false;
});
I have the user submit their name and email to the php file, that goes through correctly and displays the output message. But I then want to have another button that displays their submission, so name: xxxxx email: xxxxx inside the #content div
Here is the PHP file
<?php
extract($_GET);
extract($_POST);
$data = array();
if(isset($name) && isset($email))
{
$data[$email] = $name;
echo "User information submitted.";
}
if(isset($information))
{
foreach($data as $key => $value)
{
$name .= $key.",";
$email .= $value.",";
}
echo $name."|".$email."\n";
}
?>
Our teacher has supplied us with the PHP file and we are to code the jquery and ajax. I am very lost however. Any help on how I can use $information to retrieve the users submission?
Your not requesting your $name and $email variables in your PHP file. Add this to the top:
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
On a side note your $('#button3') is using $.post and you are using type:"GET". You will need to make a choice on what you want to use.
Note that for button3 handler, you should not use $.post, use $.get instead.
Then you can remove type: ''GET'
I have done to make control autocomplete, but I have a problem to post data with jquery.
<input type="text" id="matakuliah" class="med" name="matakuliah">
<script type="text/javascript">
$(this).ready( function() {
$("#matakuliah").autocomplete({
minLength: 1,
source:
function(req, add){
$.ajax({
url: "<?php echo site_url('bahanAjar/lookup'); ?>",
dataType: 'json',
type: 'POST',
data:req,
success:
function(data){
if(data.response =="true"){
add(data.message);
}
},
});
},
});
});
</script>
on my controller
function lookup(){
// process posted form data (the requested items like province)
$keyword = $this->input->post('term');
$data['response'] = 'false'; //Set default response
$query = $this->matakuliah_model->lookup($keyword); //Search DB
if( ! empty($query) )
{
$data['response'] = 'true'; //Set response
$data['message'] = array(); //Create array
foreach( $query as $row )
{
$data['message'][] = array(
'id_matakuliah'=>$row->id,
'value' => $row->matakuliah,
''
); //Add a row to array
}
}
if('IS_AJAX')
{
echo json_encode($data); //echo json string if ajax request
}
else
{
$this->load->view('admin/bahan_ajar/form_manage_file_view', $data); //Load html view of search results
}
}
The code work it well, but I want to add parameter to call database.
$query = $this->matakuliah_model->lookup($keyword, $id_matakuliah);
like this. how I can get
$this->input-<post('id_matakuliah')
from jquery before.;
and I have another textbox for fill value of autocomplete from textbox matakuliah.
`<input type="hidden" id="matakuliah_post" class="med" name="matakuliah_post">`
When I'm use autocomplete textbox automatic fill another textbox, please help me.
In this case req will contain {term:"your search term"}. Your can extend this javascript object to pass extra data. If you want to post id_matakuliah, you can assign its value like following before $.ajax call:
req.id_matakuliah = "Whatever you want to send";
I have written this ajax request for username checking...
function check_username() {
var username = $("#username").val();
$('.loading').fadeIn().delay(100);
$.post("ajax.php", {
username: $('#username').val(),
}, function (response) {
$('.error, .success').hide();
setTimeout(function () {
$('.loading').hide();
finishAjax('username', response);
}, 1000);
});
return false;
}
function finishAjax(id, response) {
$('#' + id).after(response).fadeIn(1000);
}
It all works fine just a couple of questions,
Can this code be improved in any way, this is the first ever one I have wrote so I wouldn't know.
Is there a way to make this a function for all my ajax requests rather than just username checking, so it can be used for email checking and such too. I am not sure on how to make a function like that would I have to pass variables on my onblur event which is attached to my form, at the minute it looks like this.
Is there a way to stop the ajax from running if the same error is there as previous, ie, string length should be over 3, so someone inputs AJ, and the error message 'must be over 3 characters' comes up, it the user then triggers the onblur event again, with the value of AJ, or CG, then the same error comes up, triggering a script that is useless and using memory.
Is there a way to make the ajax request with every character the user enters?
My ajax php is as follows...
<?php
require('dbc.php');
if (isset($_REQUEST['username'])) {
$q = $dbc -> prepare("SELECT username FROM accounts WHERE username = ?");
$q -> execute(array($_REQUEST['username']));
if (strlen($_REQUEST['username']) < 3) {
echo '<div class="error">Has to be at least 3 characters</div>';
}
elseif ($q -> rowCount() > 0) {
echo '<div class="error">Username already taken</div>';
}
else {
echo '<div class="success">Username available</div>';
}
}
?>
To answer 1 & 2. I would turn it into a plugin and do something along these lines.
$.fn.checkValid = function(options)
{
var response = function(response) {
var setClass = '';
var $span = $(this).data('checkValidTip');
if ($span)
{
$span.remove();
}
if (response === undefined) return;
setClass = (response.valid ? 'valid' : 'invalid');
var $span = $('<span>' + response.msg + '</span>');
$(this)
.data('checkValidTip', $span)
.after($span);
$span.hide()
.fadeIn(1000)[0]
.className = setClass;
};
var ajaxOptions = {
type: 'GET',
url: 'ajax.php',
success: response,
dataType: 'json'
};
this.each(function() {
var that = this;
var ajaxRequest = ajaxOptions;
ajaxRequest.data = {};
ajaxRequest.data[options.key] = this.value;
ajaxRequest.context = that
$.ajax(ajaxRequest);
});
};
Usage
$('#username, #email').blur(function() {
$(this).checkValid({ key: this.id });
});
PHP changes
You should make your PHP function return a JSON, instead of HTML i.e.
<?php
// Do your sql statements here, decide if input is valid or not
$arr = array('valid' => $is_valid,
'msg' => $error_or_good_msg
);
echo json_encode($arr);
/* For example will output:
{
"valid": "false",
"msg": "<b>Error: Must be at least 2 characters</b>"
}
Which can be read directly as response.valid
or response.msg from within response() function
*/
To answer question 3: short answer is no. For this to work, you should have basic validation in JS. The best option would be to use a plugin that uses objects for validation parameters, that way you can output your validation requirements dynamically from your database, from within PHP using json_encode i.e. your output format would be:
var validations = {
username: {
min_chars: 4,
max_chars: 10,
valid_chars: 'qwertyuiopasdfghjklzxcvbnm_-'
},
email: {
regex: /./ //your magic regex here
}
};
jsFiddle
http://jsfiddle.net/sqZfp/2/
To answer 4, just change the event as above from .blur to .keyup should do the trick.
I'm using jQuery with PHP for form validation. I want to return the fields that do not validate so i can highlight them using javascript
this is my attempt using PHP(validate.php):
<?php
...
$a_invalidInput = array();
$from = $_POST['from'];
$to = $_POST['to'];
$email_to = $_POST['email_to'];
if( empty($from) ){
$a_invalidInput[] = 'from';
}
if( empty($to) ){
$a_invalidInput[] = 'to';
}
//validate the email_to address
if( empty($email_to) ){
$a_invalidInput[] = 'email_to';
} else{
//do more validation for email
}
...
?>
This is my jquery code:
...
var data = "from="+ from + "&to=" + to + "&email_to=" + email_to;
$.ajax({
url: "includes/validate.php",
type: "POST",
data: data,
success: function(){
//highlight fields that do not pass validation
}
});
...
I'm not sure if i'm on the right path or not AND how to return the input fields that do not pass validation so i can add a class to highlight the fields that do not pass validation.
I could do this using javascript but i prefer using a php file for validation
Thanks
Marco
One way to go would be to return a json encoded array of fields that do not pass.
From your PHP script, output your Invalid Input array (json encoded so your javascript can use it). Then on the Javascript side, you want to check if that output has any values. If it does, use them.
<?php
// at the end of your script
header('Content-type: application/json');
echo json_encode($a_invalidInput);
exit();
?>
Now in your JQuery, you want to use that json output...
$.ajax({
url: "includes/validate.php",
type: "POST",
dataType: "json",
data: data,
success: function(data){
if (data !== undefined
&& data.length > 0) {
for (var i = 0; i < data.length; i++) {
var field_name = data[i];
var field = $('input[name=' + field_name + ']');
// now you have the field, so you can modify it accordingly.
}
}
}
})
Look into using jQuery for the form validation -- I personally find it easier. That said, you should always double check the data and ALWAYS escape it on the server-side.
http://yensdesign.com/2009/01/how-validate-forms-both-sides-using-php-jquery/