ajax request to test emai - php

I would like to check if an email address exists in ajax but I have a problem with my request.
Here is the html code
<form method="post" action="" id="form_email" class="form_email" >
<label class="form_et">Email <span class="etoile">*</span></label>
<input type="email" id="email" name="email">
<button type="button" id="btn_valider"
onClick="
$(document).ready(function() {
var mail = $('#email').val();
function controler(form) {
var DATA = form;
DATA += 'action=checkMail';
$.ajax({
type: 'POST',
url: 'ajax.php',
data: DATA,
success: function(data){
console.log(data);
}
});
}
controlEmail(mail);
});">Verify</button>
</form>
And my ajax.php
if (isset($_POST['action']) &&$_POST['action'] == "checkMail") {
$test = "test";
return $test;
}
I pass well in the success, if I make a console.log ('success'), it is displayed. But with the current code, console.log (data) returns an empty line in console.
Why does not it work?
If I change the url and add the error function, I go through the error. I do not understand what is happening

return in PHP returns a value from a function. It does not write the value to the output stream (i.e. the HTTP response).
For that you need echo, print or similar.

Related

ajax form submit -> receive respone from php

I've been reading multiple threads about similar cases but even now I'm still unable to do it correctly.
What I want to do
Basically, i.e. I have form which allows user to change his login (simply query to database).
PHP script looks like that:
if(isset($_POST['login'])) {
$doEdit = $user->editData("login", $_POST['login']);
if($doEdit) {
$result = displayInfobox('success', 'Good!');
} else {
$result = displayInfobox('warning', 'Bad!');
}
} else {
$error = 'Bad!';
echo $error;
}
displayInfobox is just a div with class i.e. success and content - Good!.
Right now I would like to send this form by AJAX and display $result without reloading page.
HTML:
<form id="changeLogin" method="post" class="form-inline" action="usercp.php?action=editLogin">
<label for="login">Login:</label><br />
<div class="form-group ">
<input type="text" class="form-control" name="login" id="login" required>
<input type="submit" value="ZmieƄ" class="btn btn-primary">
</div>
</form>
And finnally - my jquery/ajax:
$("#changeLogin").submit(function(e) {
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function(result) {
alert(result);
},
error: function(response) {}
});
e.preventDefault();
});
$("#changeLogin").submit();
If I leave "success" blank, it works -> form is submitted by ajax, login changed, but I do not see the result message. Otherwise whole page get reloaded.
Also, when I hit F5 form is being submited once again (even in Ajax).
I cant add comments because i do not have enough reputation but...
You should delete the last line with $("#changeLogin").submit();
And then in your php script file you should echo the result so you can get this result in ajax request. After that in your success method you have to read the result and (for example) append it somewhere to show the success or error box
I think you can use a normal button instead of submit button,just onclick can be an ajax request, the form should not be submitted,good luck.

Undefined index error in php using ajax

<form role="form" method="post" action="test.php">
<label for="contact">Mobile No:</label><br>
<input type="tel" class="form-control" name="contact" title="Mobile number should not contain alphabets. Maxlength 10" placeholder="Enter your phone no" maxlength="15" required id='contact_no'>
<br><br>
<button type="submit" class="btn btn-success" name="submit" id="submit">Submit</button>
<button type="reset" class="btn btn-default" id='reset'>Reset</button>
</form>
Ajax and Javascript Code
script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var dialcode = $(".country-list .active").data().dialCode;
var contact = $("#contact_no").val().replace(" ","");
var countrycode = $('.country-list .active').data().countryCode;
var cn;
var cc;
var dc;
$.ajax({
url: "test.php",
type: "POST",
data: {'cc' : contact},
success: function(data)
{
alert("success");
}
});
});
});
</script>
The variables show the values if displayed by alert message but are not passed on to the test.php page. It shows undefined index error at the following statement
test.php is as follows
<?php
if(isset($_POST['submit'])){
$contact = $_POST['cc']; //it shows the error here
}
echo $contact;
I had referred to many websites which show the same thing. It dosent work for me. I think the syntz of ajax is correct and have tried all possibilities but still dosent work. Please help
You're posting {cc: contact}, but you're checking for $_POST['submit'] which isn't being sent. The callback also doesn't stop the event, so you might want to return false (stops default and propagation). Something like this should do the trick:
$('#submit').on('click', function()
{
//do stuff
$.ajax({
data: {cc: contact},
method: 'post',
success: function()
{
//handle response here
}
});
return false;
});
Then, in PHP:
if (isset($_POST['cc']))
{
//ajax request with cc data
}
Also not that this:
$("#contact_no").val().replace(" ","");
Will only replace 1 space, not all of them, for that you'll need to use a regex with a g (for global) flag:
$("#contact_no").val().replace(/\s+/g,"");
You are using ajax to form submit
and you use $_POST['submit'] to check it would be $_POST['cc']
test.php
<?php
if(isset($_POST['cc'])){// change submit to cc
$contact = $_POST['cc'];//it shows the error here
}
echo $contact;
#Saty answer worked for me, but my code on ajax was a bit different. I had multiple form data wrapped up into a form variable, that was passed to the php page.
const form = new FormData();
form.append('keywords', keywords);
form.append('timescale', timescale);
form.append('pricing_entered', pricing_entered);
$.ajax({
url: "../config/save_status.php",
data: form,
method: "POST",
datatype: "text",
success: function (response, data) {
}
Then my php was:
if (isset($_POST['data'])) {
// all code about database uploading
}

jQuery Ajax function not working. Php code is working without errors

I was trying to use AJAX to submit form data to a .TXT file using PHP code.
The results are getting added to the text file but AJAX functionality is not working. Please let me know the error in my code.
Here is the Code for the form:
<div id="page-wrapper">
<h1>AJAX Sign Up Form </h1>
<div id="form-messages"></div>
<form id="signup" method="post" action="mailer.php">
<div class="field">
<input type="email" id="email" name="email" placeholder="Enter Your Email" required>
</div>
<div class="field">
<button type="submit">Send</button>
</div>
</form>
Here is the jquery(2.1.1) code
$(document).ready(function() {
$("#sign_btn").click(function(event){
var mail = $("#mail").val();
$.ajax({
type: "POST", // HTTP method POST or GET
url: "mailer.php", //Where to make Ajax calls
data: mail
})
.done (function(data) { $('#form-messages').html(data) })
.fail (function() { $('#form-messages').append("Opps!An Error Occured.Try Again</p>")});
});
});
Here is the mailer.php
<?php
$email = $_POST["email"];
$fp = fopen("signup.txt", "a");
$savestring = "$email\n";
fwrite($fp, $savestring);
fclose($fp);
echo "<h1>Thank You For Subscribing</h1>";
?>
Instead of
data: mail
use
data: {email: mail}
because, in PHP you're looking for $_POST["email"] which means, $_POST array has a key named email with some value.
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
Send your data (as a object) above in my code
Thanks
You can go with any of the folowing :
only if mail is an object that has all the input of a form like
var mail = new FormData($(this)[0]); // on form submit ofcourse
$.ajax({
type: "POST", // HTTP method POST or GET
url: "mailer.php", //Where to make Ajax calls
data: mail
})
.done (function(data) { $('#form-messages').html(data) })
.fail (function() { $('#form-messages').append("Opps!An Error Occured.Try Again</p>")});
if you want to send a single variable via ajax to php then give the data its key so that you can access it by that key in php like this
$.ajax({
type: "POST", // HTTP method POST or GET
url: "mailer.php", //Where to make Ajax calls
data: "mail=" + mail,
})
.done (function(data) { $('#form-messages').html(data) })
.fail (function() { $('#form-messages').append("Opps!An Error Occured.Try Again</p>")});
The button id is missing in the form code...

Send single input with ajax/jquery/php

I'm new to jQuery / AJAX.
I'm trying to send single input with jquery/ajax/php.
LIVE EXAMPLE
But, after pressing submit nothing is happening, where is my error?
Any help much appreciated.
HTML:
<form action="submit.php">
<input id="number" name="number" type="text" />
<input id="submit" name="submit" type="submit" />
</form>
JQUERY / AJAX:
$(document).ready(function(e) {
$('input#submit').click(function() {
var number = $('input[name=number]');
var data = 'number=' + number.val();
$.ajax({
url: "submit.php",
type: "GET",
data: data,
cache: false,
success: function(html) {
if (html == 1) {
alert('wyslane');
}
else {
alert('error');
}
}
});
return false;
});
});
PHP:
<?php
$mailTo = 'email#gmail.com';
$mailFrom = 'email#gmail.com';
$subject = 'Call Back';
$number = ($_GET['number']) ? $_GET['number'] : $_POST['number'];
mail($mailTo, $subject, $number, "From: ".$mailFrom);
?>
HTML:
<form id=submit action="">
<input id="number" name="number" type="text" />
<input name="submit" type="submit" />
</form>
The action URL is irrelevant as you want to submit your data via AJAX. Add the submit id to the form and override the default submit behavior, instead of overriding the onclick handler of the submit button. I'll explain in the JS section.
JS:
var number = $('input[name="number"]');
Quotes were missing.
$(document).ready(function(e) {
$('#submit').submit(function() {
var number = $('input[name=number]');
var data = 'number=' + number.val();
$.ajax({
url: "submit.php",
type: "GET",
data: data,
cache: false,
success: function(html) {
if (html == 1) {
alert('wyslane');
}
else {
alert('error');
}
}
});
return false;
});
});
I don't really understand your success callback, why do you expect that html should be equal to 1?
Atleast I got 404 error when pressed your submit button:
Not Found
The requested URL /index.php was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
When you get it to work, remember to add mysql_real_escape_string function to avoid SQL injections http://php.net/manual/en/function.mysql-real-escape-string.php
Since you are also using ID for number, you could just use: var data = 'number=' + $('#number').val()
Also if you add ID to your form, you can use:
$('#formId').submit(function(){
});
instead of that click. This function will launch when that form is submitted. This is better way because users can submit the form with other ways aswell than just clicking the submit button (enter).
var number = $('input[name=number]');
is wrong. It's
var number = $('input[name="number"]');

Jquery submit() html form based on php script's return value

Ok, if somebody could take a look at this, I'd really appreciate it. I'm implementing a captcha in an html form. The captcha is php based, so i need to use jquery to post the submitted form to the captcha check script.
The php script returns 1 if the check was correct, or 0 if it was incorrect.
This is all working great, the problems i am having are with actually submitting the form, or preventing it based on what the php script returns. My the code is as follows:
<form id="contactform" action="FormHandler.cgi" method="POST">
<input name="requiredContact" size="25" type="text" />
<input name="requiredEmailFrom" size="25" type="text" />
<input name="requiredTelephone" size="18" tabindex="3" />
<textarea cols="25" name="comments" rows="4"></textarea>
<select length="2" name="requiredContactMethod" tabindex="5">
<option selected="" value="Email">Email</option>
<option value="Telephone">Telephone</option>
</select>
<img src="captcha/captcha.php" style="float:none; margin:0px 0px -8px 0px; height:26px;"></img>
<input type="text" id="CAPTCHA" style="margin-left: -5px; height:26px;">
<p id="caperror"></p>
<p><input name="B1" type="submit" value="Submit" />
<input name="B2" type="reset" value="Clear" /></p>
</form>
<script>
$('#contactform').submit(function(){
var cap = $('#CAPTCHA').val();
cap = 'CAPTCHA=' + cap;
$.ajax({
type: 'POST',
url: 'captcha/capcheck.php',
data: cap,
dataType: "text",
error: postfail,
success: success
});
return false; //Temporary, to stop the form no matter what.
});
function success(result){
if(result == 1){
alert('was correct');
return true;
}
else{
alert("error" + result);
return false;
}
}
function postfail(){
alert('post failed');
return false;
}
</script>
So what i would like to happen, is when my success function returns false, it stops the form from submitting. If it returns true, go ahead and submit the form. This is what I would like
$('#contactform').submit(function(){
//The ajax post here
//check the value of the ajax success function here;
if(success(result)) {
return true;
}
else {
return false;
}
});
I am not good with function scopes in javascript. If I define a variable inside the success function, I can't check the value in the form submit function, because it only has a local scope. I could just use a link to submit the form, and then call submit(); but I want the form to be accessible to those without java.
Is there any way to get the ajax post success function's result back to the scope of the submit() handler?
Unless I'm missing something, you should be submitting the form in the AJAX call's success function. The AJAX call should also not be being thrown upon form submit. The form should not be being submitted in any way until the check has come back true. IE:
$.ajax(
//Parameters and stuff
).success(function() {
//Submit the form
$('#contactform').submit();
}).fail(function() {
//Onoes your call has failed. Do not submit le form :(
});
As far as "scoping" goes, this shouldn't be a "scoping" issue. Let me know if you need further instruction.
I would write the function like this only setting submitForm on a 1 result.
$('#contactform').submit(function(){
var submitForm = False;
var cap = $('#CAPTCHA').val();
cap = 'CAPTCHA=' + cap;
$.ajax({
type: 'POST',
url: 'captcha/capcheck.php',
data: cap,
dataType: "text",
success:function(result){
if(result == 1){
submitForm = True;
}
}
});
return submitForm;
});
I was going to suggest that in your success function you call $('#contactform').submit(), but that would just call your event handler again and you'd be stuck in a loop.
What instead you can do is call the form element's submit function, like this:
$('#contactform').submit(function(){
var cap = $('#CAPTCHA').val();
cap = 'CAPTCHA=' + cap;
myform = this; // added this line
$.ajax({
type: 'POST',
url: 'captcha/capcheck.php',
context: myform, //added this line
data: cap,
dataType: "text",
error: postfail,
success: success
});
return false; //Temporary, to stop the form no matter what.
});
function success(result){
// because we added the context option, we can now access the form with the "this" keyword
if(result == 1){
alert('was correct');
// $('#contactform').submit() // this will make an infinite loop
this.submit(); // this will submit the form
return true;
}else{
alert("error" + result);
return false;
}
}
Try making the ajax call on the submit button click not on the form submit.
If the return of the click call is true, you call the submit function.

Categories