cannot receive js array posted with ajax - javascript

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" }

Related

Returning a value from server to html for manipulation

I want to manipulate the value that it is stored in this variable $result[]. Specifically i want to return that value from php file to my html file. What should i do? Can you give me some reference code when i want to return things from server side to client side for further manipulation?
My php file:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("127.0.0.1", "root", "", "mysql3");
// Check connection
if($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$user_id =$_POST['user_id'];
$book_id =$_POST['book_id'];
$game_id =$_POST['game_id'];
$site_id =$_POST['site_id'];
//Attempt insert query execution
$query = "SELECT site_id FROM components WHERE user_id='$user_id' && book_id='$book_id' && game_id='$game_id' ORDER BY site_id DESC LIMIT 1";
$res = mysqli_query($link,$query);
$result = array();
$res = mysqli_query($link,$query) or die(mysqli_error($link));
while($row = mysqli_fetch_assoc($res)){
$result[]=$row['site_id'];
}
// Close connection
mysqli_close($link);
?>
My html file:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script>
function load3() {
var flag1 = true;
do{
var selection = window.prompt("Give the User Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection)) {
flag1=false;
}
}while(flag1!=false);
$("#user_id").val(selection)
//$("#user_id").val(prompt("Give the User Id:"))
var flag2 = true;
do{
var selection2 = window.prompt("Give the Book Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection2)) {
flag2=false;
}
}while(flag2!=false);
$("#book_id").val(selection2)
//$("#book_id").val(prompt("Give the Book Id:"))
var flag3= true;
do{
var selection3 = window.prompt("Give the Game Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection3)) {
flag3=false;
}
}while(flag3!=false);
$("#game_id").val(selection3)
//$("#game_id").val(prompt("Give the Game Id:"))
}
var fieldNameElement = document.getElementById('outPut');
if (fieldNameElement == 4)
{
window.alert("bingo!");
}
</script>
</head>
<body>
<form name="LoadGame" id="LoadGame" method="post" action="http://127.0.0.1/PHP/mine1.php" enctype="multipart/form-data">
<input type="submit" value="Load" id="load" onclick="load3()" class="button12" />
<input type="hidden" name="user_id" id="user_id">
<input type="hidden" name="book_id" id="book_id">
<input type="hidden" name="game_id" id="game_id">
<input type="hidden" name="site_id" id="site_id">
</form>
</body>
</html>
Note that this answer is making use of jQuery notation, so you will need to include a jQuery library in your application in order to make this example work:
<script src="/js/jquery.min.js" type="text/javascript"></script>
Since you have your HTML and PHP in separate files, you can use AJAX to output your HTML in an element you so desire on your HTML page.
Example of jQuery AJAX:
<script>
function submitMyForm() {
$.ajax({
type: 'POST',
url: '/your_page.php',
data: $('#yourFormId').serialize(),
success: function (html) {
//do something on success?
$('#outPut').html(html);
var bingoValue=4;
if( $('#outPut').text().indexOf(''+bingoValue) > 0){
alert('bingo!');
}
else {
alert('No!');
}
}
});
}
</script>
Note that I encapsulated the AJAX function in another function that you can choose to call onclick on a button for example.
<button id="mySubmitButton" onclick="submitMyForm();">Submit form!</button>
Step-by-step:
What we do in our AJAX function, is that we declare our data type, just like you would do with a form element. In your PHP file I noticed that you used the POST method, so that's what I incorporated in the AJAX function as well.
Next we declare our URL, which is where the data will be sent. This is the same page that your current form is sending the data to, which is your PHP page.
We then the declare our data. Now, there are different ways of doing this. I assume you are using a form currently to POST your data to your PHP page, so I thought we might as well make use of that form now that you have it anyways. What we do is that we basically serialize the data inside your form as our POST values, just like you do on a normal form submit. Another way of doing it, would be to declare individual variables as your POST variables.
Example of individual variables:
$.ajax({
type: 'POST',
url: '/your_page.php',
data: {
myVariable : data,
anotherVariable : moreData
//etc.
},
success: function (html) {
//do something on success?
$('#outPut').html(html);
}
});
A literal example of a variable to parse: myVariable : $('input#bookId').val().
The operator : in our AJAX function is basically an = in this case, so we set our variable to be equal to whatever we want. In the literal example myVariable will contain the value of an input field with the id bookId. You can do targeting by any selector you want, and you can look that up. I just used this as an example.
In the success function of the AJAX function, you can basically do something upon success. This is where you could insert the HTML that you wish to output from your PHP page into another element (a div for example). In my AJAX example, I am outputting the html from the PHP page into an element that contains the id outPut.
We also write a condition in our success function (based off comments to this answer), where we check for a specific substring value in the div element. This substring value is defined through the variable bingoValue. In my example I set that to be equal to 4, so whenever "4" exists inside the div element, it enters the condition.
Example:
<div id="outPut"></div>
If you make use of this example, then whatever HTML you structure in your PHP file, making use of the PHP values in your PHP file, will be inserted into the div element.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("127.0.0.1", "root", "", "mysql3");
// Check connection
if($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$user_id =$_POST['user_id'];
$book_id =$_POST['book_id'];
$game_id =$_POST['game_id'];
$site_id =$_POST['site_id'];
//Attempt insert query execution
$query = "SELECT site_id FROM components WHERE user_id='$user_id' && book_id='$book_id' && game_id='$game_id' ORDER BY site_id DESC LIMIT 1";
$res = mysqli_query($link,$query);
$result = array();
$res = mysqli_query($link,$query) or die(mysqli_error($link));
while($row = mysqli_fetch_assoc($res)){
$result=$row['site_id'];
echo $result.' ';
}
// Close connection
mysqli_close($link);
?>
Your form also no longer needs an action defined as all of that is now taken care of by the AJAX function.
So change:
<form name="LoadGame" id="LoadGame" method="post" action="http://127.0.0.1/PHP/mine1.php" enctype="multipart/form-data">
to:
<form name="LoadGame" id="LoadGame" method="post" enctype="multipart/form-data">
And make sure that your button: <button id="mySubmitButton" onclick="submitMyForm();">Submit form!</button> is outside of your form tag, as buttons without a defined type attribute will have type="submit" by default inside a form tag.
If you need anything elaborated, let me know. :)
First of all: remove the script tag from your php.
Secondly: Why are you executing the sql statement two times?
To your question:
You have to send a request to your PHP script via AJAX: (Place this inside <script> tags and make sure to include jquery correctly)
$(() => {
$('form').on('submit', () => {
event.preventDefault()
$.ajax({
type: 'POST',
url: '<your-php-file>', // Modify to your requirements
dataType: 'json',
data: $('form').serialize() // Modify to your requirements
}).done(function(response){
console.log(response)
}).fail(function(){
console.log('ERROR')
})
})
})
Your PHP-Script which needs to return JSON:
$query = "SELECT site_id FROM components WHERE user_id='$user_id' && book_id='$book_id' && game_id='$game_id' ORDER BY site_id DESC LIMIT 1";
// Execute Query
$res = mysqli_query($link,$query) or die(mysqli_error($link));
// Get Rows
while($row = mysqli_fetch_assoc($res)){
$result[] = $row['site_id'];
}
// Return JSON to AJAX
echo json_encode($result);
Take a look at your developer console.
Haven't tested it.

how to make submit button both send form thru' PHP -> MySQL and execute javascript?

I'm having an issue. When I hit submit, my form values are sent to the database. However, I would like the form to both send the value to the database and execute my script, as said in the title.
When I hit submit button, the form is sent to the database and the script remains ignored. However, if I input empty values into the input areas, the javascript is executed, and does what I want (which is to show a hidden < div >), but it's useless since the < div > is empty, as there is no output from the server.
What I want is:
submit button -> submit form -> javascript is executed > div shows up > inside div database SELECT FROM values (which are the ones added through the submitting of the form) appear.
Is this possible? I mean, to mix both PHP and JavaScript like this?
Thanks in advance.
By two ways, You can fix it easily.
By ajax--Submit your form and get response
$('form').submit(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: url, //action
data: form.serialize(), //your data that is summited
success: function (html) {
// show the div by script show response form html
}
});
});
First submit your from at action. at this page you can execute your script code .. At action file,
<?php
if(isset($_POST['name']))
{
// save data form and get response as you want.
?>
<script type='text/javascript'>
//div show script code here
</script>
<?php
}
?>
hers is the sample as I Comment above.
In javascript function you can do like this
$.post( '<?php echo get_site_url(); ?>/ajax-script/', {pickup:pickup,dropoff:dropoff,km:km}, function (data) {
$('#fare').html(data.fare);
//alert(data.fare);
fares = data.fare;
cityy = data.city;
actual_distances = data.actual_distance;
}, "json");
in this ajax call I am sending some parameters to the ajaxscript page, and on ajaxscript page, I called a web service and gets the response like this
$jsonData = file_get_contents("https://some_URL&pickup_area=$pickup_area&drop_area=$drop_area&distance=$km");
echo $jsonData;
this echo $jsonData send back the data to previous page.
and on previous page, You can see I Use data. to get the resposne.
Hope this helps !!
You need ajax! Something like this.
HTML
<form method='POST' action='foobar.php' id='myform'>
<input type='text' name='fname'>
<input type='text' name='lname'>
<input type='submit' name='btnSubmit'>
</form>
<div id='append'>
</div>
jQuery
var $myform = $('#myform'),
$thisDiv = $('#append');
$myform.on('submit', function(e){
e.preventDefault(); // prevent form from submitting
var $DATA = new FormData(this);
$.ajax({
type: 'POST',
url: this.attr('action'),
data: $DATA,
cache: false,
success: function(data){
$thisDiv.empty();
$thisDiv.append(data);
}
});
});
And in your foobar.php
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$query = "SELECT * FROM people WHERE fname='$fname' AND lname = '$lname' ";
$exec = $con->query($query);
...
while($row = mysqli_fetch_array($query){
echo $row['fname'] . " " . $row['lname'];
}
?>
That's it! Hope it helps
You can use jQuery ajax to accomplish it.
$('form').submit(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: url, //url where the form is to be submitted
data: data, //your data that is summited
success: function () {
// show the div
}
});
});
Yes, you can mix both PHP and JavaScript. I am giving you a rough solution here.
<?php
if(try to catch submit button's post value here, to see form is submitted)
{
?>
<script>
//do javascript tasks here
</script>
<?php
//do php tasks here
}
?>
Yes, This is probably the biggest use of ajax. I would use jquery $.post
$("#myForm").submit(function(e){
e.preventDefault();
var val_1 = $("#val_1").val();
var val_2 = $("#val_2").val();
var val_3 = $("#val_3").val();
var val_4 = $("#val_4").val();
$.post("mydbInsertCode.php", {val_1:val_1, val_2:val_2, val_3: val_3, val_4:val_4}, function(response){
// Form values are now available in php $_POST array in mydbInsertCode.php - put echo 'success'; after your php sql insert function in mydbInsertCode.php';
if(response=='success'){
myCheckdbFunction(val_1,val_2,val_3,val_4);
}
});
});
function myCheckdbFunction(val_1,val_2,val_3,val_4){
$.post("mydbCheckUpdated.php", {val_1:val_1, val_2:val_2, val_3: val_3, val_4:val_4}, function(response){
// put echo $val; from db SELECT in mydbSelectCode.php at end of file ';
if(response==true){
$('#myDiv').append(response);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>

How to save the value of a textbox to a .txt file using php in html without reloading or redirecting the page?

I want to make a textbox on an webpage which will take a number from user and that number will be saved in a .txt file. Firstly I have made the textbox in the html and made a form. I have created a submit button to run the php and made it as the action of the form. This php file contains the code for saving the data. But whenever I am trying to submit, the html is get refreshed or it is redirecting to the php file. But I need to save the value of textbox by submit button, not to refresh whole page. How to do? The following is the 'form' part of html:
<form action="write2file.php" method="GET"/>
Iteration number:<br>
<input type="number" name="iteration_no"/>
<input type="submit" id="save_run" value="Run"/>
</form>
And the php is:
<?php
$filename ="noi_RS.txt";
$file = fopen( $filename, "w" );
fwrite( $file, $_GET['iteration_no']);
fclose( $file );
?>
Modified Answer,Fix an error of value stored as null,
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"> </script>
<script>
function callSubmit(){
var dataset = {"value1": document.getElementById('itnumber').value };
$.ajax({
url: 'write2file.php',
type: 'POST',
data: dataset,
success: function() {
alert('Success');
}
});
}
</script>
</head>
<body>
<form action="" method="GET" onsubmit="callSubmit()">
Iteration number:<br>
<input type="number" name="iteration_no" id="itnumber"/>
<input type="submit" id="save_run" value="Run" />
</form>
</body>
</html>
PHP file like this,
<?php
$text1 = $_POST['value1'];
$filename ="noi_RS.txt";
$file = fopen( $filename, "w" );
//$map = $_POST['iteration_no'];
fwrite( $file, $text1);
fclose( $file );
?>
Try using onsubmit event , event.preventDefault() to prevent form submission , create script element with src set to expected query string at php as parameter to encodeURIComponent() , append script element to head element, at script onload , onerror events remove script element
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
Iteration number:<br>
<input type="number" name="iteration_no"/>
<input type="submit" id="save_run" value="Run"/>
</form>
<script>
document.forms[0].onsubmit = function(event) {
event.preventDefault();
var val = this.children["iteration_no"].value;
var script = document.createElement("script");
script.type = "text/javascript";
script.onload = script.onerror = function() {
console.log(this.src.split("?")[1]);
this.parentNode.removeChild(this)
};
script.src = "?iteration_no=" + encodeURIComponent(val);
document.head.appendChild(script);
}
</script>
</body>
</html>
You'll need to use javascript if you want to do something like dynamic form submission.
The essence of it is that you want the user to do something, and then behind the scenes respond to that action. To the user, you might just inform them "Hey, I got it".
So you'll need javascript - specifically you need to send an AJAX request. Here's some information to get you started.
You're about to start on a journey of wild endeavours - cuz javascript ain't easy.

Trying to load a response sheet from php in the same page

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!

Using AJAX to send form data to php script (without jQuery)

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.

Categories

Resources