getting data using ajax php jquery - php

I made a submit form using php and ajax and don't get it why it doesn't work.
My code:
ex1.php
<form id="myForm">
<p> Firstname: <input type="text" name= "firstName"</p>
<p> Lastname<input type="text" name = "lastName" id="lastName"</p>
<p> Password: <input type="password" name= "password" id="myPass"> </p>
<p> Email: <input type="text" name="email" id="myEmail"></p>
<p> Age: <input type="text" name="age" id="myAge"> </p>
<input type="submit" value="submit" id="subm">
</form>
<script>
$(document).ready(function(){
$("#subm").click(function(){
var firstName = $("#firstName").val();
var lastName = $("#lastName").val();
var password = $("#myPass").val();
var email = $("#myEmail").val();
var age = $("#myAge").val();
var dataString = "Firstname: " + firstName + ", Lastname: " + lastName + ", Email: " + email + " , Password: " + password + "Age: " + age;
$.ajax({
type: "POST",
url: "ex1Ex.php",
data: dataString,
cache: false,
succes: function(result){
alert(result);
}
});
});
});
externFile:
<?php
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$password = $_POST['password'];
$email = $_POST['email'];
$age = $_POST['age'];
echo 'jsjsjs';
?>
When I enter the values, after pressing the button, in console it appears
ex1?firstName=a&lastName=ww&password=111&email=a&age=11:59 POST http://local.healix/ex1Ex.php 500 (Internal Server Error)
The problem must be with the file ex1Ex.php, but I don't get it what.Any suggestions?

Change your jquery function like following.
$(document).ready(function () {
$("#subm").click(function (event) {
event.preventDefault();
var firstName = $("#firstName").val();
var lastName = $("#lastName").val();
var password = $("#myPass").val();
var email = $("#myEmail").val();
var age = $("#myAge").val();
var dataString = "Firstname: " + firstName + ", Lastname: " + lastName + ", Email: " + email + " , Password: " + password + "Age: " + age;
$.ajax({
type: "POST",
url: "ex1Ex.php",
data: dataString,
cache: false,
success: function (result) {
alert(result);
}
});
});
});
I think you have to prevent the default php form submission using event.preventDefault();
Also, please correct the spelling mistake; you have written succes: instead of success:

Pass your data out in an object .ajax will deal with that nicely converting it into the $_POST array. You also dont need to go through interim declared variables, get the data right out of the DOM straight into the data property of the .ajax call
$(document).ready(function(){
$("#subm").click(function(e){
// stop the form submitting in the normal way as well as through AJAX
e.preventDefault();
$.ajax({
type: "POST",
url: "ex1Ex.php",
data: {Firstname: $("#firstName").val(),
Lastname: $("#lastName").val(),
Email: $("#myEmail").val(),
Password: $("#myPass").val(),
Age: $("#myAge").val()
},
//cache: false,
success: function(result){ // spelling corrected
alert(result);
}
});
});
});
Then remember that whatever the name you use for each parameter in the javascript is the name that will be used in the $_POST array so if you use Firstname in javascript you should expect a $_POST['Firstname'] (case sensitive)
<?php
$firstName = $_POST['Firstname'];
$lastName = $_POST['Lastname'];
$password = $_POST['Password'];
$email = $_POST['Email'];
$age = $_POST['Age'];
//echo "I received: $firstName, $lastName, $password, $email, $age";
// or better still while testing
echo json_encode($_POST);
?>

I think the problem with keys which you have used while posting in from ajax request eg. for first name its "Firstname" and you are accessing it with key 'firstName'
php post array is case sensitive

Related

Wordpress ajax form submission without using wordpress functions possible?

I'm currently making a site on Wordpress and need a form to be submitted via ajax is it possible to do this without using Wordpress functions? My current code has no errors and returns a success message without updating the database. I don't understand why it's not working please have a look at my simplified version -
This is the form HTML -
<form action="" method="post" id="formAppointment" name="appointmentform">
<input type="text" name="message_first_name" value="" placeholder="First name" id="appointmentFirstName">
<input type="text" name="message_last_name" value="" placeholder="Last name" id="appointmentLastName">
<input type="tel" name="message_phone" value="" placeholder="Phone" id="appointmentPhone">
<input type="submit" id='appointmentSubmit' class='xAnim' name="submit">
</form>
This is the jquery AJAX -
$("#formAppointment").submit(function(e){
var firstname = $("#appointmentFirstName").val();
var lastname = $('#appointmentLastName').val();
var phone = $('#appointmentPhone').val();
var dataString = 'message_first_name='+ firstname + '&message_last_name=' + lastname + '&message_phone=' + phone;
if(firstname.trim() == "" || lastname.trim() == "" || phone.trim() == ""){
alert('missing information');
e.preventDefault();
} else {
// AJAX Code To submit Form.
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
cache: false,
success: function(result){
console.log(dataString);
alert('success');
}
});
}
return false;
});
This is the php located in process.php
include "config.php";
$patientfirstname = htmlspecialchars($_POST['message_first_name']);
$patientlastname = htmlspecialchars($_POST['message_last_name']);
$patientcontactnumber = htmlspecialchars($_POST['message_phone']);
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO data_table (firstname, lastname, phonenumber ) VALUES ('$patientfirstname', '$patientlastname', '$patientcontactnumber')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
You have to pass data as object, not as dataString.
$("#formAppointment").submit(function(e) {
e.preventDefault();
var firstname = $("#appointmentFirstName").val();
var lastname = $('#appointmentLastName').val();
var phone = $('#appointmentPhone').val();
// var dataString = 'message_first_name=' + firstname + '&message_last_name=' + lastname + '&message_phone=' + phone;
var data = {
"message_first_name": firstname,
"message_last_name": lastname,
"message_phone": phone,
}
if (firstname.trim() == "" || lastname.trim() == "" || phone.trim() == "") {
alert('missing information');
} else {
// AJAX Code To submit Form.
$.ajax({
type: "POST",
url: "process.php",
data: data,
cache: false,
success: function(result) {
console.log(result);
alert('success');
}
});
}
});
NOTE: You are missing email and message in the code. So the line if(firstname.trim() == "" || lastname.trim() == "" || email.trim() == "" || message.trim() == "") may raise some errors and js skips the execution of remaining code

php file not called from ajax call

Have a problem to call my server.php to add some values into db.
server.php:
<?php
$db = new PDO('mysql:host=localhost;dbname=test','user','password');
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$stmt = $db->prepare("INSERT INTO user (name,email,phone,address) VALUES(?,?,?,?)");
$stmt->bindParam(1,$name);
$stmt->bindParam(2,$email);
$stmt->bindParam(3,$phone);
$stmt->bindParam(4,$address);
$stmt->execute();
echo "data saved";
?>
Calling the server.php directly, the data will be saved.
But from my Html/Ajax code it will not:
<script>
function saveData(){
var name = $('#name').val();
var email = $('#email').val();
var phone = $('#phone').val();
var address = $('#address').val();
$.ajax({
type: "POST",
url: "server.php",
data: "name=" +name+"&email="+email+"&phone="+phone+"&address="+address,
}).done(function(data){
alert('success');
$('#result').html("<br/><div> class='alert alert-info'>" + data +"</div>");
)};
return false;
</script>
The alert('success') won't be called also #result div isn't filled.
Whats wrong with this code?

Trouble getting one item into MySQL db

I'm having a perplexing problem--I'm managing to get one value, extracted from a text box, successfully inserted into my table but the other (also from a text box) is not going in. Before the AJAX call, I've alerted my datastring to make sure both values are correct, and they are. When I look in the database, however, only the name value is entered and email is blank.
HTML:
<div id="basic-modal-content">
<h3>Please Alert me when this is Available</h3>
<p>Your Name: <input type="text" id="alert_name"/></p>
<p>Email Address: <input type="text" id="alert_email"/></p>
<button id="alert_submit">Submit</button>
</div>
Javascript:
$('#alert_submit').click(function(){
var datastring = 'name='+ $('#alert_name').val() + '&email=' + $('#alert_email').val();
alert(datastring);
$.ajax({
type: "POST",
url: "process_email.php",
data: datastring,
success: function(data) {
}
});
alert ("We've received your request and will alert you once the directory is available. Thank you.");
$.modal.close();
});
PHP:
$name = $_POST['name'];
$email = $_POST['email'];
try {
$conn = new PDO('mysql:host=blah;dbname=blah', '-', '-');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("INSERT INTO email_alerts(name, email) VALUES(':name, :email)");
$stmt->execute(array('name' => $name, 'email' => $email));
//$affected_rows = $stmt->rowCount();
$conn = null;
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
$conn = null;
}
try this code please
$('#alert_submit').click(function(){
$.ajax({
type: "POST",
url: "process_email.php?name="+$('#alert_name').val() +"&email="+ $('#alert_email').val(),
success: function(data) {
}
});
alert ("We've received your request and will alert you once the directory is available. Thank you.");
$.modal.close();
});

$_POST merging array and storing in only one column

I have a form that posts to a php handler which saves the data from the form into a database.
I don't think the save function is the problem. I think its a problem with the $_POST merging the forms data. When I view the sql table, the data is there but all the values are appearing in one column so the variables are being passed from the form correctly.
This is my code:
$name = isset($_POST['name']) ? $_POST['name'] : '';
$email = isset($_POST['email']) ? $_POST['email'] : '';
$com_dis = isset($_POST['comment']) ? $_POST['comment'] : '';
$id = isset($_POST['id']) ? $_POST['id'] : '';
$lowercase = strtolower($email);
$image = md5( $lowercase );
try{
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = 'INSERT INTO comments ( com_name, com_email, com_dis, post_id_fk ) VALUES ( :name, :email, :com_dis, :id )';
$st = $conn->prepare ( $sql );
$st->bindValue( ":name", $name, PDO::PARAM_STR );
$st->bindValue( ":email", $email, PDO::PARAM_STR );
$st->bindValue( ":com_dis", $com_dis, PDO::PARAM_STR );
$st->bindValue( ":id", $id, PDO::PARAM_INT );
$st->execute();
$conn = null;
}catch(PDOException $e ){
echo "QUERY FAILED" . $e->getMessage();
};
If I use $id = $_POST['id'] for all the variables, it gets an unidentified index error thrown. When I print $_POST it displays an array where the array is called name and the contents are just the rest of the variables which is the same data stored in the table.
How do I either get the data to save correctly or stop $_POST from merging the variable so they? save in the correct columns?
This is my form:
<form action="#" method="post">
<input type="hidden" name="id" id="id" value="<?php echo $id; ?>"/><br />
<span class="titles">Name</span><span class="star">*</span><br /><input type="text" name="name" id="name"/><br />
<span class="titles">Email</span><span class="star">*</span><br /><input type="text" name="email" id="email"/><br />
Comment<br /><textarea name="comment" id="comment"></textarea><br />
<input type="submit" class="submit" value=" Submit Comment " />
</form>
The form is passed via AJAX:
$(function() {
$(".submit").click(function() {
name = $("#name").val();
var email = $("#email").val();
var comment = $("#comment").val();
var id = $("#id").val();
var dataString = 'name='+ name + 'email=' + email + 'comment=' + comment + 'id=' + id;
if(name=='' || email=='' || comment==''){
alert('Please Give Valid Details');
}
else{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax-loader.gif" align="absmiddle"> <span class="loading">Loading Comment...</span>');
$.ajax({
type: "POST",
url: "commentajax.php",
data: dataString,
cache: false,
success: function(html){
$("ol#update").append(html);
$("ol#update li:last").fadeIn("slow");
document.getElementById('email').value='';
document.getElementById('name').value='';
document.getElementById('comment').value='';
$("#name").focus();
$("#flash").hide();
}
});
}
return false;
});
You need to concatenate your data string:
var dataString = 'name='+ name + 'email=' + email + 'comment=' + comment + 'id=' + id;
should be
var dataString = 'name='+ name + '&email=' + email + '&comment=' + comment + '&id=' + id;

How to instantly display data after form submission using jQuery and AJAX?

I have a PHP form that uses jQuery/AJAX to submit data into a MySQL database table. Currently, I have a message display saying " Done!" once the form is submitted, but would like the actual data to instantly display after it has been submitted. I have a loop setup to display previously added messages in divs with the class name 'msg_container', and would like the new data to display in one of these divs after form submission.
What is the best way to do this? Any help would be greatly appreciated!
index.php javascript
<script type="text/javascript">
$(document).ready(function () {
$(".button").click(function () {
var user_id = $("textarea#uer_id").val();
var msg = $("textarea#msg ").val();
var dataString = 'user_id=' + user_id + '&msg=' + msg;
$.ajax({
type: "POST",
url: "add.php",
data: dataString,
success: function () {
alert("Done!")
}
});
return false
});
});
</script>
index.php query
$user_id = $_GET['user_id'];
require_once('../../includes/connect.php');
$dbh = get_dbh($_SESSION['ORG_ID']);
$sth = $dbh->query ("SELECT *, user.last_name, user.first_name FROM msgs
INNER JOIN users
ON msgs.user_id = users.id
WHERE user_id = '$user_id'
ORDER BY timestamp");
$row = $sth->fetch ();
index.php HTML
<div id="msgs">
<?php while ($row = $sth->fetch ()) { ?>
<div class="msg_container">
<div class="left"><? echo $row['last_name'].', '.$row['first_name']; ?><br />
<? $timestamp = date('m/d/Y g:i a', strtotime($row['timestamp'])); echo $timestamp; ?>
</div>
<div class="right"><? echo $row['msg']; ?></div>
<div class="clear"></div>
</div>
<? } ?>
<div class="add_note">
<div class="left">Add Message</div>
<div class="right">
<form id="add_msg">
<textarea id="msg" name="msg"></textarea>
<input type='submit' class="button right-aligned" value='Submit' />
</form>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
</div>
add.php
<?php
require_once('../../includes/connect.php');
$dbh = get_dbh($_SESSION['ORG_ID']);
$user_id = $_POST['user_id'];
$msg= $_POST['msg'];
date_default_timezone_set("UTC");
$timestamp = date('Y-m-d H:i:s', strftime(gmmktime()));
date_default_timezone_set($_SESSION['TIME_ZONE']);
$sth = $dbh->prepare ("INSERT INTO msgs (id, user_id, msg, timestamp) VALUES (?, ?, ?, ?)");
$data = array (NULL, $user_id, $msg, $timestamp);
$sth->execute ($data);
session_write_close();
?>
You could just append the new message after the previous ones. Something like this:
$.ajax({
type: "POST",
url: "add.php",
data: dataString,
success: function() {
alert ("Done!");
$('#msgs').append('<div class="msg_container">' +
'<div class="left">' + lastNameVariable + ', ' + firstNameVariable +
'<br />' + timeStampVariable +
'</div><div class="right">' + msg + '</div>' +
'<div class="clear"></div></div>');
}
});
You will need to put the first name, last name, timestamp, etc. into variables (or do it a different way, like do an AJAX call to get the info - whatever you prefer). I didn't know what user_id is so I just thought I would let you fill in those variables.
This is just the basic idea of what you could do. If you have any questions, just ask.
I hope this helps.
Edit:
If you created another page called "getname.php" or something like that (to get the first and last name) that would display "first name, last name" based on the user ID passed in the URL, that could work. In the URL it could have ?user_id=1234567 and then on that page, it would do a mysql_query and display the first and last name. This is what I would do:
getname.php ↓
<?
// ...
$user_id = $_GET['user_id'];
$result = mysql_query("SELECT * FROM table WHERE user_id = '$user_id' AND ...");
$row = mysql_fetch_array($result);
// ...
echo $row['last_name'] . ', ' . $row['first_name'];
// ...
?>
Of course you would do this the way you do your queries, but hopefully this helps you understand what I'm saying. Then, after you have that, you can do:
$.ajax({
type: "POST",
url: "add.php",
data: dataString,
success: function() {
alert ("Done!");
var firstAndLast = '';
var theTime =
$.get('getname.php?user_id='+user_id, function(data) {
firstAndLast = data;
});
$('#msgs').append('<div class="msg_container">' +
'<div class="left">' + firstAndLast // this will display: "first name, last name" because of getname.php
+ '<br />' + theTime +
'</div><div class="right">' + msg + '</div>' +
'<div class="clear"></div></div>');
}
});
As for the time, you could either display it with JavaScript (when they refresh it would show the time that was recorded by PHP) or do the same as you did for name.
Consider the jQuery ajax method load. This is a higher level version of ajax. You will send your request and the response will immediately be placed into the preceding selector elements.
$('#result').load('ajax/test.html', data);
Here's just a quick idea to get you going. You need to return the data from the script you call with AJAX; a data that you would use to generate the DIV you want. You'll also need to change the ajax call to something like this:
$.ajax({
type: "POST",
url: "add.php",
data: dataString,
success: function(data) {
console.log(data); //to see what's returned
//use the data to generate content you want
alert ("Done!")
}
});
Due to the structure of your data, it might be the best to send a JSON response.
In the success part add this code:
success: function(data){
$('#flash').css("display","block");;
setTimeout(function () {
$('#flash').slideUp();`enter code here`}, 2000);
}
In the HTML add this code:
<div id="flash" style="display:none;">Data Saved Successfully</div>

Categories