So I have been trying to set up a contact page for a client and I am currently using emailjs to do it but it keeps coming up with errors when sending test emails to see if it works.
I have tried going onto the website for emailjs to find out what is wrong with it but I come up with nothing.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/styles2.css">
<link rel="stylesheet" href="css/newheader.css">
<link rel="stylesheet" href="css/contact.css">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<script type="text/javascript" src="https://cdn.emailjs.com/sdk/2.3.2/email.min.js"></script>
<script type="text/javascript">
(function(){
emailjs.init("user_ID"); // i have the user id in the code I just didn't want to post it online
})();
</script>
<script type="text/javascript">
window.onload = function() {
document.getElementById('contact-form').addEventListener('submit', function(event) {
event.preventDefault();
// generate the contact number value
this.contact_number.value = Math.random() * 100000 | 0;
emailjs.sendForm('contact_service', 'contact_template', this);
});
}
</script>
</head>
<body>
<header>
{{>header_2}}
</header>
<form id="contact-form">
<input type="hidden" name="contact_number">
<label>Name</label>
<input type="text" name="user_name">
<label>Email</label>
<input type="email" name="user_email">
<label>Message</label>
<textarea name="message"></textarea>
<input type="submit" value="Send">
</form>
</body>
</html>
The expected result is to send a test email to get things going but for some reason it is not working, it comes up saying bad request so I am unsure what to do.
Sending a an email is super easy, you dont need a plugin. First lets get your form ready; add these attributes to the form.
<form id="contact-form" method="POST" action="PHP/mailto.php">
now its time to set up a js script:
// first things first you gotta listen to the submit event and stop it from
// performing the 'action' which is redirecting the form data to the php
// file we are going to create.
document.getElementById('contact-form').addEventListener('submit', function(event){
//this prevents the form from doing its default action: redirection
event.preventDefault();
// disable inputs so form can only be sent once
$disabled_inputs = document.querySelectorAll('input, textarea');
for(i = 0; i < $disabled_inputs.length; i++){
$disabled_inputs[i].disabled = true;
}
// empty JSON object that will hold form data
var data = {};
//this function will loop through the data and collect the info on the inputs
// and text areas with a name attribute
this.querySelectorAll('input[name], textarea[name]').forEach(function($input) {
// this formats the data in a JSON object {inputname : inputvalue}
$data[$input.getAttribute('name')] = $input.value;
});
// take a look at the console so you get used to the json format
console.log($data);
// this will store the data in a JSON object so you have to clean it to send
// it to the php file with a post variable set
var json_upload = "your_php_postvariable=" + JSON.stringify($data);
// open new ajax request
var inquriry_request = new XMLHttpRequest();
// declare ajax method and origin (look at the form element)
inquriry_request.open("POST", "/PHP/mailto.php");
// declare cleaned JSON format to PHP file
inquriry_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// send ajax request with data
inquriry_request.send(json_upload);
// this functions runs after ajax request loads response
inquriry_request.onload = function(){
// create new script element
scripter = document.createElement('script');
// declare javascript type
scripter.type = 'text/javascript';
// load script echoed from php file inside this tag
scripter.innerHTML = inquriry_request.responseText;
// append script to body (this will cause script to run)
document.querySelector('body').append(scripter);
}
});
now lets set up the mailto.php file:
<?php
// run this function if post variable is set
if(isset($_POST['your_php_variable']){
// this while output an error log inside the /PHP/ directory
error_log(0);
// html email headers
$headers = "From: Web Emails <your#email.com>\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
// php post variable loop input attributes
var $php_post_var_loop = $_POST['your_php_variable'];
$name = $php_post_var_loop['user_name'];
$email = $php_post_var_loop['user_email'];
$message = $php_post_var_loop['message'];
// strings in php are appended by dots
$email_text = "From: ". $name . "<br><br>".
"Email: " . $email . "<br><br>".
"Message: " . $message;
// run if statement to check if php function ran to send mail
if(#mail('your#email.com', 'Email Subject', $email_text, $headers)){
// use this if you have to switch between single and double quotes
// inside your js script
$quo = '"';
echo "//js code to run if mail sends!"
} else {
// use this if you have to switch between single and double quotes
// inside your js script
$quo = '"';
echo = "//js code to run if mail does not send"
}
}
?>
Related
I am trying to send form data and js array to mysql database. I am having problem with receiving js array into my php. I receive data from form but not the array. I can't find the problem.
index.php
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"><!--bootstrap-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script><!--jquery-->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script><!--angular js-->
<script type="text/javascript" src="assets/js/main.js"></script>
</head>
<body>
<form method="post" action="upload.php">
<!--dynamic form created from javascript-->
<input id="submit" type="submit" value="Upload" name="submit" onclick="upload()"/>
</form>
</body>
</html>
javascript -- main.js
var objArray = []; //Array of questions
function upload(){
var jsonArray = JSON.stringify(objArray);
$.ajax({
type:'post',
url: 'upload.php',
data: { jsonData : jsonArray},
success: function(data){
console.log("success!");
}
});
} else {
console.log("no data javascript!");
}
}
upload.php
<?php
if(($_SERVER['REQUEST_METHOD'] == "POST") && (isset($_POST['submit']))){
$servername = "......";
$username = "......";
$password = "......";
$dbname = ".....";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(!empty($_POST['jsonData'])){
$json = $_POST['jsonData'];
var_dump(json_decode($json, true));
echo "<script type=\"text/javascript\">
console.log('received data');
</script>";
} else {
echo "data not received";
}
$conn->close();
}else {echo "unsecure connection";}
?>
objArray looks like this:
[{"questionId":1,"questionTypeObj":"single","options":3},{"questionId":2,"questionTypeObj":"single","options":3}]
upload.php outputs "data not received"
Your output indicates what the problem is: You get to the part where you echo data not received but you are not sending a submit key: $_POST['submit'] is not set when called through ajax.
So you are submitting your form the "normal" way and not through ajax.
This is caused by the fact that you are not cancelling the default submit action of your button.
The best way to solve that (in my opinion...), is to remove the inline javascript - the click handler - and replace your function with:
$("form").on('submit', function(e) {
// Cancel the default form submit
e.preventDefault();
// The rest of your function
var jsonArray = JSON.stringify(objArray);
...
});
Note that I am catching the form submit event. You could also replace that with the button click event but that might not work correctly when a visitor uses the enter key in a form field.
You shouldn't be doing it this way. There's no way to guarantee that the javascript will execute before you redirect. In fact, it won't run fast enough, and will just redirect to the next page. Try
<form method="post" action="upload();">
This will get the data to the page, but it won't display it. If you want it displayed you should have forms submitting it. If you post with ajax you can also try to catch the response with jquery.
when you click the button your code are going to send 2 requests to the server
First request-the ajax
this ajax request has the parameter you need jsonData : jsonArray
and right after that you are going to send another request
Second request-submitting the form
and the form has no jsonData : jsonArray paramter sent with it
you don't need this ajax at all!
all you need to do to receive the jsonData : jsonArray paramter is to send it along with the form
for example:
change your form to be like this
<form method="post" action="upload.php">
<input id="jsonData" type="hidden" name="jsonData" value="">
<input id="submit" type="submit" value="Upload" name="submit" onclick="upload()"/>
</form>
and change your button function to be like this
function upload(){
var jsonArray = JSON.stringify(objArray);
$('input#jsonData')[0].value=jsonArray ;
}
EDIT :
Or if you want upload.php to process the ajax request, and not to response with a whole document then you don't need the form, remove the form from your HTML , and just add submit:Upload to the ajax request
data: { jsonData : jsonArray, submit:"Upload" }
The problem is when I click on "submit data" button I get the response (this is correct), but when I click on "go to the php file" link (which is the same php file as previously) I get Undefined index: firstname and Undefined index: lastname error. How can I fix it?
Here is my code:
<html>
<head>
<script>
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "my_parse_file.php";
var fn = document.getElementById("first_name").value;
var ln = document.getElementById("last_name").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
First Name: <input id="first_name" name="first_name" type="text"> <br><br>
Last Name: <input id="last_name" name="last_name" type="text"> <br><br>
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();"> <br><br>
<div id="status"></div>
go to the php file
</body>
and the php file
<?php
echo 'Thank you '. $_POST['firstname'] . ' ' . $_POST['lastname'] . ', says the PHP file';
?>
Because both are different requests :
As you are passing parameters firstname and lastname using AJAX. You have to pass the same in URL using GET request.
go to the php file
<?php
echo 'Thank you '. $_REQUEST['firstname'] . ' ' . $_REQUEST['lastname'] . ', says the PHP file';
?>
Output :
Thank you abc xyz, says the PHP file
It will work in both Submit button and Hyperlink.
By clicking the link your browser sends not a POST request, but a GET request to your server-side. That is why the global array $_POST doesn't contains the elements you are trying to retrieve in your PHP file. The error message points you that there is no such elements in the $_POST array like "firstname" and "lastname".
It is recommended to add a check whether the array elements exist like so:
<?php
if (isset($_POST['firstname']) && isset($_POST['lastname'])) {
echo 'Thank you '. $_POST['firstname'] . ' ' . $_POST['lastname'] . ', says the PHP file';
} else {
echo 'Nothing to say';
}
Thanks R J for explanation. Now i fixed it and works properly.
But I am worried, because i used this code only for training. In my main problem i need to send the real object (not string etc.) by ajax to my php site, so i cant add it to the url, can I?
Relevant page here:
http://marcmurray.net/test_sites/cans/news.php
I've been trying to load a message confirmation modal for a while after the user submits an email, but can't get it to work at all.
So far I've tried echoing the whole script out, triggering the script, and changing the hash in the URL and checking for that, which has worked in other areas of the site.
Adding functions like alerts and echoing text onto the page is working fine, but when I use the show method it doesn't work. That leads me to believe I am either escaping characters wrong, or misunderstand how modals work a little.
Can anyone see where I'm messing up?
PHP:
<?php
if(isset($_POST["submit"])) {
// Checking For Blank Fields..
if($_POST["vname"]==""||$_POST["vemail"]==""||$_POST["sub"]==""||$_POST["msg"]==""){
echo "Please fill out everything! We need to know who you are, and why you want to get in touch with us!";}
else
{
// Check if the "Sender's Email" input field is filled out
$email=$_POST['vemail'];
// Sanitize E-mail Address
$email =filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate E-mail Address
$email= filter_var($email, FILTER_VALIDATE_EMAIL);
$emailConfirmed=$_POST['vemail'];
if (!$email){
echo "Don't forget to include your email adress! Otherwise we can't get back to you.";
}
else
{
$subject = $_POST['sub'];
$message = $_POST['msg'];
$headers = 'From:' . $emailConfirmed . "\r\n"; // Sender's Email
$headers .= 'Cc:' . $emailConfirmed . "\r\n"; // Carbon copy to Sender
// Message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// Send Mail By PHP Mail Function
mail("marc.murray.92#gmail.com", $subject, $message, $headers);
echo "<script>$('#thankyouModal').modal('show')</script>";
};
}
}
?>
HTML for the modal
<div class="modal fade" id="thankyouModal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Thank you for pre-registering!</h4>
</div>
<div class="modal-body">
<p>Thanks for getting in touch!</p>
</div>
</div>
</div>
</div>
EDIT: Updated code to be simpler than initial question.
Instead of calling modal show method upfront let all the assets load first then call the modal show method.
echo "<script>
$(window).load(function(){
$('#thankyouModal').modal('show');
});
</script>";
Instead of echoing the script why not just detect your form submit with javascript and then display the modal?
Something like
$("form").on('submit', function(){
$('.modal').show();
})
(If you're using JQuery)
First problem i see in your example code is, unnecessary \ on following code.echo "<script> \. Remove it
Second: Are you including all required js and css files for boostrap modal? If you are not Please update the code with following lines of code
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
At last there is no event triggered to open boostrap modal. Add following code to trigger the modal.
$(window).load(function(){
$('#myModal').modal('show');
});
Final code :
echo "<script>
var newHTML = document.createElement ('div');
newHTML.innerHTML =
newHTML = document.createElement ('div');
newHTML.innerHTML = ' <div id=\"myModal\" class=\"modal fade\" tabindex=\"-1\" role=\"dialog\"> <div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"></div>';
document.body.appendChild (newHTML);
$(window).load(function(){
$('#myModal').modal('show');
});
</script>";
Hope this helps.
I discovered that .in (sets opacity to 1) class which I believe should be set by Bootstrap does not show after submitting the form.
$('.modal').show().addClass('in');
Btw. you have an error in console
$(...).parsley(...).on is not a function
Maybe this is the problem..
echo "<script>$('#thankyouModal').modal('show')</script>";
I would do this....
$var = "<script>$(document).ready(function(){
$('#thankyouModal').modal('show')
});</script>";
And later print it on the right part inside your head at your html template.
Using your option and adding $(document).ready inside the script you are echoing dont think would work...the problem with the last option is that you will echo the script but jquery might not be yet fully loaded and it wont recognize it.
So, I suggest it to send it as a parameter and then print it.
If you are not using a framework and it is hard for you to pass a parameter, you can do it thought the URL and do something like my project.com/result.php?submit=true
and at your frontend you will read that variable
Like
if(isset($_GET["submit"]) && ($_GET["submit"]) ){
//echo your modal script
}
As xkcd149 says, if you mean to load the modal in the same page without reloading, you should be using AJAX requests:
replace the onsubmit attribute of the form to a function that sends the request data
window.onload = function() {
var forms = document.getElementsByTagName("form");
for(var f in forms) {
frm[f].onsubmit = xhr; // xhr is the function that sends the XHR
}
}
in the submit funcion used above, add success and error callbacks:
function xhr(){
var client = new XMLHttpRequest();
...
client.onerror = xhrerr;
client.onreadystatechange = handler;
client.send(...);
...
}
the success function should display the modal if the returned HTTP code is 200 (or whatever you want/need)
function handler(){
if (this.readyState == 4 && this.status == 200) {
var widget = document.getElementById("modal-body");
// add content to the body of the modal
} else {
// manage error
}
}
$('#thankyouModal').submit(function(e) {
e.preventDefault(); // don't submit multiple times
this.submit(); // use the native submit method of the form element
$('#thankyouModal').modal('show'); //Open the model
});
or You can manually create a button after form submit and trigger click on that button to open the modal.
$('#thankyouModal').click(function(e) {
e.preventDefault(); // don't submit multiple times
$("form").submit(); // use the native submit method of the form element
$('<button type="button" id="btnThankYou" class="hidden" data-toggle="modal" data-target="#thankyouModal">ThankYouButton</button>').appendTo('body');
//This will click the button and open the modal
$("#btnThankYou" ).trigger("click");
});
Place this links at your HEAD tag:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
and then change this:
<script>$('#thankyouModal').modal('show')</script>
to:
$(document).ready(function(){
<script>$('#thankyouModal').modal('show')</script>
});
$modal = "<script>$(document).ready(function(){
$('#thankyouModal').modal('show')
});</script>";
if(isset($_GET["submit"]) && ($_GET["submit"]) ){
// after running other script
echo $modal;
}
You can try as
$('#thankyouModal').submit(function(e) {
e.preventDefault(); // don't submit multiple times
this.submit(); // use the native submit method of the form element
$('#thankyouModal').modal('show'); //Open the model
});
Maybe you should send form via ajax, so after submit event you don't have to refresh your page.
As long as you won't refresh your page, your modal will be load successfully.
<?php
if(isset($_POST["submit"])) {
// Checking For Blank Fields..
$checkpost = false;
if($_POST["vname"]==""||$_POST["vemail"]==""||$_POST["sub"]==""||$_POST["msg"]==""){
echo "Please fill out everything! We need to know who you are, and why you want to get in touch with us!";}
else
{
// Check if the "Sender's Email" input field is filled out
$email=$_POST['vemail'];
// Sanitize E-mail Address
$email =filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate E-mail Address
$email= filter_var($email, FILTER_VALIDATE_EMAIL);
$emailConfirmed=$_POST['vemail'];
if (!$email){
echo "Don't forget to include your email adress! Otherwise we can't get back to you.";
}
else
{
$checkpost = true;
$subject = $_POST['sub'];
$message = $_POST['msg'];
$headers = 'From:' . $emailConfirmed . "\r\n"; // Sender's Email
$headers .= 'Cc:' . $emailConfirmed . "\r\n"; // Carbon copy to Sender
// Message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// Send Mail By PHP Mail Function
mail("marc.murray.92#gmail.com", $subject, $message, $headers);
echo "<script>$('#thankyouModal').modal('show')</script>";
};
}
}
?>
in html
<?php if($checkpost){ ?>
<script>
$('.modal').show();
</script>
<?php } ?>
I know it's a bit too late to answer. But hopefully it might help others.
The below code worked for me where I am using a Post-Redirect-Get pattern.Open a modal after form submission.
window.onpageshow = function() {
if (typeof window.performance != "undefined"
&& window.performance.navigation.type === 0) {
$('#myModal').modal('show');
}
}
Write down the following code.If you are using JQuery.
success: function(data)
{
$("#myModal").modal("show");
}
I'm trying to load a response from the php onto the same page. My Client side html looks like this.
<p>
<script type="text/javascript">// <![CDATA[
function sendForm() {
var dataSend = "?ClientName=" + $("#ClientName").val();
$.post("AddClient.php", dataSend, function(data) {
$("#responseDiv").html(data);
});
// ]]></script>
</p>
<div id="responseDiv"> </div>
<form action="AddClient.php" onsubmit="sendForm()">
<h1>Client Wizard <span>Please fill all the texts in the fields.</span></h1>
<label> <span>Client Name :</span> <input id="ClientName" type="text" name="ClientName" /> </label> <span> </span> <input class="button" type="Submit" value="Send" />
</form>
My Server side php looks like this:
<?php
$dbhost='127.0.0.1';
$dbuser='name';
$dbpass='password';
$dbname='dbname';
$conn=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
if(!$conn)
{
die('Could not connect:'.mysqli_connect_error());
}
$client=$_REQUEST["ClientName"];
$retval=mysqli_query($conn,"INSERT into client (clientid,clientname) VALUES (NULL,'$client')");
if(!$retval)
{
die('Could not add client:'.mysql_error());
}
$display_string="<h1>Client Added Successfully</h1>";
echo $display_string;
mysqli_close($conn);
?>
Unfortunately not only is the response being shown in anew html page, Its not accepting any name typed in the form. When I check the sql table the Column has a blank entry under it. I have not been able to figure out where I'm going wrong. Any help would be really appreciated.
All right. Your code have some room for improvement, but it's not an endless thing.
I saw somebody mention sanitization and validation. Alright, we got that. We can go in details here
This is how I will restructure your code using some improvements made by Samuel Cook (thank you!) and added a lot more.
index.html
<p>
<script type="text/javascript">// <![CDATA[
function sendForm() {
var dataSend = {clientName: $('#clientName').val()}
$.post("AddClient.php", dataSend, function(data) {
$('#responseDiv').html(data);
});
return false;
}
//]]>
</script>
</p>
<div id="responseDiv"></div>
<form action="AddClient.php" onsubmit="sendForm(); return false;">
<h1>Client Wizard <span>Please fill all the texts in the fields.</span></h1>
<label><span>Client Name :</span><input id="clientName" type="text" name="clientName"/><span></span><input type="submit" class="button" value="Send"></label>
</form>
Notice change in an input id and input name - it's now start with a lower case and now clientName instead of ClientName. It's look a little bit polished to my aesthetic eye.
You should take note on onsubmit attribute, especially return false. Because you don't prevent default form behavior you get a redirect, and in my case and probably your too, I've got two entries in my table with a empty field for one.
Nice. Let's go to server-side.
addClient.php
<?php
$dbhost = '127.0.0.1';
$dbuser = 'root';
$dbpass = '123';
$dbname = 'dbname';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if (!$conn) {
die('Could not connect: ' . mysqli_connect_error());
}
$client=$_REQUEST["clientName"];
$client = filter_var($client, FILTER_SANITIZE_STRING);
if (isset($client)) {
$stmt = $conn->prepare("INSERT into client(clientid, clientname) VALUES (NULL, ?)");
$stmt->bind_param('s', $client);
$stmt->execute();
}
if (!$stmt) {
die('Could not add client:' . $conn->error);
}
$display_string = "<h1>Client $client Added Successfully</h1>";
echo $display_string;
mysqli_close($conn);
?>
That is going on here. We are using PHP filters to sanitize our incoming from somewhere string.
Next, we check if that variable $client even exist (you remember that twice sended form xhr? Double security check!)
Here comes a fun part - to protect our selves even more, we start using prepared mySQL statements. There is no way someone could SQL inject you somehow.
And just check for any errors and display it. Here you go. I've tested it on my machine, so it works.
Forms default behavior is to redirect to the page given in the action attribute (and if it's empty, it refreshes the current page). If you want it to make a request without redirecting to another page, you need to use Javascript to intercept the request.
Here's an example in jQuery:
$('form').on('submit', function(e) {
e.preventDefault(); // This stops the form from doing it's normal behavior
var formData = $(this).serializeArray(); // https://api.jquery.com/serializeArray/
// http://api.jquery.com/jquery.ajax/
$.ajax($(this).attr('action'), {
data: formData,
success: function() {
// Show something on success response (200)
}, error: function() {
// Show something on error response
}, complete: function() {
// success or error is done
}
});
}
Would recommend having a beforeSend state where the user can't hit the submit button more than once (spinner, disabled button, etc.).
First off, you have a syntax error on your sendForm function. It's missing the closing bracket:
function sendForm() {
//...
}
Next, You need to stop the form from submitting to a new page. Using your onsubmit function you can stop this. In order to do so, return false in your function:
function sendForm() {
//...
return false;
}
Next, you aren't actually sending any POST data to your PHP page. Your second argument of your .post method shouldn't be a query string, but rather an object (I've commented out your line of code):
function sendForm() {
var dataSend = {ClientName:$("#ClientName").val()}
//var dataSend = "?ClientName=" + $("#ClientName").val();
$.post("AddClient.php", dataSend, function(data) {
$("#responseDiv").html(data);
});
return false;
}
Lastly, you have got to sanitize your data before you insert it into a database. You're leaving yourself open to a lot of vulnerabilities by not properly escaping your data.
You're almost there, your code just need a few tweaks!
I am trying to do a basic AJAX implementation to send some form data to a php script and db. I'm just doing this for learning purposes, and have taken it as far as I could. When I hit the "Create Profile" button, nothing is happening. From my code below, does anything obvious jump out at anyone in my syntax/structure?
Note* I've yet to implement the code to retrieve the data using AJAX, will do this later once I get the send working.
EDIT*** I made some slight changes to the sendFunction(), and have seen some success. Values are now being added to my database, but they values are blank, instead of the values in the form data.
Thank you for all help/suggestions ahead of time!
HTML doc:
<!DOCTYPE HTML>
<html>
<head>
<title>Ajax Form</title>
<script language="javascript" type="text/javascript">
function sendFunction() { // Create a function to handle the Ajax
var xmlhttpCreate; // Variable to hold the xmlhttpRequest object
if (window.XMLHttPRequest) { // Checks for browser compatibilities
xmlhttpCreate = new XMLHttpRequest();
}
else {
xmlhttpCreate = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttpCreate.onreadystatechange = function() {
if (xmlhttpCreate.readyState == 4) { // If server has processed request and is ready to respond
document.getElementById("createSuccess").innerHTML = xmlhttpCreate.responseText; // Display a success message that the data was sent and processed by the php script & database
}
}
var fName = document.getElementById('firstName').value; // Dump user firstName into a variable
var lName = document.getElementById('lastName').value; // Dump user lastName into a variable
var queryString = "?fName=" + fName + "&lName=" + lName; // A query string that will be sent to the php script, which will then send the values to the db
xmlhttpCreate.open("GET", "ajax_create.php" + queryString, true); // Open the request
xmlhttpCreate.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttpCreate.send(); // Send the request
}
</script>
</head>
<body>
<h3>Create Profile</h3><br>
<form name="form">
First Name: <input type="text" id ="firstName"/><br><br>
Last Name: <input type="text" id="lastName"/><br><br>
<input type="button" onclick="sendFunction()" value="Create Profile">
</form><br>
<div id="createSuccess"></div><br>
<h3>Search for Profile</h3><br>
<form name="searchForm">
First Name: <input type="text" id="searchFirstName"/><br><br>
<input type="button" onclick="sendFunction()" value="Search for Profile"/>
</form><br><br>
<div id="resultFN"></div><br>
<div id="resultLN"></div><br>
</body>
</html>
And here is my PHP script:
<?php
// Connect to the database
$con = mysqli_connect('localhost', 'root', 'intell', 'ajax_profile');
// GET variables from xmlhttpCreate
$fName = $_POST['fName'];
$lName = $_POST['lName'];
// Escape the user input to help prevent SQL injection
$fName = mysqli_real_escape_string($fName);
$lName = mysqli_real_escape_string($lName);
// Build the query
$query = "INSERT INTO users (firstName, lastName) VALUES ('$fName', '$lName')";
mysqli_query($con, $query);
mysqli_close($con);
$success = "Profile added to the database";
echo $success;
?>
you are sending data with method GET and you want to get the date in your php file with POST ... now you have two solutions . you can change the javascript code to send with GET like this :
var queryString = "fName=" + fName + "&lName=" + lName; // A query string that will be sent to the php script, which will then send the values to the db
xmlhttpCreate.open("POST", "ajax_create.php", true); // Open the request
xmlhttpCreate.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttpCreate.send(queryString);
or you can change the way you get the data on your php file like this:
$fName = $_GET['fName'];
$lName = $_GET['lName'];
don't do both things , only one, change either javascript function or php file.