I have some validation code something like this -
if ($('#address').val()) {
if ($('#address').val().length > 60 || $('#address').val().length < 5) {
errorMessage += "Length of Your Address must be between 5 and 60.\n";
valid = false;
} else {
var rege = /^[a-zA-Z]([0-9a-z_\s])+$/i;
if(!rege.test($('#address').val())){
errorMessage += "Please enter Valid Address.\n";
valid = false;
} else {
var address = $('#address').val();
//alert ('My address is : ' + address);
}
}
} else {
errorMessage += "please enter your address\n";
valid = false;
}
My problem is how I get this value to php. My value have here - var address = $('#address').val();
I need to check this value again in PHP and need to echo the value on the same page.
I use it something like this -
if( !valid && errorMessage.length > 0){
alert(errorMessage);
} else {
$.ajax({
type: "POST", // HTTP method POST or GET
url: "demo2.php", //Where to make Ajax calls
data: {
myname: name,
myaddress: address,
myemail: email
}
});
}
demo2.php page is the same page which my form have.
Above of my page I tried to print $_POST array but nothing display there.
echo '<pre>', print_r( $_POST).'</pre>';
Hope someone will help me.
Thank you.
First put a check in demo2.php for if POST is set
if( isset($_POST['myaddress']) ) {
// your echo statement here
}
Then you just need to add some code to the jquery handle the response.
if( !valid && errorMessage.length > 0){
alert(errorMessage);
} else {
$.ajax({
type: "POST", // HTTP method POST or GET
url: "demo2.php", //Where to make Ajax calls
data: {
myname: name,
myaddress: address,
myemail: email
}
}).done(function(response) {
$('#address-display-div').html(response);
});
}
replacing #address-display-div with whatever selector you're going to display the address in.
Request page:
var request =$.ajax({
type: "POST",
url: "demo2.php",
data: {myname: name,myaddress: address,myemail: email}
dataType: "json",
success: function (a) {
alert(a[0]);
}
});
request.fail(function(jqXHR, textStatus){alert('Ajax Error: '+ textStatus);});
And in your php file:
<?php
if(isset($_POST['myname']) && isset($_POST['myaddress']) && isset($_POST['myemail'])){
[do your stuff]
echo json_encode(array(0=>'<pre>'.print_r( $_POST,true).'</pre>'));
}
else
echo json_encode(array(0=>'Missed Variable'));
exit();
?>
Otherwise can you also post your php page?
Related
I have this ajax function for login.
Edit: I just noticed that this server runs php7 while other server where the login does work uses php5. What has changed in php that this script doesn't work anymore?
Edit 2: Looks like the server request method isn't post but changed to get, why?
Solution: needed to remove the .php from url: "./ajaxcall/login.php", because I use pretty url htaccess.😅
var InName = $('#InName').val();
var InPass = $('#InPass').val();
alert(InName);
$.ajax({
type: "POST",
url: "./ajaxcall/login.php",
dataType: "json",
data: {InName:InName, InPass:InPass},
error: function (request, error) {
console.log(arguments);
alert("Inlog Can't do because: " + error);
},
success : function(data){
if (data.code == "200"){
$("#InErEr").html(data.msg);
//window.location.reload(true);
} else {
$("#InErEr").html(data.msg);
$('.lds-dual-ring').animate({opacity: 0}, 300);
}
}
});
On the alert(InName); I get the correct value of the username. But when I check in my php file $_POST['InName'] it is empty.
Part of php file
include('../config.php');
if(empty($_POST['InName'])) {
$Ierror = 'Username is required.';
}
if($_POST['InPass'] == '') {
$Ierror = 'Password is required.';
}
$username = $_POST['InName'];
$passwordL = $_POST['InPass'];
// count user in between //
if($Inlognumber_of_rows == 0) {
$Ierror = 'Username not found.';
} else {
// password check //
if(password_verify($salty_pass, $hashed_password)) {
} else {
$Ierror = 'Password incorrect.';
}
}
if ($Ierror == '') {
// do login //
} else {
$showerror = '<span style="color:#F00;">'.$Ierror.$username.$passwordL.$_POST['InName'].$_POST['InPass'].'</span>';
echo json_encode(['code'=>404, 'msg'=>$showerror]);
exit;
}
In the return message, $showerror I only get, Username not found, without the posted values. So the login is not working because of empty values? User is also present in the database of course. I also don't get the empty $_POST errors. So to cap up, in javascript I get the correct value for InName but not in php.
You are close but your error catch is not correct ... try this (Jquery):
var InName = 'something';
var InPass = 'morething';
$.post("./ajaxcall/login.php", {
InName: InName,
InPass: InPass
}, function(data, status) {
console.log(data, status);
}).done(function() {
alert("second success");
})
.fail(function() {
alert("error");
})
.always(function() {
alert("finished");
});
on your php file just do print_r($_POST); and you will receive this in your console...:
Array
(
[InName] => something
[InPass] => morething
)
success
Basically you were trying to print the error where you should have consoled log the request.responeText...
A good trick to know if posts arrived to the php even if the console.log won't show is doing this in the php file:
<?php
print_r($_POST) ;
$newfile = fopen('newfile.txt','a');
fwrite($newfile,json_encode($_POST));
fclose($newfile);
This will print and also store on a local file the post data....
Solution: needed to remove the .php from url: "./ajaxcall/login.php", because I use pretty url htaccess.😅
I wanna make header location like stackoverflow system has. After posting, it will load the page based on lastinsertid. I tried to use php, it works, but I wanna change it using ajax jquery because of its single page. Could I use ajax jquery in this case? how to make it work?
here's the code :
PHP
if($sumn>0 && $sump>=0) {
echo "banned";
}
else if($sumn==0 && $sump<=3) {
echo "oot";
}
else{
$insert=$db_con->prepare("INSERT INTO tb_post (id_user,title,description,created_date) VALUES(:id_user,:title,:description,NOW())");
$insert->bindParam(":id_user",$id_user);
$insert->bindParam(":title",$title);
$insert->bindParam(":description",$description);
$insert->execute();
$id_post=$db_con->lastInsertId();
if ($insert->rowCount()>0) {
$post = $db_con->prepare("SELECT * FROM tb_post WHERE id_post=:id_post");
$post->execute(array(":id_post"=>$id_post));
$row=$post->fetch(PDO::FETCH_ASSOC);
$title = clean_url($row['title']);
$detail ="../discuss/".$row['id_post']."/".$title;
header("location:$detail");
echo 'success';
}else {
echo 'fail';
}
ajax jquery
$.ajax({
url: 'create_process.php?page=send_post',
type: 'post',
data: 'title='+title+'&description='+description,
success: function(msg){
if(msg=='success') {
window.location='/'; //This the problem.. need to know how to use header location based on lastinsertid
}
else if(msg=='banned') {
$("#dis-mes").html('<div class="allert alert-danger">Banned</div>');
}else if(msg=='oot'){
$("#dis-mes").html('<div class="allert alert-danger">OOT</div>');
}else {
alert('failed');
}
}
});
instead of using a header, you should return the redirect url in the response.
the php response should be a json string like this :
{
status: "success",
url: "../discuss/".$row['id_post']."/".$title
}
in the javascript just check the content of msg.status and use msg.url in your window.location
If you still want to use headers, you can use this in your success function:
success: function(msg, textStatus, request){
if (msg == 'success') {
window.location = request.getResponseHeader('location'));
}
},
I am building an inline code validation for a web form. With my current script, When a bad code is entered and it is being corrected (same length), POST data is not using the latest value. For example, I first enter "QFFE" and then correct it to "QFFF", but the latter is not stored in $_POST. See Firebug extract ("QFFF" passed but "QFFE" processed):
Here is the code (AJAX part):
var data = {};
$(document).ready(function() {
$('input[type="submit"]').on('click', function() {
resetErrors();
var url = 'process.php';
$.each($('form input, form select'), function(i, v) {
if (v.type !== 'submit') {
data[v.name] = v.value;
}
}); //end each
console.log(data);
$.ajax({
dataType: 'json',
type: 'POST',
url: url,
data: data,
cache: false,
success: function(resp) {
if (resp === true) {
//successful validation
alert("OK, processing with workflow...");
// $('form').submit();
return false;
} else {
$.each(resp, function(i, v) {
console.log(i + " => " + v); // view in console for error messages
var msg = '<label class="error" for="'+i+'">'+v+'</label>';
$('input[name="' + i + '"], select[name="' + i + '"]').addClass('inputTxtError').after(msg);
});
var keys = Object.keys(resp);
$('input[name="'+keys[0]+'"]').focus();
console.log('QD: error val');
}
return false;
},
error: function() {
console.log('there was a problem checking the fields');
}
});
return false;
});
});
function resetErrors() {
$('form input, form select').removeClass('inputTxtError');
$('label.error').remove();
}
And here my PHP script (process.php):
<?php
//List of accepted codes
$code_list = array("QWOLVE", "QFFF");
session_start();
if(isset($_POST)){
if (empty($_POST['promo_code'])) {
$_SESSION['errors']['promo_code'] = 'Please enter a promo code to access the beta site';
}elseif(! in_array($_POST['promo_code'], $code_list)){
$_SESSION['errors']['promo_code'] = $_POST['promo_code']." is not a valid code";
unset($_POST);
}
if(count($_SESSION['errors']) > 0){
//This is for ajax requests:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo json_encode($_SESSION['errors']);
// header('Location: redirect.php');
exit;
}
//This is when Javascript is turned off:
echo "<ul>";
foreach($_SESSION['errors'] as $key => $value){
echo "<li>" . $value . "</li>";
}
echo "</ul>";exit;
}else{
//Form validation successful - process data here:
echo json_encode(true);
}
}
?>
How can I make sure that the process.php is always using the latest form data?
I'm not sure why you store errors in the the session, but since you don't seem to clear that session, the next time you call the POST method $_SESSION['errors'] will still have the previous error in it (QFFE), hence the output.
This is a mailing list script. It works by itself without jquery but I am trying to adapt it to work with ajax. However, without success. When the $.sql part is commented out it returns the variables in the url string successfully. However, when I uncomment that part of the js file and introduce the PHP into things it simply refreshes the page with the email address still in the input box. By itself, the PHP works so I'm at a loss as to where I'm going wrong. Here's what I have... any help would be appreciated.
Form :
<form name="email_list" action="" id="maillist_form">
<p><strong>Your Email Address:</strong><br/>
<input type="text" name="email" id="email" size="40">
<input type="hidden" name="sub" id="sub" value="sub">
<p><input type="submit" value="Submit Form" class="email_submit"></p>
</form>
JQuery :
$(function() {
$('#maillist_form').submit(function() {
var email = $("input#email").val();
if (name == "") {
$("input#email").focus();
return false;
}
var sub = $("input#sub").val();
if (name == "") {
$("input#sub").focus();
return false;
}
var dataString = $("#maillist_form").serialize();
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "mailing_list_add2.php",
data: dataString,
success: function() {
$('#display_block')
.hide()
.fadeIn(2500, function() {
$('#display_block');
});
}
});
return false;
});
});
PHP :
<?php
// connects the database access information this file
include("mailing_list_include.php");
// the following code relates to mailing list signups only
if (($_POST) && ($_POST["sub"] == "sub")) {
if ($_POST["email"] == "") {
header("Location: mailing_list_add2.php");
exit;
} else {
// connect to database
doDB();
// filtering out anything that isn't an email address
if ( filter_var(($_POST["email"]), FILTER_VALIDATE_EMAIL) == TRUE) {
echo '';
} else {
echo 'Invalid Email Address';
exit;
}
// check that the email is in the database
emailChecker($_POST["email"]);
// get number of results and do action
if (mysqli_num_rows($check_res) < 1) {
// free result
mysqli_free_result($check_res);
// cleans all input variables at once
$email = mysqli_real_escape_string($mysqli, $_POST['email']);
// add record
$add_sql = "INSERT INTO subscribers (email) VALUES('$email')";
$add_res = mysqli_query($mysqli, $add_sql)
or die(mysqli_error($mysqli));
$display_block = "<p>Thanks for signing up!</p>";
// close connection to mysql
mysqli_close($mysqli);
} else {
// print failure message
$display_block = "You're email address - ".$_POST["email"]." - is already subscribed.";
}
}
}
?>
I won't put the include code in here because I'm assuming it is correct - unless the introduction of the jquery means this needs to be adapted as well.
Your AJAX is not catching back the result:
$.ajax({
type: "POST",
url: "mailing_list_add2.php",
data: dataString,
success: function(response) {
$('#display_block')
.hide()
.fadeIn(2500, function() {
$('#display_block').html(response); //just an example method.
//Are you sure the selector is the same?
//Can also be $(this).html(response);
}
});
And as noted by gdoron, there's no "name" variable. Maybe you meant "email" and "sub", respectively?
PHP response, also, isn't echoed back. Just put:
echo $display_block;
You don't echo an data from the server, not trying to get data in the success callback, and the fadeIn callback just have a selector,.
You check for the wrong variable:
var email = $("input#email").val();
if (name == "") { // Didn't you mean email?
$("input#email").focus();
return false;
}
var sub = $("input#sub").val();
if (name == "") { // Didn't you mean sub?
$("input#sub").focus();
return false;
}
How can it work!?
I have created a registration system that uses AJAX to process the form so that I can return false. The relevant js is the top block of code. I pass this data to join.php, which sends it to the database. I run a check in join.php to make sure that nobody with a duplicate email has already signed up. As you can see, if the email already exists, I want to insert a message using javascript. Instead of reading the script tags, it simply pastes them into my alert in plaintext...so my alert has the datastring and then actually says the code <script>...</script>. How can I get this js to process instead?
Javascript:
$(".submit").click(function() {
var dataString = {
school : $("#school").val(),
studentEmail : $("#studentEmail").val(),
studentPassword : $("#studentPassword").val(),
parentEmail : $("#parentEmail").val(),
parentPassword : $("#parentPassword").val(),
studentFirstName : $("#studentFirstName").val(),
studentLastName : $("#studentLastName").val(),
studentPhone : $("#studentPhone").val(),
parentFirstName : $("#parentFirstName").val(),
parentLastName : $("#parentLastName").val(),
parentPhone : $("#parentPhone").val()
};
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function(data) {
alert ("data sent: "+ data);
}
});
return false;
}
});
join.php
if($_POST) {
$school = mysql_real_escape_string($_POST['school']);
$studentEmail = mysql_real_escape_string($_POST['studentEmail']);
$parentEmail = mysql_real_escape_string($_POST['parentEmail']);
$studentFirstName = mysql_real_escape_string($_POST['studentFirstName']);
$studentLastName = mysql_real_escape_string($_POST['studentLastName']);
$studentPhone = mysql_real_escape_string($_POST['studentPhone']);
$parentFirstName = mysql_real_escape_string($_POST['parentFirstName']);
$parentLastName = mysql_real_escape_string($_POST['parentLastName']);
$parentPhone = mysql_real_escape_string($_POST['parentPhone']);
$check = mysql_query("SELECT studentEmail FROM clients WHERE studentEmail = '{$studentEmail}';");
$num = mysql_num_rows($check);
if (($num) == 0) {
$sql = "INSERT INTO clients ".
"(`studentEmail`, `studentPassword`, `parentEmail`, `parentPassword`, ".
"`studentFirstName`, `studentLastName`, `studentPhone`, `parentFirstName`, ".
"`parentLastName`, `parentPhone`, `school`) ".
" VALUES ('$studentEmail', '$studentPassword', '$parentEmail', ".
"'$parentPassword', '$studentFirstName', '$studentLastName', ".
"'$studentPhone', '$parentFirstName', '$parentLastName', '$parentPhone', '$school')";
$result = mysql_query($sql);
if ($result) {
echo "Database query successful!";
}
else {
die("Database query failed: " . mysql_error());
}
include "emails/signUp.php";
}
else {
echo 'FAIL
<script>
$(".formErrorMessage").html("Email already exists");
</script>';
}
}
The alert shows your script block because you've got this in your success handler:
alert ("data sent: "+ data);
Data is going to be whatever text you output in your PHP. If you want to have variable behavior based on whether your request was successful or not, I'd recommend that your PHP returns JSON containing a success flag and the message. Your JavaScript callback would then look like this:
function(data) {
if (data.success) {
alert ("data sent: "+ data.message);
} else {
$(".formErrorMessage").text(data.message);
}
}
Your PHP should then change your content-type to JSON:
header('Content-Type: application/json');
... and your echos would change to something like this:
echo '{"success": false, "message": "Email already exists."}';
Your server call shouldn't be returning raw HTML. Should return JSON that contains all the status information the server needs to handle things. i.e. in the usual case:
{'success': true}
or
{'success': false, 'emailAlreadyExists': true, 'msg': 'Email Already Exists'}
of
{'success': false, 'msg': 'Database query failed: blahblahMySqlError'}
Then your client JS should handle it...
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function(data) {
if(data.success) {
alert ("success!");
}
else{
alert("error: " + data.msg);
if(data.emailAlreadyExists){
$(".formErrorMessage").html("Email already exists");
}
}
}
});
from php, you have give formatted status responses
on success:
echo '{"status":"success", message:"Database query successful!"}';
if account already exists:
echo '{"status":"failed", message:"Email already exists"}';
So you will be able to identify this in JavaScript callback function
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function(data) {
if(status.error == "failed"){
$(".formErrorMessage").html(data.message);
}
}
});
This is the best way to do it. Or if you just want to execute a string received from php, you can use eval
success: function(data) {
eval(data);
}
In that case there is no need of script tags in response, only the Javascript statement that has to be executed.