Difficulty processing data from jQuery post to pg_query(); - php

Having the following difficulty.
I'm currently creating a form. This form is made in HTML and controlled by jQuery.
The form code is as following;
<div id="form">
<form>
<label>ID :</label>
<input type="text" id="clientid" /><br /><br />
<label>Name :</label>
<input type="text" id="name" /><br /><br />
<label>IP Address :</label>
<input type="text" id="ipaddress"/><br /><br />
<label>Status :</label>
<input type ="text" id ="status" />
<input type="button" id="button" value="Insert" /><br /><br /><br />
<label id="response"></label>
</form>
Now, this form picks up user data, and gets processed by the following jQuery script;
// Start jQuery script
// jQuery for dynamic adding without complete page reloads
//Wait for document readiness
$('document').ready(function() {
// Define submit button and action
$('#button').click(function() {
// Assign variable
if ($('#clientid').val() == "") {
alert("Enter Client ID");
return false;
} else {
var clientid = $('#name').val();
}
// Assign variable
if ($('#name').val() == ""){
alert("Enter Client full name");
return false;
} else {
var name =$('#name').val();
}
// Assign variable
if ($('#ipaddress').val() == "") {
alert("Enter Client owned IP address");
return false;
} else {
var ipaddress = $('#ipaddress').val();
}
// Assign variable
if ($('#status').val() == "") {
alert("Enter client status");
return false;
} else {
var status = $('#status').val();
}
// When variables are known, continue processing and POST'ing
// Posting to seperate PHP file to complete
jQuery.post("processing/addC.php", {
clientid: clientid,
name: name,
ipaddress: ipaddress,
status: status
},
function(data, textStatus) {
if (data == 1) {
$('#response').html("Insert successful!");
$('#response').css('color', 'green');
} else {
$('#response').html("Insertion failure. Please try again or restart.");
$('#response').css('color', 'red');
}
});
});
});
This code obviously passes the variables through a POST to addC.php.
addC.php contains the following code:
<?php
// Get current connection
include 'dbconnect.php';
$clientid = $_POST['clientid'];
$name = $_POST['name'];
$ipaddress = $_POST['ipaddress'];
$status = $_POST['status'];
$query = pg_query_params(
$dbconnection,
'INSERT INTO clients(clientid, name, ipaddress,status) VALUES ($1, $2, $3, $4);',
array($clientid, $name, $ipaddress, $status)
);
if(pg_affected_rows($query)>0){
echo "1";
}else{
echo "2";
}
?>
The desired result of this code is the if-statement returning a 1, so the jQuery can create a nice green message saying the database insertion went correct.
Now, as I validated the pg_query(); syntax to be correct, there must be something wrong in this code itself. What seems to be the problem here?
EDIT:
Following error;
Warning: pg_query_params(): Query failed: ERROR: invalid input syntax for integer: "michael" in /Applications/XAMPP/xamppfiles/htdocs/LoginHQ/processing/addC.php on line 18

invalid input syntax for integer: "michael"
It means that column has type integer, but you try insert string

Related

Contact form - Passing variables from PHP to jQuery

[I suspect the issue at hand has to do with how the php array gets passed to jQuery, if that isn't the case I apologize for the misleading title]
The contact form below is working -- except when I submit the forms' data, sometimes one field always keeps its red border indicating missing input, even when it actually has data.
To elaborate: I have a working php-only solution but on submit it causes a page-reload which I would like to avoid. After some research, it seems I need php/jQuery/ajax to perform these things asynchronously and to stay on the same site.
Desired behaviour:
So there are three required input fields called name, email and message, if any one is left out, it should receive a red border and no email gets sent.
Actual behaviour:
If for example only name and message are filled out and submitted, the empty email field is colored red.
But if a (valid) email is provided, the second submit action does not remove the red border around the email field.
I know that javascript and friends is a client-side language, and PHP gets processed server-side. Once the form is submitted, the .ajax function takes the serialized form values, uses 'POST' to stuff it into the php script and waits for the server to call us back inside .done()
This is where I'm lost - how is the php array to be used in jQuery?
E.g. no matter what, this line is never reached:
console.log("All fields filled and valid");
index.html:
<!DOCTYPE html>
<head>
<meta http-equiv="content-type" content="text/html" charset="UTF-8" />
<script src="jquery-1.12.4.min.js"></script>
<script src="verify.js"></script>
<style>
.input-error
{
border: 2px solid red;
}
</style>
<script>
$(document).ready(function() // Wait until website (DOM) is completely loaded
{
/* Page top */
$('#pagetop').click(function()
{
console.log(this);
$('body, html').animate({scrollTop: '0px'}, 600);
return false;
});
});
</script>
</head>
<body>
<!-- action is left blank as process.php is called from verify.js -->
<form action="" method="POST" id="contactForm">
<label for="company">Company</label>
<br>
<input type="text" style="width: 904px; height: 24px;" id="company" name="company" value="">
<br><br>
<label for="name">Name *</label>
<br>
<input type="text" style="width: 904px; height: 24px;" id="name" name="user_name" value="">
<br><br>
<label for="email">Email *</label>
<br>
<input type="text" style="width: 904px; height: 24px;" id="email" name="user_email" value="">
<br><br>
<label for="message">Message *</label>
<br>
<textarea style="width: 904px; resize: none;" rows="9" id="message" name="user_message"></textarea>
<br><br>
<input type="submit" id="submit" name="submit" value="Send">
<br><br>
</form>
</body>
verify.js
$(document).ready(function()
{
// process the form
$('#contactForm').submit(function(event)
{
//$('#name, #email, #message').removeClass('input-error');
// process the form
$.ajax(
{
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : $('#contactForm').serialize(),
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data)
{
// log data to the console so we can see
console.log(data);
if (data.errors.name)
{
console.log("Name missing");
$('#name').addClass('input-error');
}
else
{
$('#name').removeClass('input-error');
}
// handle errors for email
if (data.errors.email)
{
console.log("Email missing or invalid");
$('#email').addClass('input-error');
}
else
{
$('#email').removeClass('input-error');
}
// handle errors for message
if (data.errors.message)
{
console.log("Message missing");
$('#message').addClass('input-error');
}
else
{
$('#message').removeClass('input-error');
}
if(data.input_valid == true)
{
console.log("All fields filled and valid");
alert('success');
}
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
process.php
<?php
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// Sanitize input variables
$company = test_input($_POST['company']);
$name = test_input($_POST['user_name']);
$email = test_input($_POST['user_email']);
$message = test_input($_POST['user_message']);
// Validate the variables
// If any of these variables don't exist, add an error to our $errors array
if (empty($name))
$errors['name'] = 'Name is required.';
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL))
$errors['email'] = 'Valid Email is required.';
if (empty($message))
$errors['message'] = 'Message is required.';
$from = '--- Contact Form ---';
$to = 'some#mail.com';
$subject = 'Message from Contact Form';
$body = "From: $name\nCompany: $company\nE-Mail: $email\nMessage:\n\n$message";
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
if(!empty($errors))
{
// if there are items in our errors array, return those errors
$data['input_valid'] = false;
$data['errors'] = $errors;
}
else
{
// If there are no errors process our form, then return a message
$data['input_valid'] = true;
if(mail($to, $subject, $body, $from))
{
$data['message'] = 'Thank you for your message!';
$data['mail_sent'] = true;
}
else
{
$data['message'] = 'Message could not be sent - please try again later.';
$data['mail_sent'] = false;
}
}
// return all our data to an AJAX call
echo json_encode($data);
// Convert special characters to html entities to prevent XSS attacks
// Also remove white-space and backslashes
function test_input($val)
{
$val = trim($val);
$val = stripslashes($val);
$val = htmlspecialchars($val);
return $val;
}
?>
It looks like if all validations pass in your php script, then data['errors'] is never defined. This might cause an error to be thrown (that you can see in the browser console) in the javascript when you write:
if (data.errors.name)
data.errors will evaluate to undefined in javascript, and when you try to access a property of undefined like data.errors.name, it will throw an error and stop the script.
To fix this, you probably just need to define errors in your php script, (though I'm not 100% sure the JSON methods won't leave out an empty array...). Try doing this in your php script:
if(!empty($errors))
{
// if there are items in our errors array, return those errors
$data['input_valid'] = false;
$data['errors'] = $errors;
}
else
{
// If there are no errors process our form, then return a message
$data['input_valid'] = true;
$data['errors'] = $errors; // even though it is empty
// etc
EDIT:
I don't know if it will work with your jquery version but just in case it doesn't, place this code in your header:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
I used the below code and it worked. Sent the email without having to change the PHP code:
$(document).ready(function() {
$('#contactForm').submit(function(event) {
$.ajax({
type: 'POST',
url: 'process.php',
data: $('#contactForm').serialize(),
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
if(data.input_valid == true) {
console.log("All fields filled and valid");
// If the function is a success remove error classes from all fields
// you can either place the below code above the alert so that it happens
// before you get the success message, or after.
$('#name').removeClass('input-error');
$('#email').removeClass('input-error');
$('#message').removeClass('input-error');
alert('success');
} else {
if (data.errors.name) {
console.log("Name missing");
$('#name').addClass('input-error');
} else {
$('#name').removeClass('input-error');
}
if (data.errors.email) {
console.log("Email missing or invalid");
$('#email').addClass('input-error');
} else {
$('#email').removeClass('input-error');
}
if (data.errors.message) {
console.log("Message missing");
$('#message').addClass('input-error');
} else {
$('#message').removeClass('input-error');
}
}
});
event.preventDefault();
});
});

Radio button value with Ajax/PHP

I have a problem with an apparently simple form for a mailing list subscription.
The HTML5 form contains 3 fields:
text input for e-mail address: <input type="email" name="email"
radio button control with 2 choices:
<input type="radio" value="subscribe" name="radio"
<input type="radio" value="unsubscribe" name="radio"
text input for a CAPTCHA check: <input type="text" name="captchavalue"
<form id="contact" name="contact" method="post" action="index.php" enctype="multipart/form-data">
<input type="hidden" name="check" value="01">
<small>*tutti i campi sono obbligatori</small>
<label for="email" id="emailabel">E-mail:<span class="err topp">INDIRIZZO NON VALIDO</span></label>
<input type="email" name="email" id="email" class="textemail">
<label for="subscr" id="subscrlabel">Scelta:<span class="err topp">devi selezionare una scelta</span></label>
<p><input type="radio" name="radio" id="radio" value="subscribe" checked>Iscrizione</p>
<p><input type="radio" name="radio" id="radio" value="unsubscribe">Cancellazione</p>
<img src="captcha.php" id="captchaimg">
<label for="captcha" id="captchalabel">Copiare il codice di verifica<span class="err capter">CAPTCHA ERRATO</span></label>
<input type="text" name="captchavalue" id="captchavalue" class="textcaptcha">
<section id="subber">
Invia richiesta
</section>
</form>
</div>
We have a list of domains which are allowed to ask for subscription contained in an external file .dat, some line in PHP to dynamically create a regular expression to check the email address (just in case of subscription, otherwise any valid email address is allowed)
<?php
$domains = file("domains.dat");
$domcount = count($domains);
for ($i=0; $i < $domcount; $i++) {
$regex .= "(".trim($domains[$i]).")|";
}
$regex = str_replace(".", "\.", $regex);
$regex = "/^([a-zA-Z\.-_0-9]*#(".substr($regex, 0, strlen($regex)-1).")$)/i";
?>
function checkValidCNRAddress(emailAddress) {
var pattern = new RegExp(<? echo $regex ?>);
return pattern.test(emailAddress);
};
function checkValidEmailAddress(emailAdd) {
var pattern = new RegExp(/^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+")([\w-+]+(?:\.[\w-+]+)*))(#((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i);
return pattern.test(emailAdd);
};
var mailsendstatus;
function userSendMailStatus(uemail,usubscr, ucaptcha) {
// statement below is for DEBUG purposes only -- to show the
// value of the radio button (subscription status) in ALL CASES
document.write(usubscr); //DEBUG
//check that a radio button option is checked (default: "subscribe" is checked )
if(!usubscr) {
$("#subscrlabel").children(".err").fadeIn('slow');
}
else if(usubscr) {
// we have *something* selected in the radio button for subscription
$("#subscrlabel").children(".err").fadeOut('slow');
// next, check for validate email addresses using regular expressions
//check on dynamic regex
if (usubscr == "subscribe") {
if(!checkValidCNRAddress(uemail)) {
$("#emailabel").children(".err").fadeIn('slow');
}
else if(checkValidCNRAddress(uemail)) {
$("#emailabel").children(".err").fadeOut('slow');
}
} //else check at least for a valid email address
else if (usubscr == "unsubscribe"){
if(!checkValidEmailAddress(uemail)) {
$("#emailabel").children(".err").fadeIn('slow');
}
else if(checkValidEmailAddress(uemail)) {
$("#emailabel").children(".err").fadeOut('slow');
}
}
}
Then it checks whether the captcha it's OK or not (it sends data to a PHP page captcha_check) and then submits to sendmail.php (which is in charge to send the subscribe/unsubscribe request to our mailserver)
// captcha check
$.ajax(
{
type: 'POST',
url: 'captcha_check.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "false") {
mailsendstatus = false;
$("#captchalabel").children(".err").fadeIn('slow');
}
else if(data == "true"){
$("#captchalabel").children(".err").fadeOut('slow');
if((checkValidCNRAddress(uemail))||(checkValidEmailAddress(uemail))) {
// in this case it's alright
// TRUE
mailsendstatus = true;
$("#subber").html('<img src="img/load.gif" alt="loading...">');
$.ajax(
{
type: 'POST',
url: 'sendmail.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "yes") {
$("#contactwrapper").slideUp(650, function(){
$(this).before("<p>La tua richiesta รจ stata inviata, grazie.</p>");
});
}
}
}
); //
} //
} //
} //
} //
);
return mailsendstatus;
}
$(document).ready(function(){
$("#contact").submit(function() { return false; });
$("#submitlink").bind("click", function(e){
var usercaptvalue = $("#captchavalue").val();
var emailvalue = $("#email").val();
var subscrvalue = $("#radio").val();
//sends values to sendmail.php
var postchecks = userSendMailStatus(emailvalue, subscrvalue, usercaptvalue);
});
});
</script>
</body>
Can anybody explain this to me:
- when the script verifies the email address, the value of the radio button given is always "subscribe", in any case, even if I check for unsubscription
- but if I type an email address which domain is contained in domains.dat and check the button for unsubscription, the value passed to sendmail.php is "unsubscribe" (as I can see when I receive the e-mail message)
Hope it's clear enough...thank you in advance for your precious help!
Your problem is that you're NOT actually making any AJAX request to sendmail.php AT ALL unless the email is valid and ONLY when the email is valid.
You see, all your validations in JavaScript to check for valid email addresses, are ONLY then:
fading your errors IN => $("#subscrlabel").children(".err").fadeIn('slow');
or
fading your errors OUT => $("#subscrlabel").children(".err").fadOut('slow');
but, this is occurring on the page only
When you actually submit, it fails the AJAX request if the email is invalid, BUT, it is still submitting the form normally and therefore it resets to the default subscribe input state of "checked"
What you need to do is include your .ajax(...) statement/call inside of your validation, not below it, after you've closed the function:
var mailsendstatus;
function userSendMailStatus(uemail,usubscr, ucaptcha) {
//verify radio button (it's checked by default in our case)
if(!usubscr) {
$("#subscrlabel").children(".err").fadeIn('slow');
}
else {
$("#subscrlabel").children(".err").fadeOut('slow');
//check on dynamic regex
if (usubscr == "subscribe") {
if(!checkValidCNRAddress(uemail)) {
$("#emailabel").children(".err").fadeIn('slow');
}
else if(checkValidCNRAddress(uemail)) {
$("#emailabel").children(".err").fadeOut('slow');
mailsendstatus = true;
}
} //else check at least for a valid email address
else if (usubscr == "unsubscribe"){
if(!checkValidEmailAddress(uemail)) {
$("#emailabel").children(".err").fadeIn('slow');
}
else if(checkValidEmailAddress(uemail)) {
$("#emailabel").children(".err").fadeOut('slow');
mailsendstatus = true;
}
}
}
if (mailsendstatus = true;) {
...
//make your AJAX request here
...
}
}

How to use a php ajax form in a color box?

I have a login form in (login.php). It call a separate sample.php via ajax, and sample.php returns it the value and the Javascript will show the relevant message depending on the php return value. It works perfectly fine in a normal webpage. But when I display the form in color box (in test.php). The javascript/jquery failed to run. I have research abit about this by using ajaxform, but how exactly do i do it? Please advise me some keywords for me to research further :(, i am stucked.
test.php:
$(".ajax").colorbox();
<a href="" class=ajax>Login</a>
This is my ajax function:
function login()
{
hideshow('loading',1);
error(0);
$.ajax({
type: "POST",
url: "http://utourpia.me/php/login_submit.php",
data: $('#loginForm').serialize(),
dataType: "json",
success: function(msg){
if(!(msg.status))
{
error(1,msg.txt);
}
else location.replace(msg.txt);
hideshow('loading',0);
}
});
}
This is my jQuery:
$('#loginForm').submit(function(e) {
login();
e.preventDefault();
});
This is my form:
<form id=loginForm method=post action="">
<label for=email class=email>Email:</label>
<input name=email type=text size=20 maxlength=40/>
<label for="password" class="password">Password:</label>
<input name="password" type="password" size="20" maxlength="40" />
<input class="login" type="submit" name="submit" value="Login" />
</form>
<div id="error"></div>
login_submit.php
<?php
require_once('../lib/connections/db.php');
include('../lib/functions/functions.php');
session_start();
$location_id = $_SESSION['location_id'];
$email = $_POST['email'];
$query = mysql_query('SELECT username FROM users WHERE email = "'.secureInput($email).'"') or die (mysql_error());
if(mysql_num_rows($query) == 1)
{
$row = mysql_fetch_assoc($query);
$username = $row['username'];
}
$returnURL1 = 'http://utourpia.me/php/places.php?id='.$location_id.'&username='.$username;
$returnURL2 = 'http://utourpia.me/php/myprofile.php?username='.$username;
$returnURL3 = 'http://utourpia.me';
$returnURL4 = 'http://utourpia.me/php/dreamtrip.php';
//For login
// we check if everything is filled in and perform checks
if(!$_POST['email'] || !$_POST['password'])
{
die(msg(0,"Email and / or password fields empty!"));
}
else
{
$res = login($_POST['email'],$_POST['password'],$username);
if ($res == 1){
die(msg(0,"Email and / or password incorrect!"));
}
if ($res == 2){
die(msg(0,"Sorry! Your account has been suspended!"));
}
if ($res == 3){
die(msg(0,"Sorry! Your account has not been activated. Please check your email's inbox or spam folder for a link to activate your account."));
}
if ($res == 99){
if ($_SESSION['login_submit']=="places.php")
{
echo(msg(1,$returnURL1));
}
else if ($_SESSION['login_submit']=="myprofile.php")
{
echo(msg(1,$returnURL2));
}
else if ($_SESSION['login_submit']=="home.php")
{
echo(msg(1,$returnURL3));
}
else if ($_SESSION['login_submit']=="dreamtrip.php")
{
echo(msg(1,$returnURL4));
}
}
}
function msg($status,$txt)
{
return '{"status":'.$status.',"txt":"'.$txt.'"}';
}
?>
First thing you need to change in the form tag:
Wright only above code. because you have given the method and URL that's why it refresh the page.
Replace your jquery code $('#loginForm').submit(function(e) { this code replace by $('.login').click(function(e) {.
Why are you using the replace method in the ajax success function is gives the error. remove else part.
location object does't have the replace method. if you want to redirect to user on success then use the location.href="your link";.
Make these changes and then check.

jQuery focus / blur $_GET['variable'] conflict

I have a simple focus / blur. 'Name of Venue' is shown by default since it's the value of the input type. on 'focus' it hides and on 'blur' is shows again if there's no text.
Here's the input field
<input type="text" name="name" id="search_name" value="Name of Venue" maxlength="100" />
Here's the jQuery
$('#search_name').focus(function() {
if($(this).val() == 'Name of Venue') {
$(this).val('');
}
});
$('#search_name').blur(function() {
if($(this).val() == '') {
$(this).val('Name of Venue');
}
});
On submit I don't want 'Name of Venue' to be stored as the get variable for $_GET['name']. So, I'm doing <br /><br /> PHP
if($_GET['name'] === 'Name of Venue') {
$_GET['name'] = '';
}
But, this doesn't work. How can I make it so the get variable will be empty on submit if it's the default value?
Consider using the HTML5 placeholder attribute if possible. The value will be blank if nothing was entered.
<input type="text" name="search_name" id="search_name" placeholder="Name of Venue" maxlength="100" />
It will appear/disappear automatically, so you won't need the focus/blur code. Also, "name" is a bad name for name, I'd use something more unique (usually the id will do).
As an alternative, you could do this:
<form id="myform" method="get" action="">
<input type="text" name="search_name" id="search_name" value="Name of Venue" maxlength="100" />
<input type="submit" id="submit_button" value="Submit" />
</form>
<script src="jquery-1.7.1.min.js"></script>
<script>
// ready() not need if <script> follows content, but best to put this in a .js file and link in <head>
$(document).ready(function() {
// Define once and you're good
var search_name = $('#search_name');
var submit_button = $('#submit_button');
var search_default = 'Name of Venue';
search_name.focus(function() {
if($(this).val() == search_default) {
$(this).val('');
}
});
search_name.blur(function() {
if($(this).val() == '') {
$(this).val(search_default);
}
});
$("#myform").submit(function(event) {
if (search_name.val() == '' || search_name.val() == search_default) {
event.preventDefault();
} else {
return true;
}
});
});
</script>
<?php
var_dump($_GET);
$name = '';
if (isset($_GET['search_name'])) {
// Without the check, we might run query when none exists
$name = $_GET['search_name'];
$name = $name != 'Name of Venue' ? $name : '';
}
var_dump($name);
?>
This will prevent a submit with a blank or default name. It's probably handy to put any repeated logic in a function and call those when handling the GET in PHP with any extra search variables.
You can control the value on client side and if it's a required field don't let the form to be submitted. If it's not required, just set the value to "" if it is "Name of Venue".
I think you have to make the field value blank before submitting the form if value is Name of Venue.
$('#frName').submit(function() { if($('#search_name').val() == 'Name of Venue' ){ $('#search_name').val('') } return false;});
You can remove return false if you want to submit the value. Hope its helps you

Jquery submit and post to post a form unable to return data

i have problem with jquery submit and post. I would like to submit a form and post it to my php for a check, and return the php result back to the form. However, I have problem with the returning of data, it basically ignores the result.
This is my html form:
<form id="form" method="post">
<p id="status">Status:</p>
<p class="text">
<label for="name" class="label">Name:</label>
<input type="text" id="name" name="name" value="" size="30" />
</p>
<p class="text">
<label for="email" class="label">Email:</label>
<input type="text" id="email" name="email" value="" size="30" />
</p>
<p class="submit">
<input type="submit" name="send_btn" id="send_btn" value="Send" />
</p>
</form>
This is my javascript to do the submit and post:
$('#form').submit(function(e) {
e.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
$.post('notify.php', {name: name, email: email}, function(data) {
$('#status').html(data);
});
});
This is the php that does the check and return the data:
<?php
if (isset($_POST['name'], $_POST['email']))
{
$name = htmlentities($_POST['name']);
$email = htmlentities($_POST['email']);
if ($name == "myname")
{
$output = 'It matches!';
}
else
{
$output = 'No matches!";
}
}
?>
Can please highlight what has gone wrong? Thank you.
You need to echo or die in your php script, so your function can get the results.
So, change your script to this:
<?php
if (isset($_POST['name'], $_POST['email']))
{
$name = htmlentities($_POST['name']);
$email = htmlentities($_POST['email']);
if ($name == "myname")
{
$output = 'It matches!';
}
else
{
$output = 'No matches!';
}
echo $output;
}
?>
Notice the third to last line, where I am calling echo $output - whatever you echo will be returned from your ajax call. If you want to get more complex, you should return a JSON object.
$results = array("result" => "It Matches!", "foo" => "bar");
echo json_encode($results);
EDIT: You also need to change the " to a ' at the end of your else.
Print the answer on PHP
as comment suggest
echo $output;
at the end of the line
In your php code, you aren't actually writing $output to the page.
<?php
// your code
echo $output;
?>
dont forget
return false;
If u forget it, the form when submit will refesh and ajax will fail ;
$('#form').submit(function(e) {
e.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
$.post('notify.php', {name: name, email: email}, function(data) {
$('#status').html(data);
});
return false;
});

Categories