How to get the values from a $.ajax using php - php

I'm trying to use $.ajax to send some values to a php page which then sends an email,
I can't figure out how to get the values from $.ajax in my php file,
any help would be appreciated,
$(function() {
$('form#email input[type=image]').click(function() {
var name = $('form#email #name').val();
var enq = $('form#email #enq').val();
var dataString = 'name=' + name + '&enq=' + enq;
$.ajax({
type:'POST',
url:'email.php',
data:dataString,
success:function() {
$('form#email').fadeOut();
}
});
$('form#email')[0].reset();
return false;
});
});
php file
if (isset($_POST['submit_x'])) {
$name = $_POST['name'];
$enq = $_POST['enq'];
$name = htmlentities($name);
$enq = htmlentities($enq);
//echo $name,$enq;
$to = 'amirkarimian#hotmail.co.uk';
//$to = 'tutor#inspiretuition.co.uk'
$subject = 'Enquiry';
$message = $enq;
mail($to,$subject,$message);
if(!mail) {
echo 'failed to send mail';
}
}
the email doesn't get sent.
if I dont use $.ajax and submit the form normally the email get sent.
thanks

You're checking for a variable you're not submitting, submit_x, you'll need to remove that outer if check. Also, it's better to let jQuery serialize your strings properly (what if there's a & in there?) like this:
$(function() {
$('#email input[type=image]').click(function() {
$.ajax({
type:'POST',
url:'email.php',
data: { name: $('#name').val(), enq: $('#enq').val() }
success:function() {
$('form#email').fadeOut();
}
});
$('#email')[0].reset();
return false;
});
});
Or if the <form> elements have proper name attributes (they should, for graceful degradation) , you can replace data: { name: $('#name').val(), enq: $('#enq').val() }
with data: $('#email').serialize().

try sending 'submit_x' to php :)

You can use a data map to define your data:
var name = $('form#email #name').val();
var enq = $('form#email #enq').val();
$.ajax({
type: 'POST',
url: 'email.php',
dataType: 'html',
data: {
submit_x : 1,
name : name,
enq : enq
},
success: function(html){
$('form#email').fadeOut();
},
error: function(e, xhr) { alert('__a Error: e: ' + e + ', xhr:' + xhr); }
});

Related

Ajax doesn't post data

[SOLVED]
That was THE most difficult bug ever - all due to copy/paste stuff up.
This:
$('#errors'+bUID).append('<ul id="error_list"'+bUID+'></ul>');
should have been that:
$('#errors'+bUID).append('<ul id="error_list'+bUID+'"></ul>');
The damn '+bUID+' was pasted AFTER the " , not BEFORE!
Of course it couldn't append anything to it... 2 weeks...2 WEEKS wasted!!! )))
Here's the js:
$('form').submit(function(e){
bUID = $(this).find('input[name=bUID]').data("buid");
e.preventDefault();
submitForm(bUID);
alert(bUID);
});
function submitForm(bUID) {
var name = $('#name'+bUID).val();
var email = $('#email'+bUID).val();
var message = $('#message'+bUID).val();
var code = $('#code'+bUID).val();
alert(bUID);
// also tried this
var post_data = {
'name': $('#name'+bUID).val(),
'email': $('#email'+bUID).val(),
'message': $('#message'+bUID).val(),
'code': $('#code'+bUID).val(),
'buid': bUID,
};
alert(Object.keys(post_data).length);
// ALSO tried this instead of ajax:
//$.post($('#contact_form'+bUID).attr('action'), post_data, function(response){
alert(response);
$.ajax({
dataType: "json",
type: "post",
data: "name=" + name + "&email=" + email + "&message=" + message + "&code=" + code + "&buid=" + bUID,
//data: post_data,
url: $('#contact_form'+bUID).attr('action'),
success: function(response) {
if (typeof response !== 'undefined' && response.length > 0) {
if (response[0] == "success") {
$('#success'+bUID).append('<p>Success</p>');
}
else {
$('#errors'+bUID).append('<p>' + js_errors + '</p>');
$('#errors'+bUID).append('<ul id="error_list"'+bUID+'></ul>');
$.each(response, function(i, v){
if (i > 0) {
$('#error_list'+bUID).append('<li>' + v + '</li>');
}
});
}
}
}
});
}
here's the action in view.php:
<?php
$bUID = $controller->getBlockUID($b);
$form = Loader::helper('form');
$formAction = $view->action('submit', Core::make('token')->generate('contact_form'.$bUID));
?>
<form id="contact_form<?php echo $bUID; ?>"
class="contact-form"
enctype="multipart/form-data"
action="<?php echo $formAction?>"
method="post"
accept-charset="utf-8">
<?php echo $bUID; ?><br />
<input type="hidden" name="bUID" data-buid="<?php echo $bUID; ?>" data-popup="<?php echo $popup; ?>">
...etc.
and here's the controller.php:
public function action_submit($token = false, $bID = false)
{
$this->form_errors = array();
array_push($this->form_errors, "error");
array_push($this->form_errors, $_POST['name']);
array_push($this->form_errors, $_POST['email']);
array_push($this->form_errors, $_POST['message']);
array_push($this->form_errors, $_POST['code']);
array_push($this->form_errors, $_POST['buid']);
echo Core::make('helper/json')->encode($this->form_errors, JSON_UNESCAPED_UNICODE);
exit;
}
it gets all data and shows it in alert but then trows the following error in the console:
Uncaught TypeError: Cannot use 'in' operator to search for 'length' in ["error","gggg","gggg#gmail.commm","gggggggggggggggggggggggg","gggg","171"]
at r (jquery.js:2)
at Function.each (jquery.js:2)
at Object.success (view.js:132)
at j (jquery.js:2)
at Object.fireWith [as resolveWith] (jquery.js:2)
at x (jquery.js:5)
at XMLHttpRequest.b (jquery.js:5)
Line 132 of the js file is this: $.each(response, function(i, v){
I can't figure out what's wrong. The alert works and returns entered data: "error,gggg,gggg#gmail.commm,gggggggggggggggggggggg,gggg,171‌", but php retruns null objects: "["error",null,null,null,null,null]" - $_POST is empty!
What's wrong here? Why doesn't the form get posted?
Thank you very much.
Have you tried adding return false; to prevent your form from submitting to its desired action?
$('form').submit(function(e){
bUID = $(this).find('input[name=bUID]').data("buid");
//e.preventDefault();
//e.stopPropagation();
submitForm(bUID);
alert(bUID);
return false;
});
Try this way,
function submitForm(bUID) {
var name = $('#name'+bUID).val();
var email = $('#email'+bUID).val();
var message = $('#message'+bUID).val();
var code = $('#code'+bUID).val();
$.post($('#contact_form'+bUID).attr('action'), {name:name, email:email, message:message, code:code, buid:bUID}, function(result){
alert(result);
});
}
Your post_data variable was correct. As it is now your data attribute in your ajax is wrong - it's in GET format (a string), not POST. The correct way (json) is;
$.ajax({
dataType: "json",
type: "post",
data: {
name: nameVar,
email: emailVar,
message: messageVar
},
url: ...,
success: function(data) {
...
}
});
I "renamed" your variables to try and avoid variables with the same names as keys (e.g. you want to post "name", setting a variable "name" might conflict).
Just use
data: form.serializeArray()
Like this:
$.ajax({
url: 'url to post data',
dataType: "json",
method: "post",
data: form.serializeArray(),
success: function(data) {
// another staff here, you can write console.log(data) to see what server responded
},
fail: function(data) {
console.log(data) // if any error happens it will show in browsers console
}
});
Another tips: in server side you can use http_response_code(200) for success, http_response_code(400) for errors, http_response_code(403) if authorisation is required

jQuery gathering inputs without submit

I'm trying to get values from inputs without any action from user and then save it via php to txt file.
This is what I got so far:
var x = setInterval(function() {
var email = $("#test").val();
if(email != '' && email != newemail) {
$('#display').append(email)
$.ajax({
type: "POST",
url: 'inputs-saving.php',
data: ({usremail:email}),
success: function(data) {
}
});
}
var newemail = $("#test").val();
}, 1000);
it works almost fine, but I need to check if value changed, because if I input some text it will be constantly writen in file every second.
I have also tried to add something like "var newemail = email", but can't make it work corectly.
You can do like this
$('#test').on('change',function () {
var email= $(this).val();
if(email != '') {
$('#display').append(email);
$.ajax({
type: "POST",
url: 'inputs-saving.php',
data: ({usremail:email}),
success: function(data) {
}
});
}
});
Here test is the email filed id.
I thing it will help you.
$("input").blur(function(){
//place your logic
});
blur will not trigger every time you change the text, only when you remove focus from that box
There is variable scope problem , Try this:
var newemail = '';
var x = setInterval(function() {
var email = $("#test").val();
if (email != '' && email != newemail) {
$('#display').append(email)
$.ajax({
type: "POST",
url: 'inputs-saving.php',
data: ({
usremail: email
}),
success: function(data) {
currentemail = email;
}
});
}
}, 1000);

PHP - how to retrieve value of input type file on Ajax / JQuery page

I can retrieve input type text, textarea, select on Ajax / JQuery page. Then variable values are passed to PHP process page where data are retrieve using POST method and data inserted into database table. All things are working fine.
But when I try to retrieve value of input type file variable on Ajax / Query page, it is giving blank value. I tried different codes to do it which I found from internet.
Please advise so I can make necessary changes in my script to make it working.
personal_details.php
<form name="AddForm" id="AddForm" novalidate>
<div class="control-group form-group">
.
.
<input type="file" name="file_photo" id="file_photo">
.
.
other fields like Name, Mail etc
.
.
<div id="success"></div>
<!-- For success/fail messages -->
<button type="submit" class="btn btn-primary">Send Message</button>
</div>
</form>
personal_details.js
$(function() {
$("#AddForm input,#AddForm textarea, #AddForm file").jqBootstrapValidation({
preventSubmit: true,
submitSuccess: function($form, event) {
event.preventDefault();
var name = $("input#name").val();
var email = $("input#email").val();
.
.
var file_photo = $("file#file_photo").val();
//var file_photo = $('#file_photo')[0].files[0];
//var file_photo = document.getElementById("file_photo").files[0];
$.ajax({
url: "./user/personal_details_p.php",
type: "POST",
data: {
name: name,
email: email,
file_photo: file_photo,
},
cache: false,
success: function(data)
{
//alert(data);
var $ResponseText_L=JSON.parse(data);
.
.
if condition
.
.
},
})
},
});
personal_details_p.php
$str_name = "";
if (isset($_POST["name"])) { $str_name = trim($_POST["name"]); }
$str_email = "";
if (isset($_POST["email"])) { $str_email = trim($_POST["email"]); }
$str_photo = "";
if(isset($_FILES['file_photo'])) { $str_photo = trim($_FILES['file_photo']['name']); }
.
.
SQL Query to insert data
.
.
$response['status']='SUC';
$response['message']="Data inserted successfully";
echo json_encode($response);
return;
Easy Ajax Image Upload with jQuery, PHP
All textbox, textarea and file type variables will be available on PHP process page with the same name like they have on HTML form page.
I have made my own function for asynchronous upload with progress bar. I will try to write example for you. Also add enctype="multipart/form-data" attribute to your form.
var file_photo = $("file#file_photo").val();
var form = file_photo.parents('form');
file_photo.on('change', processUpload);
var processUpload = function() {
var formData = new FormData(form[0]);
$.ajax({
url: "./user/personal_details_p.php",
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload) {
myXhr.upload.addEventListener('progress', progressHandling, false);
}
return myXhr;
},
success: function(json) {
file_photo.val(''); // Empty file input after upload
},
error: function() {
// Do whatever you want as error message
},
data: formData,
cache: false,
contentType: false,
processData: false
});
};
var progressHandling = function(e) {
if(e.lengthComputable) {
// Uploaded bytes: e.loaded / Maximum bytes: e.total
}
};
you can use https://github.com/blueimp/jQuery-File-Upload. It has various options and its documentation is also good. so if you can use plugin you can go with this
Please Try below code for file upload.
$(function() {
$("#AddForm input,#AddForm textarea, #AddForm file").jqBootstrapValidation({
preventSubmit: true,
submitSuccess: function($form, event) {
event.preventDefault();
var name = $("input#name").val();
var email = $("input#email").val();
// my edit for File upload code starts here
var FileData = $('#file_photo').prop('files')[0];
var form_data = new FormData();
form_data.append('file', FileData);
// my edit for File upload code ends here
$.ajax({
url: "./user/personal_details_p.php",
type: "POST",
data: {
name: name,
email: email,
file_photo: file_photo,
},
cache: false,
success: function(data)
{
//alert(data);
var $ResponseText_L=JSON.parse(data);
.
.
if condition
.
.
},
})
},
});
For accessing file you should have to do like this in jquery:
$(function() {
$("#AddForm input,#AddForm textarea, #AddForm file").jqBootstrapValidation({
preventSubmit: true,
submitSuccess: function($form, event) {
event.preventDefault();
var name = $("input#name").val();
var email = $("input#email").val();
var file_data = $("#file_photo").prop("files")[0];
var form_data = new FormData();
form_data.append("doc_upload", file_data)
var data_text=$('form').serializeArray();
$.each(data_text,function(key,input){
form_data.append(input.name,input.value);
});
$.ajax({
url: "./user/personal_details_p.php",
contentType: false,
processData: false,
data: form_data,
cache: false,
success: function(data)
{
//alert(data);
var $ResponseText_L=JSON.parse(data);
.
.
if condition
.
.
},
})
},
});

How to insert data to database using multiple array using POST method with ajax:

I read similar answer here in this question: How to insert into MYSQL row from multiple $_POST arrays and How to insert into MYSQL row from multiple $_POST arrays but the problem is these answers do not work in my code. Is it because im using an ajax? and i only get the value of the first array.
If i also place the variable declaration inside the for loop it is not working too.
Here is my ajax:
var name = [];
$('input[name="name[]"]').map(function(){ name.push($(this).val()); }); var studid = [];
$('input[name="studid[]"]').map(function(){ studid.push($(this).val()); }); var nameStr = name != '' ? '&name='+ name : '';
var studStr = studid != '' ? '&studid='+ studid : '';
var dataString = 'subject='+ subject + '&section=' + section + studStr + nameStr;
$.ajax({ type: "POST", url: 'save.php', data: dataString, dataType: "html",
success: function(data) {
$('input#subject-field').val('');
$('input#section-field').val('');
$('input.record-input-forms').val('');
$('#status-message').css({"color":"#39b1c6"});
$('#status-message').html('Save successfully',function(){
$('#status-message').fadeOut(2000); }); },
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError); } });
return false;
});
Here is my php:
if(isset($_POST['studid']) || isset($_POST['name'])){
$studid = array_map(mysql_real_escape_string, explode(",",$_POST['studid']));
$name = array_map(mysql_real_escape_string, explode(",",$_POST['name']));
for ($i=0; $i<count($studid); $i++){
$sql_1 = "INSERT INTO tbl_student(StudentID, StudentName, SubjectID) VALUES ('".$studid[$i]."', '".$name[$i]."', LAST_INSERT_ID())";
mysqli_query($con,$sql_1);
}
}
use mysql_insert_id();
instead of LAST_INSERT_ID()
You're not sending data correctly from the jQuery and its seems you'r mixing arrays and string together.
This is a simple request that posts studid-array from jQuery
var saveData = $.ajax({
type: 'POST',
data: {studid: studid},
url: 'save.php',
dataType: 'html'
});
saveData.done(function(data) {
$('input#subject-field').val('');
$('input#section-field').val('');
$('input.record-input-forms').val('');
$('#status-message').css({"color":"#39b1c6"});
$('#status-message').html('Save successfully',function(){
$('#status-message').fadeOut(2000); });
});
saveData.fail(function(ts) {
alert(ts.responseText);
});
When save.php is called, $_POST['studid'] would be set (if there are anything in the array)
If you instead do like this:
var saveData = $.ajax({
type: 'POST',
url: 'save.php?studid=' + studid,
dataType: 'html'
});
When save.php is called, $_GET['studid'] would be set (if there are anything in the array). The best way though is to use data-option in the ajax-function call (in my first case). If you choose to use this option you would have to serialize the stuid-array before putting it in as a part of an url.
UPDATE
If you want to pass multiple arrays you would have to do something like this:
var saveData = $.ajax({
type: 'POST',
data: {studid: studid, name_arr2: data_arr2},
url: 'save.php',
dataType: 'html'
});

undefined variable passing a not check

I'm not really certain where the problem lies but I am passing a variable through ajax and it is not being caught if I pass a blank when I check it with !$varname
Here is my ajax function:
var subscribe = function(){
var dataString = $("#subinput").val();
$.ajax ({
url: '<?php echo $path ?>',
type: 'POST',
data: 'email=' + dataString.value,
datatype: 'JSON',
success: function(results){
if(results.err == '1'){
$('.onconfirmation').css('color','#f00');
}else{
$('.onconfirmation').css('color','#5A5A5A');
}
$('.onconfirmation').innerHTML(results.message);
$('.onconfirmation').fadeIn();
//alert(results);
}
});
and here is my PHP:
<?php
$email = $_POST['email'];
if(!$email){
$o['err'] = '1';
$o['message'] = 'Please do not leave this field blank';
}/*elseif(filter_var($email, FILTER_VALIDATE_EMAIL)){
$o['err'] = '1';
$o['message'] = 'Please enter a valid email address';
}else{
$o['err'] = '0';
$o['message'] = 'Thank you for your subscription';
}*/
ob_start();
var_dump($o);
$out = ob_get_clean();
mail('[REDACTED]','debug',$out);
//$o = json_encode($o);
//return ($o);
?>
As you can see it's in a debugging state at the moment, but if I pass a blank value through into this, the email I am getting is NULL. If I email myself the $email variable instead of the $out variable, the email I get is undefined, but if I remove the ! from the if statement, the email I get is:
array(2) {
["err"]=>
string(1) "1"
["message"]=>
string(36) "Please do not leave this field blank"
}
I'm sure I am just missing something awfully simple, I always am, but I honestly can't figure this one out. Any help would be massively appreciated. Cheers.
var subscribe = function(){
var dataString = $("#subinput").val();
$.ajax ({
url: '<?php echo $path ?>',
type: 'POST',
data: { email : dataString },
datatype: 'JSON',
success: function(results){
if(results.err == '1'){
$('.onconfirmation').css('color','#f00');
}else{
$('.onconfirmation').css('color','#5A5A5A');
}
$('.onconfirmation').innerHTML(results.message);
$('.onconfirmation').fadeIn();
//alert(results);
}
});
see the line
data: { email : dataString }
Once you have the val() you shouldn't use " .value " and when POST-ing data this way is the correct way to add keys and values.
At PHP do those things..
<?php
$o = array();
if(!isset($_POST['email']) OR empty($_POST['email'])){
$o['err'] = '1';
$o['message'] = 'Please do not leave this field blank';
echo json_encode($o);
exit();
}
$email = $_POST['email'];
.......other code
The exit() stops PHP from reading the next lines at your file so IF emial is not set or empty it wont do any further tasks.
Replace this:
var subscribe = function(){
var dataString = $("#subinput").val();
$.ajax ({
url: '<?php echo $path ?>',
type: 'POST',
data: 'email=' + dataString.value,
datatype: 'JSON',
success: function(results){
if(results.err == '1'){
$('.onconfirmation').css('color','#f00');
}else{
$('.onconfirmation').css('color','#5A5A5A');
}
$('.onconfirmation').innerHTML(results.message);
$('.onconfirmation').fadeIn();
//alert(results);
}
});
with this:
var subscribe = function(){
var dataString = $("#subinput").val();
$.ajax ({
url: '<?php echo $path ?>',
type: 'POST',
data: 'email=' + dataString,
datatype: 'JSON',
success: function(results){
if(results.err == '1'){
$('.onconfirmation').css('color','#f00');
}else{
$('.onconfirmation').css('color','#5A5A5A');
}
$('.onconfirmation').innerHTML(results.message);
$('.onconfirmation').fadeIn();
//alert(results);
}
});
val() actually returns the value of an element.
var dataString = $("#subinput").val();
// ...
data: 'email=' + dataString.value,
You used .val() to get the value of #subinput, which is a string. Then, you attempted to read a "value" property of that string, which does not exist. When you concatenate the undefined value with "email=", JavaScript converts it to the string "undefined".
To fix this, you can just change dataString.value to dataString. However, for the sake of those who use the + symbol in their e-mail addresses (especially Gmail users), which your PHP code would interpret as a space, you probably should change the entire line to:
data: {email: dataString},
Passing a JavaScript object with the name-value pairs to jQuery allows it to properly query string escape the +.

Categories