'undefined' data submited when using ajax - javascript

I'm using HTML form to send data to google sheet, it work great. But when i add ajax code, the data send to google sheet always is "undefined", remove the code it'll work but it show the code really ugly after that, so i want using ajax.
$(document).ready(function() {
var submit = $("button[type='submit']");
submit.click(function() {
var data = $('form#test-form').serialize();
$.ajax({
type: 'GET',
url: 'https://script.google.com/macros/s/AKfycby8PCL7hef6N35QAEe7CcGWEVLeONJfy8ATXIsM5Sn7icTDMw8/exec',
dataType: 'json',
crossDomain: true,
data: data,
success: function(data) {
if (data == 'false') {
alert('Oopps! Đã có lỗi. Quý khách hãy thử lại hoặc liên hệ trực tiếp qua hotline nhé.');
} else {
alert('Đã tiếp nhận thành công! Cát Tiên sẽ liên hệ lại trong thời gian sớm nhất. Cám ơn quý khách');
}
}
});
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="https://script.google.com/macros/s/AKfycby8PCL7hef6N35QAEe7CcGWEVLeONJfy8ATXIsM5Sn7icTDMw8/exec" method="GET">
<input type="text" name="SDT" id="ip2" placeholder=" SĐT hoặc Email">
<button type="submit" id="submit-form" class="button">Nhận</button>
</form>
<script type="text/javascript">
</script>
I don't know about code, all i using tutorial in web. Many thanks for your help.

You forgot to add an ID to your form.
Your script is trying to serialize the form with the id test-form with this function:
var data = $('form#test-form').serialize();
The form isn't found, because you forgot to add the id to the form.
Just replace your form's HTML with the following:
<form
id="test-form"
action="https://script.google.com/macros/s/AKfycby8PCL7hef6N35QAEe7CcGWEVLeONJfy8ATXIsM5Sn7icTDMw8/exec" method="GET">
<input type="text" name="SDT" id="ip2" placeholder=" SĐT hoặc Email">
<button type="submit"id="submit-form" class="button">Nhận</button>
</form>

Related

how to upload an image using ajax

I want to upload an image without refreshing the page,But my page still refresh when i hit submit button to upload image. what is wrong with my ajax code. This works when am submitting form with plain text but not with image file.
test.php
<div class="preview_d_p" id="preview_d_p">
<div class="preview">
<div class="p_preview">
<div id="p_p_image"><div id="myimage"></div></div>
</div>
<div id="lab"> <label for="photo_upload">upload</label></div>
<form enctype="multipart/form-data">
<input type="file" id="photo_upload" name="image_upload">
<input type="submit" value="save" id="insert_img" onclick="return loadimage()">
</form>
</div></div>
<script>
function loadimage(){
var image = documentElement('photo_upload').value;
$.ajax({
type:'post',
url:'profile.php',
data:{
image:image
},
cache:false,
success: function(html){
}
});
return false;
}
</script>
my advice is changing the input to a button (type="button") - I prefer buttons to inputs as they're more easily stylable.
But you can do something like this to govern submitting data without page refresh:
HTML EXAMPLE (NOT A COPY OF YOUR HTML):
<div id="container">
<form action="" method="post" id="myForm">
<input type="text" value="hello world!" />
</form>
<!-- what's great about buttons, is that you don't have to place inside the form tags -->
<button type="button" id="submitBtn">
JS To match
$(document).ready(function()
{
$('#submitBtn').on('click', function()
{
//ajaxy stuff
//will show the success callback function though:
success: function(res)
{
$('#container').html(res);
}
})
});
if your post script returns html then this should work. Let me know if otherwise :)
I solved this problem using formdata to send my image file to server
$(document).on("submit","form",function(e){
e.preventDefault();
var file = $("#product-file-i").val();
var p = $("#product-upload-f").children("input[name=name]").val();
$.ajax({
type:"post",
url:"profile.php",
data:new FormData(this),
contentType:false,
processData:false,
cache:false,
success: function(feedback){
alert(feedback);
},
error: function(){
}
});
});

Reload a single DIV on a page using onClick

In my page there are several DIVs, which are supposed to show different news items depending on the user selection and a press of a submit button.
Am I able to refresh only a single DIV when the relevant submit button is clicked?
I tried <input type ="button"> instead of <input type="submit"> but that didn't work as expected. My code is below:
<div class="dloader"></div>
<div class="search">
<form action="" method="post">
Furniture:
<input type="text" name="val1" id="val1" value="<?=$_POST['val1']?>" />
<input type="submit" value="Submit" name="submit" />
</form>
</div>
<?php
if( isset($_POST['submit']) ){
$postItemHeader = htmlentities($_POST['val1']);
}?>
<script>
$(window).load(function() {
$(".dloader").fadeOut("slow");
})
</script>
Take One Button For Post Event
<input type="submit" id="add" name="add" />
If You want to pass the Text Data, so a text value from the Text to fetch the particular data
<div id="result">Result should appear here</div>
Use Javascript To POst The Text Data To Back End
$(document.ready(function() {
$("#add").click(function(e) {
e.preventDefault();
$.ajax({
url: 'test.php',
type: 'POST',
data: $('#add').val,
success: function(data, status) {
$("#result").html(data)
}
});
});
});
What you need is AJAX. (read the documentation). A simple example is here.
The HTML
<div id="target_div"></div> <!-- Here is where you gonna place your new content -->
<input type='button' id='trigger' onClick="get_new_data()" value="Get new Content"> <!-- When this button is pressed get new content -->
The Javascript
function get_new_data()
{
$.ajax(
{
type: POST,
url: "you-url-here.php",
dataType:"HTML", // May be HTML or JSON as your wish
success: function(data)
{
$('div#target_div').html(data) // The server's response is now placed inside your target div
},
error: function()
{
alert("Failed to get data.");
}
}); // Ajax close
return false; // So the button click does not refresh the page
} // Function end

Complete Javascript Ajax php confusion

Hi all I am developing a site in Codeigniter and I have a form that I am posting using PHP and this is absolutely fine. However I have a small dropdown on the side of my page which I am using to jump between pages - in order to do this I am simply using a href and passing variables within the URL.
I need to POST some data however when they click on the link. I don't wish to use a button and was wondering whether this could be acheived using an ajax onclick() event?? - the data I need to post however is within the form. The code structure is roughly:
<form action="main/postback" method="post">
<input type="hidden" name="pagereference" value="2" />
<input type="hidden" name="supervariable" value="7" />
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname">
</form>
<div>
<ul>
<li><a href = 'http:localhost/landing'>click me</a></li>
</ul>
</div>
When someone clicks on the link I want to send an Ajax Post request, but In the php file that I am posting the data I want to be able to retrieve data from within the form. Is this possible? if so could someone please provide an example AJAX request and how to retrieve the data in PHP as I am majorly confused. I tried the following:
<li><a onclick='myFunction()'>click me</a></li>
<script type="text/javascript">
function myFunction()
{
var "test";
$.ajax({
type: "POST",
url: "http://localhost/ciproject/assessment/test",
dataType: String,
success: function(msg){
alert( "Data Saved: " + msg ); //Anything you want
}
});
window.alert("TEST");
}
</script>
Any ideas would be much appreciated, many thanks
You will probably run into problems using complete urls (with the domain name) due to CORS so I would recommend removing that, but you can easily do what you want using something like:
<li><a class="postFormLink">click me</a></li>
<script type="text/javascript">
$('.postFormLink').on('click', function() {
$.ajax({
type: "POST",
url: "/ciproject/assessment/test",
data: $('form').serialize(),
success: function(msg){
alert( "Data Saved: " + msg ); //Anything you want
}
});
window.alert("TEST");
}
</script>
If you have more than one form on your page, you should add an ID or a class to target it instead of using $('form').
Note that I have also removed the inline event handler.
Try the following:
<form action="main/postback" method="post" id="form1">
<input type="hidden" name="pagereference" value="2" />
<input type="hidden" name="supervariable" value="7" />
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname">
</form>
<li><a id="clickme">click me</a></li>
<script type="text/javascript">
$(function () {
$("#clickme").click(function () {
var form_data = $('#form1').serialize();
$.ajax({
type: "POST",
dataType: "text",
url: "ciproject/assessment/test",
data: form_data,
success: function(response){
alert('Job well done');
}
})
})
})
</script>
The following should work, if you put it into your ajax options. You will need to identify your form, the easiest way is to use an id.
data: $("#theFormId").serialize()

Trouble with AJAX and PHP

I have a form, and it has a field for entering a PIN code. Here I am using ajax for finding place when enter PIN code. It works when that field is not enclose in a form. If it is enclosed in a form, AJAX is not working.
HTML CODE:
<form id="form" class="blocks" action="#" method="post" enctype="multipart/form-data">
<div class="col_4 right">
<label for="fullname">FirstName:</label>
<input name="fname" type="text" class="text" />
</div>
<div class="col_4 right">
<label for="pincode">Pin-Code:</label>
<input name="pincode" type="text" class="text" id="pincode" />
<div id="section1"></div>
</div>
</form>
JS CODE:
<script>
$(document).ready(function() {
$('#pincode').keyup(function (e) {
if (e.keyCode == 13) {
//ajax request
$.ajax({
url: "pincode_check.php",
data: {
'pincode' : $('#pincode').val()
},
dataType: 'json',
success: function(data) { <!--console.log(data.success);-->
if(data.success){
//console.log(data.results[0].formatted_address.split(','))
var long_address=data.results[0].formatted_address.split(',');
console.log(long_address[0]);
$('#section1').append(long_address[0]);
}
}
});
}
});
});
</script>
PHP CODE(pincode_check.php):
<?php
$pincode=$_REQUEST['pincode'];
$geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$pincode.'&sensor=false');
$response= json_decode($geocode); //Store values in variable
$lat = $response->results[0]->geometry->location->lat; //Returns Latitude
$long = $response->results[0]->geometry->location->lng; // Returns Longitude
$geocode=file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng='.$lat.','.$long.'&sensor=false');
$data= json_decode($geocode);
if($data==true)
{ // Check if address is available or not
$data->results[0]->formatted_address ;
$data->success=true;
echo json_encode($data);
}
else {
$data->success= false;
echo json_encode($data);
}
?>
The default content type in $.ajax is application/x-www-form-urlencoded. But you've set your form content to multipart/form-data.
multipart/form-data is normally used for sending files with POST. I don't think you need that, so you don't need to specify enctype at all, just remove it and use the default form encoding, which is application/x-www-form-urlencoded.
(Additionally, the default request type in $.ajax is GET, so if you do want to send a file, you'll need to change that too..as well as add the attribute type="file" to your form I believe...)

Stop 2 Instances of an Ajax form on the same page interfering with each other

I've the following form twice on my homepage:
<form id="get-consultation-form" action="javascript:alert('success!');" >
<h3 class="sub-heading">Book a Consultation</h3>
<div id="message"></div>
<div id="fields">
<input type="text" maxlength="" name="Consultation[name]" placeholder="NAME" />
<input type="text" maxlength="" name="Consultation[number]" placeholder="NUMBER" />
<input type="text" maxlength="" name="Consultation[email]" placeholder="EMAIL" />
<button type="submit" class="btn">Submit</button>
</div>
</form>
The form uses jQuery/Ajax/PHP to forward the data via email:
$(document).ready(function() {
$("#get-consultation-form").submit(function() {
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "http://novicecoder.co.uk/priestley/consultation-process.php",
data: str,
success: function(msg) {
$(document).ajaxComplete(function(event, request, settings) {
NProgress.set(0.0);
if (msg === 'OK') {
result = '<div class="thanks" id="thanks">Thank you, we will contact you <span>shortly.</span></div>';
$(this).find("#fields").hide();
NProgress.set(0.5);
$("#message").hide();
$("#message").html(result).slideDown(100);
$("#message").html(result);
}
else
{
result = msg;
$("#message").hide();
$("#message").html(result).slideDown(200);
$("#message").html(result);
}
NProgress.set(1.0);
});
}
});
return false;
});
});
The first form is working perfectly, however as you'll see in my working example, the 2nd is not:
My website
Any ideas why this is happening????
IDs are unique.
Try to change form elements to diferent ids.
Or instead use classes.
If you use classes you can use $('.messages-class').closest() inside the form submit() for only interact in the current form.
You can't have an element with the same ID on a page twice. Replace your #get-consultation-form ID with a class, that should solve your issue. This also applies to the elements within the form like #fields and #message.

Categories