Undefined result from Ajax - php

I am passing some form variables through to a php page using Ajax, however when the php code runs the table rows are filled with the value undefined.
I have checked the php code, substituting the form variables and that works fine and so i am thinking that the problem is with the Ajax code,
AJAX
$(document).ready(function(){
$('form.submit').submit(function () {
var name = $(this).find('.name').attr('value');
var address = $(this).find('.address').attr('value');
var number = $(this).find('.number').attr('value');
var price = $(this).find('.price').attr('value');
var deposit = $(this).find('.deposit').attr('value');
var product = $(this).find('.product').attr('value');
var payment_type = $(this).find('.payment_type').attr('value');
var deal_date = $(this).find('.deal_date').attr('value');
var install_date = $(this).find('.install_date').attr('value');
var installed = $(this).find('.installed').attr('value');
var notes = $(this).find('.notes').attr('value');
var contract_received = $(this).find('.contract_received').attr('value');
// ...
$.ajax({
type: "POST",
url: "add.php",
data: "name="+ name +"& address="+ address +"& number="+ number +"& price="+ price +"& deposit="+ deposit +"& product="+ product +"& payment_type="+ payment_type +"& deal_date="+ deal_date +"& install_date="+ install_date +"& installed="+ installed +"& notes="+ notes +"& contract_received="+ contract_received,
success: function(){
$('form.submit').hide(function(){$('div.success').fadeOut();});
}
});
return false;
});
});
HTML
<form id="submit" name="submit" class="submit">
<input name="name" id="name" type="text" class="form-control" placeholder="Name"/><br />
<input name="address" id="address" type="text" class="form-control" placeholder="Address"/><br />
<input name="number" id="number" type="text" class="form-control" placeholder="Number"/><br />
<input name="price" id="price" type="text" class="form-control" placeholder="Price"/><br />
<input name="deposit" id="deposit" type="text" class="form-control" placeholder="Deposit"/><br />
<input name="product" id="product" type="text" class="form-control" placeholder="Product"/><br />
<input name="payment_type" id="payment_type" type="text" class="form-control" placeholder="Payment"/><br />
<input name="deal_date" id="deal_date" type="text" class="form-control" placeholder="Deal Date"/><br />
<input name="install_date" id="install_date" type="text" class="form-control" placeholder="Install Date"/><br />
<input name="installed" id="installed" type="text" class="form-control" placeholder="Installed"/><br />
<textarea name="notes" id="notes" cols="" rows="" class="form-control" placeholder="Notes"></textarea><br />
<input name="contract_received" id="contract_received" type="text" class="form-control" placeholder="Contract Received"/><br />
<input type="submit" name="button" id="button" value="Submit" />
</form>
PHP
$name = htmlspecialchars(trim($_POST['name']));
$address = htmlspecialchars(trim($_POST['address']));
$number = htmlspecialchars(trim($_POST['number']));
$price = htmlspecialchars(trim($_POST['price']));
$deposit = htmlspecialchars(trim($_POST['deposit']));
$product = htmlspecialchars(trim($_POST['product']));
$payment_type = htmlspecialchars(trim($_POST['payment_type']));
$deal_date = htmlspecialchars(trim($_POST['deal_date']));
$install_date = htmlspecialchars(trim($_POST['install_date']));
$installed = htmlspecialchars(trim($_POST['installed']));
$notes = htmlspecialchars(trim($_POST['notes']));
$contract_received = htmlspecialchars(trim($_POST['contract_received']));
$addClient = "INSERT INTO DATA (
name, address,number,price,deposit,product,payment_type,deal_date,install_date,installed,notes,contract_recieved)VALUES('$name','$address','$number','$price','$deposit','$product','$payment_type','$deal_date','$installed_date','$installed','$notes','$contract_received')";
mysql_query($addClient) or die(mysql_error());

You are making it very hard for yourself. There is no need to get all individual values from the form if you are sending the whole form. But if you do, you need to encode each value correctly using encodeURIComponent(). And don't send any spaces in your query string either.
The easiest solution is to have jQuery serialize your form and send that:
$.ajax({
type: "POST",
url: "add.php",
data: $('form.submit').serialize(), // or just: data: $(this).serialize(),
success: function(){
$('form.submit').hide(function(){$('div.success').fadeOut();});
}
});
Now all key-value pairs from the form will be sent correctly and jQuery will also take care of the encoding for you.

The correct syntax is http://api.jquery.com/jQuery.ajax/
data: {name: name, address: address, number: number}
and so on.

Related

how to send data with ajax from input fields to php

I have currently this html:
<td>
<input type="hidden" class="old_name" name="old_name" value="folder1/image.jpg" />
<input type="text" class="new_name" name="new_name" value="" />
<button type="submit" class="rename">Rename</button>
</td>
<td>
<input type="hidden" class="old_name" name="old_name" value="folder2/image.jpg" />
<input type="text" class="new_name" name="new_name" value="" />
<button type="submit" class="rename">Rename</button>
</td>
<td>
<input type="hidden" class="old_name" name="old_name" value="folder3/image.jpg" />
<input type="text" class="new_name" name="new_name" value="" />
<button type="submit" class="rename">Rename</button>
</td>
My jquery ajax looks like this:
// AJAX for rename files
$(document).on('click' , '.rename' , function() {
var old_name = $(".old_name").val(); // getting old value from input
var new_name = $(".new_name").val(); //getting new value from input
$.ajax({
url:"",
method:"POST",
data:{
old_name:old_name ,
new_name:new_name
},
success:function(data){
// here comes echo
}
});
});
My php:
if( isset($_POST["old_name"]) && isset($_POST["new_name"]) ) {
echo $_POST["old_name"];
echo $_POST["new_name"];
First problem: when click on Rename second button, it echos the old_name from first button. So how can i catch the second value old_name when click on second Rename button?
Second problem: php does not echo the $_POST["new_name"]
How can i achieve this without using a form?
First problem solution
use different name (in your specific case different class name ) for different input
<td>
<input type="hidden" class="old_name1" name="old_name" value="folder1/image.jpg" />
<input type="text" class="new_name1" name="new_name" value="" />
<button type="submit" class="rename1">Rename</button>
</td>
<td>
<input type="hidden" class="old_name2" name="old_name" value="folder2/image.jpg" />
<input type="text" class="new_name2" name="new_name" value="" />
<button type="submit" class="rename2">Rename</button>
</td>
<td>
<input type="hidden" class="old_name3" name="old_name" value="folder3/image.jpg" />
<input type="text" class="new_name3" name="new_name" value="" />
<button type="submit" class="rename3">Rename</button>
</td>
new js function will be
$(document).on('click' , '.rename1' , function() {
var old_name = $(".old_name1").val(); // getting old value from input
var new_name = $(".new_name1").val(); //getting new value from input
$.ajax({
url:"",
method:"POST",
data:{
old_name:old_name ,
new_name:new_name
},
success:function(data){
// here comes echo
}
});
});
$(document).on('click' , '.rename2' , function() {
var old_name = $(".old_name2").val(); // getting old value from input
var new_name = $(".new_name2").val(); //getting new value from input
$.ajax({
url:"",
method:"POST",
data:{
old_name:old_name ,
new_name:new_name
},
success:function(data){
// here comes echo
}
});
});
$(document).on('click' , '.rename3' , function() {
var old_name = $(".old_name3").val(); // getting old value from input
var new_name = $(".new_name3").val(); //getting new value from input
$.ajax({
url:"",
method:"POST",
data:{
old_name:old_name ,
new_name:new_name
},
success:function(data){
// here comes echo
}
});
});
Second problem solution
you probably leave the field empty

Hide API KEY and URL inside of PHP file

I have a form where the user submits info (name, address, phone, etc.) and on submit, the data will be inserted into the API url, sent to the API, data is returned and put into hidden fields then posted. Is it possible to hide the AJAX URL inside a php file so I can hide the API KEY so it's not public? Like:
$.ajax({
url: whitepages.php
Inside whitepages.php
Here is my existing code:
var wpfname = $('#customer_person_name_f input').val();
var wplname = $('#customer_person_name_l input').val();
var wpfullname = wpfname + " " + wplname;
var wpaddress = $('#customer_address_street input').val();
var wpcity = $('#customer_address_city input').val();
var wpstate = $('#address_state_abbr input').val();
var wpzip = $('#customer_address_zipcode input').val();
var wpphone = $('#customer_phone_number input').val();
var wpemail = $('#customer_email_address input').val();
$.ajax({
url: "https://proapi.whitepages.com/3.3/lead_verify.json?name=" + wpfullname +"&phone=" + wpphone + "&address.street_line_1=" + wpaddress + "&api_key=" + KEYGOESHERE + "&address.city=" + wpcity + "&address.postal_code=" + wpzip + "&address.state_code=" + wpstate + "&email_address=" + wpemail,
dataType: "text",
method: "GET",
crossDomain: "true",
success: function(data) {
var json = $.parseJSON(data);
console.log(json);
$('#wp_phone_contact_score').val(json.phone_checks.phone_contact_score);
$('#wp_subscriber_name').val(json.phone_checks.subscriber_name);
$('#wp_subscriber_age_range').val(json.phone_checks.subscriber_age_range);
$('#wp_subscriber_address').val(json.phone_checks.subscriber_address.street_line_1 +', ' + json.phone_checks.subscriber_address.city +', ' + json.phone_checks.subscriber_address.state_code + ' ' + json.phone_checks.subscriber_address.postal_code);
$('#wp_line_type').val(json.phone_checks.line_type);
$('#wp_is_commercial').val(json.phone_checks.is_commercial);
$('#wp_address_contact_score').val(json.address_checks.address_contact_score);
$('#wp_is_active').val(json.address_checks.is_active);
$('#wp_address_to_name').val(json.address_checks.address_to_name);
$('#wp_resident_age_range').val(json.address_checks.resident_age_range);
$('#wp_resident_phone').val(json.address_checks.resident_phone);
$('#wp_type').val(json.address_checks.type);
}
<form>
<input id="wp_phone_contact_score" type="hidden" name="customer_wp_phone_contact_score" value="">
<input id="wp_subscriber_name" type="hidden" name="customer_wp_subscriber_name" value="">
<input id="wp_subscriber_age_range" type="hidden" name="customer_wp_subscriber_age_range" value="">
<input id="wp_subscriber_address" type="hidden" name="customer_wp_subscriber_address" value="">
<input id="wp_line_type" type="hidden" name="customer_wp_line_type" value="">
<input id="wp_is_commercial" type="hidden" name="customer_wp_is_commercial" value="">
<input id="wp_address_contact_score" type="hidden" name="customer_wp_address_contact_score" value="">
<input id="wp_is_active" type="hidden" name="customer_wp_is_active" value="">
<input id="wp_address_to_name" type="hidden" name="customer_wp_address_to_name" value="">
<input id="wp_resident_age_range" type="hidden" name="customer_wp_resident_age_range" value="">
<input id="wp_resident_phone" type="hidden" name="customer_wp_resident_phone" value="">
<input id="wp_type" type="hidden" name="customer_wp_type" value="">
<input type="text" name="customer_person_name_f">
<input type="text" name="customer_person_name_l">
<input type="text" name="customer_phone_number">
<input type="text" name="customer_address_street">
<input type="text" name="customer_address_city">
<input type="text" name="customer_address_state_abbr">
<input type="text" name="customer_address_zipcode">
<input type="submit" id="submitBtn" class="btn btn-primary btn-large" value="Submit"/>
</form>
No.
You can't have the browser make an HTTP request with some data in the URL without giving the data to the browser.
You would have to make the HTTP request to the whitepages.com from the server instead of the browser.
Yes, but your user can't directly call whitepages like you are doing in your script.
You will have to write your own script that the user will call using ajax and to use your server to make the request to whitepage.
Either using CURL or file_get_contents() Call a REST API in PHP
All the user will know is that he is sending you his (name, address, phone, etc.).

Number of files uploaded on server end (php) differs from the client side

HTML Form:
<form enctype="multipart/form-data" method="post" name="fileinfo" id="myForm">
<label>Your email address:</label>
<input type="email" autocomplete="on" autofocus id="userid" name="userid" placeholder="email" required size="32" maxlength="64" /><br />
<label>File to stash:</label>
<input type="file" name="fileToUpload[]" id="fileToUpload[]" required />
<input type="file" name="fileToUpload[]" id="fileToUpload[]" required />
<input type="submit" id="save" value="Stash the file!" />
</form>
I have used formdata to the best of my knowledge but I am not sure if I have done it right.
Javascript Code:
<script type="text/javascript">
$('#save').click(function(event){
event.preventDefault();
var fd = new FormData(document.querySelector("form"));
var ins = document.getElementById('fileToUpload[]').files.length;
console.log(ins);
if (ins != 0) {
fd.append("fileToUpload[][]", document.getElementById('fileToUpload[]').files[0]);
fd.append("Email", $('#userid').val());
for (var pair of fd.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
$.ajax({
url: "upload.php",
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function(data){
console.log(data);
}
});
}
else{
console.log("Nothing attached ");
}
})
</script>
In my upload.php file i am just trying to print the names. but i Am always getting count value as 3 whatever be the number of files uploaded on the front end, even if I don't upload any files at all, it gives the value 2.
<?php
$count = count($_FILES['fileToUpload']['name']);
echo $count;
for ($i = 0; $i < $count; $i++) {
echo 'Name: '.$_FILES['fileToUpload']['name'][$i].'\r\n';
}
?>
I am doing this for the first time. I have no idea where I am going wrong. Thanks in advance.

Input fields are empty after .submit jquery statement

I'm trying to send data using an ajax call inside of a ('#form').submit call but all the inputs of the forms are empty when I didn't intend them to be. I thought it may of had something to do with the $(document).ready statement being in the incorrect location for things to work properly but I couldn't get it to work.
<script>
(function($){
$(document).ready( function() {
$("#success").hide();
$("#inval_email").hide();
$("#text_selection").on("change", function() {
var id = $("#text_selection option:selected").attr("value");
$("#inv_text").html($("#"+id).html());
});
$("#invitation_form").submit(function(e){
var email = $('#email').val();
var first_name = $('#first_name').val();
var last_name = $('#last_name').val();
var message_title = $('#message_title').val();
var article_title = $('#article_title').val();
var reference_location = $('#reference').val();
var inv_text = $('#inv_text').html();
var request;
alert(first_name);
e.preventDefault();
request = $.ajax({
type: 'POST',
url: BASE_URL+"wp-content/themes/Flatter/ajax/send_invite.php",
dataType: "text",
data: { first_name: first_name, last_name: last_name, email: email, message_title: message_title, article_title: article_title, reference_location: reference_location, inv_text: inv_text },
success: function(data){
console.log(data)
if(data=="true"){
$("#invitation").hide();
$("#success").show();
}
if(data=="false"){
$("#inval_email").show();
}
}
});
});
});
})(jQuery);
</script>
<div class="col-md-4">
<div id="success" hidden><br><br>Invitation sent successfully!</div>
<div id="invitation">
<br><br><br></br><h1>Invitation Form</h1>
<form id = "invitation_form">
First Name:<input id="first_name" type="text" name="first_name" required>
Last Name:<input id="last_name" type="text" name="last_name" required>
Email Address:<input id="email" type="text" name="email" required>
Message Title:<input id="message_title" type="text" name="message_title" required>
Article Title:<input id="article_title" type="text" name="article_title" required>
Reference Location:<input id="reference" type="text" name="reference" required>
Message:<textarea id="inv_text" style="resize: none" rows="10" placeholder="Select invitation type..." readonly required></textarea>
Invitation Type:
<select id="text_selection">
<option value="empty_field"></option>
<option value="community_inv_text">Community Invitation</option>
<option value="content_submission_inv" >Content Submission Invitation</option>
<option value="individual_inv">Individual Invitation</option>
<option value="content_submission_and_individual_inv">Content Submission and Individual Invitation</option>
<option value="contributor_content_submission_inv">Contributor Content Submission Invitation</option>
</select>
<input id="submit_inv" type="submit" value="Invite">
</form>
I would greatly appreciate some help in this matter. The point of this code is to collect information from the user and send the data to another file so it can be processed. Thanks for any help in advance.
I figured it out. There was a CSS file that was modifying elements under the same name as the ones I am using in my file (i.e. first_name, last_name, email, etc.).

I am so confused by checkboxes in Ajax

I am attempting to create an ajax contact form that the results gets emailed to me. I found a form demo online and edited it to meet my criteria, except that there were no checkboxes in the demo, when I add checkboxes everything but those work.
Can someone please guide me through this?
The html is:
<div class="done">
<strong>Thank you !</strong> We've received your questions and someone from our office will respond at our earliest convience.</p>
<p>Check your email, we just sent you a coupon for 10% off your first purchase.</p>
</div>
<div class="form">
<form method="post" action="process2.php" autocomplete="off">
<label for="name">Name</label>
<input type="text" name="name" id="name" />
<label for="phone">Phone</label>
<input type="text" name="phone" id="phone" />
<label for="email">Email</label>
<input type="text" name="email" id="email" />
<ul>
<li>Design:</li>
<li><label for="master_plan"><input type="checkbox" name="service[]" id="master_plan" value="Master Plan" /> Master Plan</label></li>
<li><label for="front_foundation"><input type="checkbox" name="service[]" id="front_foundation" value="Front Foundation" /> Front Foundation</label></li>
<li><label for="backyard_plan"><input type="checkbox" name="service[]" id="backyard_plan" value="Backyard Plan" /> Backyard Plan</label></li>
<li><label for="specialty_garden"><input type="checkbox" name="service[]" id="specialty_garden" value="Specialty Garden" /> Specialty Garden</label></li>
</ul>
<label for="newsletter"><input type="checkbox" name="newsletter" id="newsletter" value="x" checked="checked" /> Yes, I would like to be added to your newsletter list.</label>
<label for="comments">Comments</label>
<textarea name="comments" id="comments" rows="5" cols="40" /></textarea>
<input type="submit" id="submit" value="Sign Up" />
<div class="loading"></div>
</form>
</div>
The javascript is:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function () {
var name = $('input[name=name]');
var phone = $('input[name=phone]');
var email = $('input[name=email]');
var comments = $('textarea[name=comments]');
if (name.val()=='') {
name.addClass('hightlight');
return false;
} else name.removeClass('hightlight');
if (email.val()=='') {
email.addClass('hightlight');
return false;
} else email.removeClass('hightlight');
var data =
'name=' + name.val() +
'&phone=' + phone.val() +
'&email=' + email.val() +
'&comments=' + encodeURIComponent(comments.val());
$('.text').attr('disabled','true');
$('.loading').show();
$.ajax({
url: "process2.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
if (html==1) {
$('.form').fadeOut('slow');
$('.done').fadeIn('slow');
} else alert('Sorry, unexpected error. Please try again later.');
}
});
return false;
});
});
</script>
And the php (process2.php) is:
$name = ($_GET['name']) ? $_GET['name'] : $_POST['name'];
$phone = ($_GET['phone']) ?$_GET['phone'] : $_POST['phone'];
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];
$mailing = ($_GET['newsletter']) ?$_GET['newsletter'] : $_POST['newsletter'];
$comments = ($_GET['comments']) ?$_GET['comments'] : $_POST['comments'];
if($phone) {$phone = '('.substr($phone, 0, 3).') '.substr($phone, 3, 3).'-'.substr($phone, 6, 4);} else {$phone = '(Not Entered)';}
I am so very confused that I dont know what to do?
You aren't including them in your data that you're sending via ajax. You're also not even trying to get the service values in your php.
var data =
'name=' + name.val() +
'&phone=' + phone.val() +
'&email=' + email.val() +
'&comments=' + encodeURIComponent(comments.val());
//data only includes name, phone, email, comments
You might want to try jQuery serialize method instead of the above code.
var data = $(this).parents('form').serialize();

Categories