I'm trying to POST some JSON data to a local host and I keep getting a 404 Not Found error which is strange because the php file is located in the correct location as specified in the script. I would appreciate any feedback from anyone who has experience with this. Am I getting this error because the the server can not locate the ajax.php file for some unknown reason?
<div class="container">
<div class="header">
<h3 class="text-muted">AJAX JSON Data</h3>
</div>
<div id="data-div">
<form method="post" action="api/ajax.php" class="ajax">
<p><label for="firstname" class="contact-input-text">First Name</label> <br/>
<input id="first-name" name="firstname" type="text" maxlength="30" autofocus /></p><p><label for="lastName" class="contact-input-text">Last Name</label> <br/>
<input id="last-name" name="lastname" type="text" maxlength="30" autofocus /></p>
<p><input type="submit" id="submit-button" class="contact-input-text" value="submit" /></p>
</form>
</div>
</div>
<script>
$('form.ajax').on('submit', function(){
var jsondata = {};
$(this).find('[name]').each(function(i, data){
console.log(data);
var that = $(this);
var key = that.attr('name');
var value = that.val();
jsondata[key] = value;
});
console.log(jsondata);
$.ajax({
type: 'POST',
url: 'ajax.php',
dataType: 'json',
data: jsondata,
success: function(response){
console.log(response);
},
error: function(xhr){
console.log(xhr);
}
});
return false;
</script>
Here is the ajax.php file....
<?php
if(isset($_POST['submit'])) {
$file = "data.json";
$json_string = json_encode($_POST,JSON_PRETTY_PRINT);
file_put_contents($file,$json_string,FILE_APPEND);
}
?>
This is the directory structure :
index.html (contains the form input fields and the ajax request)
ajax.php
/styles
/images
have you ensure with correct url in ajax?
maybe not thi:
url: 'ajax.php'
but this:
url: 'api/ajax.php'
Related
I want to call input value from javascript
My home page code :
<form method="post" id="form">
<div class="row">
<div class="col-md-6">
<label for="f_name">First Name</label>
<input type="text" class="form-control" name="f_name "id="f_name" value="">
</div>
<div class="col-md-6">
<label for="l_name">Last Name</label>
<input type="text" class="form-control" name="l_name" id="l_name" value="">
</div>
</div>
....
javascript code :
$("#singup_btn").click(function(event){
event.preventDefault();
$.ajax({
url : "register.php",
method : "POST",
data : $("form").serialize(),
success : function(data){
alert(data);
}
})
})
...calling page code :
<?php
include "db.php";
$fname = $_POST["f_name"];
$lname = $_POST["l_name"];
...
echo $fname;
...error while click button, only last name (input) value defined
<br />
<b>Notice</b>: Undefined index: f_name in <b>D:\xampp\htdocs\shop\register.php</b> on line <b>5</b><br />
<br />
<b>Notice</b>: Undefined index: email in <b>D:\xampp\htdocs\shop\register.php</b> on line <b>7</b><br />
<br />
<b>Notice</b>: Undefined index: password in <b>D:\xampp\htdocs\shop\register.php</b> on line <b>8</b><br />
please someone help me?
I stuck like more than 4 hours on this. Im learning javascript n php, n still newbie. Please help. thanks.
You are missing a # You also have an error in your first input field.
<input name="f_name ">
shouldbe
<input name="f_name">
$("#singup_btn").click(function(event){
event.preventDefault();
$.ajax({
url : "register.php",
method : "POST",
data : $("#form").serialize(),
success : function(data){
alert(data);
}
})
})
try this code
$(document).on('click', '#singup_btn', function() {
$.ajax({
url : "register.php",
type : "POST",
data : $("#form").serialize(),
success : function(data){
alert(data);
}
});
});
Please remove type="submit" from submit button and add type="button". It will work!
Serializing the form with a space in name="f_name "id="f_name" forces a + to be appended to the serialized value. This is why its not being picked up correctly server side.
Expected server side value
f_name=asd&l_name=asd
Actual server side value
f_name+=asd&l_name=asd
see test below
$("button").click(function()
{
//output values before serialization
console.log( "Result of f_name");
console.log ($("#f_name").val() );
console.log( "Result of l_name");
console.log ($("#l_name").val() );
//output values after serialization
var serialized = $("form").serialize();
console.log( "Result: Notice how f_name has an appended + in its key");
console.log( "'" + serialized + "'");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="form">
<div class="row">
<div class="col-md-6">
<label for="f_name">First Name</label>
<input type="text" class="form-control" name="f_name "id="f_name" value="">
</div>
<div class="col-md-6">
<label for="l_name">Last Name</label>
<input type="text" class="form-control" name="l_name" id="l_name" value="">
</div>
</div>
<button type="button"> test </button>
</form>
Credit to Chris
My code here works fine except image uploading. It inserts all data in database .
<input type="file" name="image2" class="file" id="imgInp"/>
But after adding file type input in php it is showing
Notice: Undefined index: image2 in C:\xampp\htdocs\upload\submit.php on line 18
How can I add image uploading function in my existing code.
<div id="form-content">
<form method="post" id="reg-form" enctype="multipart/form-data" autocomplete="off">
<div class="form-group">
<input type="text" class="form-control" name="txt_fname" id="lname" placeholder="First Name" required /></div>
<div class="form-group">
<input type="text" class="form-control" name="txt_lname" id="lname" placeholder="Last Name" required /></div>
<div class="form-group">
<input type="text" class="form-control" name="txt_email" id="lname" placeholder="Your Mail" required />
</div>
<div class="form-group">
<input type="text" class="form-control" name="txt_contact" id="lname" placeholder="Contact No" required />
</div>
// here is the problem
<input type="file" name="image2" class="file" id="imgInp"/>
//here is the problem
<hr />
<div class="form-group">
<button class="btn btn-primary">Submit</button>
</div>
</form>
</div>
<script type="text/javascript">
$(document).ready(function() {
// submit form using $.ajax() method
$('#reg-form').submit(function(e){
e.preventDefault(); // Prevent Default Submission
$.ajax({
url: 'submit.php',
type: 'POST',
data: $(this).serialize() // it will serialize the form data
})
.done(function(data){
$('#form-content').fadeOut('slow', function(){
$('#form-content').fadeIn('slow').html(data);
});
})
.fail(function(){
alert('Ajax Submit Failed ...'); });
});
</script>
submit.php
<?php
$con = mysqli_connect("localhost","root","","table" ) or die
( "unable to connect to internet");
include ("connect.php");
include ("functions.php");
if( $_POST ){
$fname = $_POST['txt_fname'];
$lname = $_POST['txt_lname'];
$email = $_POST['txt_email'];
$phno = $_POST['txt_contact'];
$post_image2 = $_FILES['image2']['name']; // this line shows error
$image_tmp2 = $_FILES['image2']['tmp_name'];
move_uploaded_file($image_tmp2,"images/$post_image2");
$insert =" insert into comments
(firstname,lastname,email,number,post_image) values('$fname','$lname','$email','$phno','$post_image2' ) ";
$run = mysqli_query($con,$insert);
?>
You can use FormData, also I suggest you can change the elements id of the form, now all of them have ('lname') Try this with your current:
In yout HTML, put an ID to your file input
<input type="file" name="image2" id="name="image2"" class="file" id="imgInp"/>
And change the id of the other input.
In your JavaScript:
var frmData = new FormData();
//for the input
frmData.append('image2', $('#image2')[0].files[0]);
//for all other input
$('#reg-form :input').each(function(){
if($(this).attr('id')!='image2' ){
frmData.append($(this).attr('name'), $(this).val() );
}
});
$.ajax( {
url: 'URLTOPOST',
type: 'POST',
data: frmData,
processData: false,
contentType: false
}).done(function( result ) {
//When done, maybe show success dialog from JSON
}).fail(function( result ) {
//When fail, maybe show an error dialog
}).always(function( result ) {
//always execute, for example hide loading screen
});
In your PHP code you can access the image with $_FILE and the input with $_POST
FormData() works on the modern browsers.If you want for older browser support use malsup/form plugin
Your Form
<form method="post" action="action.php" id="reg-form" enctype="multipart/form-data" autocomplete="off">
Javscript
<script type="text/javascript">
var frm = $('#reg-form');
frm.submit(function (ev) {
var ajaxData = new FormData(frm);
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: ajaxData,
contentType: false,
cache: false,
processData:false,
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
In php extract($_POST) to get all input data and $_FILE for files
good day. I have a code which can upload image file but I don't know if this code is also work for uploading media file such as mp3. My project need to upload a media file but my code didn't work.
view
form
<form name="uploadform" id="uploadform" method="POST" enctype="multipart/form-data" >
<div class="form-group">
<label for="Title">Song Title</label>
<input type="text" class="form-control" id="title" placeholder="Title">
</div>
<div class="form-group">
<label for="Artist">Artist/Singer</label>
<input type="text" class="form-control" id="artist" placeholder="Artist/Singer">
</div>
<div class="form-group">
<label for="lyrics">Lyrics</label>
<textarea class="form-control" id="lyrics" placeholder="Lyrics"></textarea>
</div>
<div class="form-group">
<label for="Artist">Audio</label>
<input type="file" class="form-control" name="file" id="file" accept="audio/mp3">
</div>
<div class="form-group">
<span class="input-group-btn">
<button class="btn btn-primary" id="btn">UPLOAD</button>
</span>
</div>
</form>
view
javascript
$('#btn').click(function() {
var title = document.getElementById('title').value;
var artist = document.getElementById('artist').value;
var lyrics = document.getElementById('lyrics').value;
var file = $('#file').val();
$.ajax({
type: "post",
url: "<?php echo base_url('Admin/upload/')?>",
cache: false,
mimeType: "multipart/form-data",
contentType: false,
processData: false,
data: {
"title" : title,
"artist" : artist,
"lyrics" : lyrics,
"file" : file,
},
success: function(data){
try{
console.log(data);
}catch(e) {
alert('Exception while request..');
}
},
error: function(){
alert('Error while request..');
}
});
});
controller
Admin.php
public function upload()
{
$title = $this->input->post('title');
$artist = $this->input->post('artist');
$lyrics = $this->input->post('lyrics');
$attachment_file=$_FILES["file"];
$output_dir = "uploads/";
$fileName = $_FILES["attachment_file"]["name"];
move_uploaded_file($_FILES["attachment_file"]["tmp_name"],$output_dir.$fileName);
echo "File uploaded successfully";
}
that code gave me an error message.
<h4>A PHP Error was encountered</h4>
<p>Severity: Notice</p>
<p>Message: Undefined index: file</p>
<p>Filename: controllers/Admin.php</p>
<p>Line Number: 35</p>
I do not know why the file is undefined index since the 'file' is exist on form tag.
my code is not working for uploading mp3. How can I make this problem works?
I want to show the user a form sent correctly alert message with javascript using bootstraps built in alerts.
When I run the code I get the object array of the values (inspecting the page at console log). what I want to do is after it is sent, to display a success alert (if it is a success).
there is test4.sj which contains the javascript code and then there is main.php which is the code for the form.
The code that I have so far is in the snippet.
$('form.ajax').on('submit', function() {
var that = $(this),
type = that.attr('action'),
data = {};
that.find('[name]').each(function(index, value) {
//console.log(value);
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
console.log(data);
/* $.ajax({
url: url,
type: type,
data: data,
success: function(response){
console.log(response);
}
})*/
return false;
})
<body>
<form method="post" class="ajax">
<div>
<input name="name" type="text" placeholder="Your name" required>
</div>
<div>
<input name="lName" type="text" placeholder="Your Last Name">
</div>
<div>
<textarea name="message" placeholder="Your Message"></textarea>
</div>
<input type="submit" value="Send">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</body>
Just add hidden alert panel and show it on AJAX success.
HTML:
<form method="post" class="ajax">
<div class="alert alert-success js-alert hidden" role="alert">
Form was successfully sent!
</div>
...
<div>
<input name="name" type="text" placeholder="Your name">
</div>
...
<button type="submit" class="btn js-btn">Send</button>
</form>
JS:
$('form').on('submit', function( event ) {
var $form = $( this );
event.preventDefault();
$('.js-alert').addClass('hidden');
$('.js-btn').button('loading');
$.ajax({
url: '/someurl',
type: 'POST',
data: $form.serialize(),
success: function(response){
$('.js-alert').removeClass('hidden');
$('.js-btn').button('reset');
}
});
});
Check the fiddle:
https://jsfiddle.net/xw63db57/1/
you can use ajax jqXHR status and statusCode and based up on that you can write the alert code
success(data, textStatus, jqXHR){
var statusCode = jqXHR.status;
var statusText = jqXHR.statusText;
}
I'm using a Google Form's value to integrate with my website where I want to submit the form and store data in google sheet as form responses. I'm using AJAX to redirect to another page instead of google form submit page. But whenever I'm trying to submit it's redirecting to my page accurately but datas are not saved in google sheet. Here are my codes,
<strong>Full Name</strong>
<input type="text" name="Fullname" class="form-control" id="Fullname" />
<strong>Email Address</strong>
<input type="text" name="Email" class="form-control" id="Email" />
<strong>Subject</strong>
<input type="text" name="Subject" class="form-control" id="Subject" />
<strong>Details</strong>
<textarea name="Details" rows="8" cols="0" class="form-control" id="Details"></textarea><br />
<button type="button" id="btnSubmit" class="btn btn-info" onclick="postContactToGoogle()">Submit</button>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
function postContactToGoogle() {
var email = $('#Email').val();
var fullname = $('#FullName').val();
var subject = $('#Subject').val();
var details = $('#Details').val();
$.ajax({
url: "https://docs.google.com/forms/d/abcdefgh1234567xyz/formResponse",
data: {
"entry_805356472": fullname,
"entry_1998295708": email, "entry_785075795":
subject, "entry_934055676": details
},
type: "POST",
dataType: "xml",
statusCode: {
0: function () {
window.location.replace("Success.html");
},
200: function () {
window.location.replace("Success.html");
}
}
});
}
</script>
How can I save the data in google sheet? Am I missing something in my code? Need this help badly? Thanks.
You can directly copy the form from google view form page like shown in the demo, and then do the following changes in the AJAX call as shown below.
And now once you submit data it is visible in google forms, view responses.
$(function(){
$('input:submit').on('click', function(e){
e.preventDefault();
$.ajax({
url: "https://docs.google.com/forms/d/18icZ41Cx3-n1iW7yTOZdiDx9a6mySWHOy9ryd1l59tM/formResponse",
data:$('form').serialize(),
type: "POST",
dataType: "xml",
crossDomain: true,
success: function(data){
//window.location.replace("youraddress");
//console.log(data);
},
error: function(data){
//console.log(data);
}
});
});
});
<div class="ss-form"><form action="https://docs.google.com/forms/d/18icZ41Cx3-n1iW7yTOZdiDx9a6mySWHOy9ryd1l59tM/formResponse" method="POST" id="ss-form" target="_self" onsubmit=""><ol role="list" class="ss-question-list" style="padding-left: 0">
<div class="ss-form-question errorbox-good" role="listitem">
<div dir="auto" class="ss-item ss-text"><div class="ss-form-entry">
<label class="ss-q-item-label" for="entry_1635584241"><div class="ss-q-title">What's your name
</div>
<div class="ss-q-help ss-secondary-text" dir="auto"></div></label>
<input type="text" name="entry.1635584241" value="" class="ss-q-short" id="entry_1635584241" dir="auto" aria-label="What's your name " title="">
<div class="error-message" id="1979924055_errorMessage"></div>
<div class="required-message">This is a required question</div>
</div></div></div>
<input type="hidden" name="draftResponse" value="[,,"182895015706156721"]
">
<input type="hidden" name="pageHistory" value="0">
<input type="hidden" name="fvv" value="0">
<input type="hidden" name="fbzx" value="182895015706156721">
<div class="ss-item ss-navigate"><table id="navigation-table"><tbody><tr><td class="ss-form-entry goog-inline-block" id="navigation-buttons" dir="ltr">
<input type="submit" name="submit" value="Submit" id="ss-submit" class="jfk-button jfk-button-action ">
</td>
</tr></tbody></table></div></ol></form></div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
If you go to your form on Google and click on 'View Live Form', and then view source on the form, you'll see that the fields you want to upload have aname in the form entry.12345678; the id is in the form entry_12345678. You need to use the name value. Try this:
<script>
function postContactToGoogle() {
var email = $('#Email').val();
var fullname = $('#FullName').val();
var subject = $('#Subject').val();
var details = $('#Details').val();
$.ajax({
url: "https://docs.google.com/forms/d/abcdefgh1234567xyz/formResponse",
data: {
"entry.805356472": fullname,
"entry.1998295708": email,
"entry.785075795": subject,
"entry.934055676": details
},
type: "POST",
dataType: "xml",
statusCode: {
0: function () {
window.location.replace("Success.html");
},
200: function () {
window.location.replace("Success.html");
}
}
});
}
</script>