undefined variable passing a not check - php

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 +.

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

$_Post failing (Sending Ajax)

Can someone please show me the correct way I can add these two lines of code
data: {name: info, me: '<?php echo $me; ?>'},
data: dataString ,
So that I can send them in a $_POST to my action.php , I have tried several ways to do this but cannot get both of them successfully to be passed on to my action_comments.php I understand I'm missing something possible when using data: below or have not correctly formatted my code . I'm a total beginner with very little experience so sorry if I lack good practice but hopefully can be better from my debugging . Thanks to anyone who helps me get passed this .
Here is complete code to give overview what Im doing
<script type="text/javascript">
$(function() {
// call the submit button ref: name
$(".submit_button").click(function() {
declare textcontent
var textcontent = $("#content").val();
//dataString = 'content' globel var
var dataString = 'content='+ textcontent;
declare info
var info = $('#name').val();
// option no text inputted
if(textcontent=='')
{
// show message if no text
alert("Enter some text..");
$("#content").focus();
}
else
{
//display text animation loading
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
//var info equals the string
var info = $('#content').val();
//start ajax call
$.ajax({
type: "POST",
//path to my action.php
url: "actions/action_comment.php",
//Need to undestand how to correctly format these lines so
//they are both succesful when submitted to my action_comment.php
$me is declared (not-shown here it holds integer)
data: {name: info, me: '<?php echo $me; ?>'},
// pass the string from textarea to $_POST
data: dataString ,
// I can get one or the other to work but not both
cache: true,
// feed the success my data
success: function(html){
$("#show").after(html);
document.getElementById('content').value='';
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
I have my $_POST as follows in action_comment.php
echo $me = $_POST['me'];
//DATASTRING FROM TEXTAREA
echo $content= $_POST['content'];
var dataString = 'content='+ textcontent;
$.ajax({
type: "POST",
url: "actions/action_comment.php",
data: {name: info, me: '<?php echo $me; ?>',txt_data: dataString},
....
});
Cannot use data attribute multiple times in same ajax request. Within php file you can access like $_POST['txt_data'] to get textarea content and same way for other parameters;
define data attribute once and pass all the data like as shown above.
if you want to post whole form data you can use this way
var form = $('#my_form');
$.ajax( {
type: "POST",
url: form.attr( 'action' ),
data: form.serialize(),
..
..
});

Error when using jQuery Ajax POST (json) with php

On page load I use this code to display data from database:
<script>
$(function feed(){
var page = 1;
var type = '<?php echo $filter ;?>';
var theData = {};
theData['page'] = 'profile';
theData['type'] = type;
theData['username'] = '<?php echo $user_data->username; ?>';
theData['get_activities'] = 'true';
$.ajax({
type: "POST",
url: "data.php",
data: theData,
dataType:'json',
success: function(data){
$("#activities").html(data.activity_feed);
if(page < data.total_pages){
$("#activities").after('<div id="loader"><button id="load_more_activities">Load more</button></div>');
}
}
});
$("#activity_container").on("click", "#load_more_activities", function(){
var next = page+=1;
var type = '<?php echo $filter ;?>';
var theData = {};
theData['page'] = 'profile';
theData['type'] = type;
theData['username'] = '<?php echo $user_data->username; ?>';
theData['get_activities'] = 'true';
theData['page_num'] = next;
$.ajax({
type: "POST",
url: "data.php",
data: theData,
dataType: "json",
success: function(data){
$("#activities").append(data.activity_feed);
if(next == data.total_pages){
$("#loader").html("No more data");
} else {
$("#loader").html('<div id="loader"><button id="load_more_activities">Load more</button></div>');
}
},
});
});
});
</script>
Everything work fine, but if I refresh page more than 5 or 6 times or if load_more_activities function is called more than 5 or 6 times...then post is not executed and I don't get any data displayed...
Is something wrong with this code or there are maybe some restrictions from my host provider?
When post is executed:
When post is not executed:
My host provider has a protection from several sending ajax data with variables named "username" or "password". So when this happens, server detect some kind »brute-force« and then drop-all-packets.

How to get the values from a $.ajax using 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); }
});

Categories