php javascript form serialize get data undefined index - javascript

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

Related

How to handle validation errors in laravel5.1 using ajax/jquery

Im creating a validation now using laravel5.1 with ajax of jquery. Everything works fine. But, what I want is to display the errors each <inputs> just like when using validation without ajax. Please see my code below, and the picture for the sample output. I've also tried it with #if of blade(laravel), but not working.
Note: Im using bootstrap framework too.
<div class="row">
<div class="col-md-6">
<div id="result">
<ul></ul>
</div>
<form action="" method="post" id="create">
<div class="form-group">
<label for="name" class="control-label">Name</label>
<input type="text" name="name" id="name" class="form-control">
</div>
<div class="form-group">
<label for="description" class="control-label">Description</label>
<textarea name="description" id="description" cols="30" rows="10" class="form-control"></textarea>
</div>
<div class="form-group">
<label for="type" class="control-label">Type</label>
<input type="text" name="type" id="type" class="form-control">
</div>
<div class="form-group">
<label for="price" class="control-label">Price</label>
<input type="text" name="price" id="price" class="form-control">
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-success">
</div>
{{ csrf_field() }}
</form>
</div>
</div>
<script>
$(document).ready(function(){
var url = '{{ route('ajax-push') }}';
var token = '{{ csrf_token() }}';
$('#create').on('submit', function(){
$.ajax({
type: 'POST',
url: url,
data: { _token: token },
dataType: 'json',
success: function(data){
console.log(data);
},
error: function(data){
var errors = data.responseJSON;
$('#result').removeClass('alert').removeClass('alert-danger');
$('#result > ul').empty();
$.each(errors, function(i, item){
$('#result').addClass('alert').addClass('alert-danger');
$('#result > ul').append('<li>' + item + '</li>');
});
}
});
return false;
});
});
</script>
Controller
public function postAjaxCreate(Request $request){
$validator = $this->validate($request, [
'name' => 'required|max:255',
'description' => 'required|min:2',
'type' => 'required|max:255',
'price' => 'required|numeric'
]);
if($validator->fails()){
return response()->json($validator->messages(), 200)->with($validator->messages());
}
}
You need to pass the from data to the ajax request
data: $('#create').serialize(),
and most likely the response doesn't have a responseJSON property, and you are sending the data twice from, remove the with function in you php function
Add the errors to the page using something similar to the following js:
$.each(data, function(i, item){
$('#'+i).addClass('alert alert-danger');
('#'+i).after('<p>' + item + '</p>');
});

Post data to database using AJAX

I asked yesterday a similar question and i resolved the answer myself in which i wanted to add data into the database using ajax to avoid refreshing the page.
Now, i wish to do the same thing, but update the data in the database.
Im not sure if the issue is caused by having 2 ajax script requests on the same page..
I am trying to submit this form:
I should probably tell you, this form is in a modal screen
<form id="editarticleform" method="post">
<div class="form-group">
<input type="hidden" class="form-control" id="blog-id" name="blog-id" value="<?php echo $list['id']; ?>">
</div>
<div class="form-group">
<label for="blog-title">Article title</label>
<input type="text" class="form-control" id="blog-title" name="blog-title" placeholder="Blog title" value="<?php echo $list['blog_title']; ?>" required>
</div>
<div class="form-group">
<label for="blog-content">Article content</label>
<textarea class="form-control" id="blog-content" name="blog-content" placeholder="Blog content" required><?php echo $list['blog_body']; ?></textarea>
</div>
<div class="form-group">
<label for="exampleInputFile">Article image</label>
<input type="file" class="form-control-file" id="article-image" name="article-image" aria-describedby="fileHelp" value="<?php echo $list['blog_image']; ?>">
<small id="fileHelp" class="form-text text-muted">This is the image that will appear along side the article.</small>
</div>
<fieldset class="form-group">
<legend>Active</legend>
<div class="form-check">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="active-inactive" id="optionsRadios1" value="1" checked>
Article is active - Will be shown in the blog.
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="active-inactive" id="optionsRadios2" value="0">
Article is inactive - Will not show.
</label>
</div>
</fieldset>
<fieldset class="form-group">
<legend>Comments</legend>
<div class="form-check">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="enable-comments" id="enable-comments1" value="1" checked>
Enable comments - Users can post comments
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="enable-comments" id="enable-comments2" value="0" aria-describedby="disableComments">
Disable comments - Users cannot post comments
<small id="disableComments" class="form-text text-muted">If you disable comments for users, administrators will still be able to post comments.</small>
</label>
</div>
</fieldset>
<button type="submit" id="edit_article" name="edit_article" class="btn btn-primary">Save</button>
</form>
Updating the database using this script:
<?php
require_once("../../includes/database.class.php");
session_start();
$uid = $_SESSION['uid'];
$id = $_POST['blog-id'];
$title = $_POST['blog-title'];
$content = $_POST['blog-content'];
$image = $_POST['article-image'];
$active = $_POST['active-inactive'];
$comments = $_POST['enable-comments'];
$sql = "UPDATE blog_article SET blog_title = '$title', blog_body = '$content', blog_image = '$image', active = '$active', comments = '$comments' WHERE id = '$id'";
// print_r($sql);
$result = $database->query($sql);
if ($result) {
echo "Article updated.";
}else {
echo "Query failed" . print_r($sql);
}
?>
Via AJAX to avoid refreshing the page:
<script>
var submit = $('#edit_article');
submit.click(function() {
var data = $("#editarticleform").serialize();
var update_div = $('#update_div');
$.ajax({
data: data,
type: 'post',
url: '/editarticle.php',
success:function(html){
update_div.html(html);
}
});
});
</script>
As with the last question, the script works perfectly fine if i directly set the form action to the editarticle.php script. When i implement the ajax script, it doesn't update the database.
I am unsure if its got something to do with the blog-id, but thats what my head immediately thinks it is.. Or it may be that i am being blind and its a tiny little issue..
I suspect that the click event isn't triggered. Perhaps try something like this:
<script>
// Wait for document ready
$(function(){
$(document).on('click', '#edit_article', function() {
var data = $("#editarticleform").serialize();
var update_div = $('#update_div');
$.ajax({
data: data,
type: 'post',
url: '/editarticle.php',
success: function(html){
update_div.html(html);
}
});
});
});
</script>
Check the Network tab of your browser's developer tools to see that anything gets sent to the backend, and the request headers to see if all the necessary data is included.
I would do the following to debug;
Check what you are sending to the php file, to see if blog-id value is not empty. by doing var data = $("#editarticleform").serialize();
console.log(data);
Change your ajax url to url: 'editarticle.php' ,because it seems your ajax probably doesn't see the php file.
if you use modal bootstrap try this :
$('#myModal').on('shown.bs.modal', function () {
var submit = $('#edit_article');
submit.click(function () {
var data = $("#editarticleform").serialize();
var update_div = $('#update_div');
$.ajax({
data: data,
type: 'post',
url: '/editarticle.php',
success: function (html) {
update_div.html(html);
}
});
});
})
check this
<script>
// Wait for document ready
$(document).ready(function(){
$("#edit_article").click(function() {
var data = $("#editarticleform").serialize();
var update_div = $('#update_div');
$.ajax({
url: 'editarticle.php',
type: 'post',
data: data,
success: function(html){
update_div.html(html);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
});
});
</script>
If still doesn't work try to send raw data with ajax and check if it works
data: "blog-id="+blog-id

Add image uploading function inside this existing ajax code

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

PHP Ajax response is empty using jQuery

At the moment I create a register "page". Here is the html code of the form
<form class="register_form" method="POST" action="insert.php">
<label class="label_register">Benutzername*:</label>
<div class="input_group">
<input class="input_register" id="register_username" name="username" type="text"/><span class="register_span">-</span>
</div>
<label class="label_register">Passwort*:</label>
<div class="input_group">
<input class="input_register" id="register_password_1" name="password" type="password"/><span class="register_span">-</span>
</div>
<label class="label_register">Passwort wdh.*:</label>
<div class="input_group">
<input class="input_register" id="register_password_2" name="password2" type="password"/><span class="register_span">-</span>
</div>
<label class="label_register">E-Mail Adresse*:</label>
<div class="input_group">
<input class="input_register" id="register_email" name="email" type="text"/><span class="register_span">-</span>
</div>
<button class="button button_register">Jetzt kostenlos registrieren</button>
<p class="register_hint">
* Pflichtfeld
</p>
</form>
Here is my jquery code
var username_bool = true;
var password_bool = true;
var email_bool = true;
$('.register_form').on('submit', function(){
if(username_bool == true && password_bool == true && email_bool == true){
$.ajax({
type: "POST",
url: "insert.php",
data: $(this).serialize(),
success: function(response){
console.log(response);
alert(response);
},
});
}
else{
alert("---");
}
return false;
});
And here is the php code
<?php
if(isset($_POST["username"]) && isset($_POST["password_1"]) && isset($_POST["email"])){
echo "response";
}
?>
Now I have sent the form, but the respone is empty. I use Firebug to debugg. What is my mistake? And I made also other mistakes?
Thanks for you help.
You seem to be checking for a field named password_1
isset($_POST["password_1"])
while it's named password
<input class="input_register" id="register_password_1" name="password" type="password"/><span class="register_span">-</span>
You'll have to make sure the name attribute matches the value you're checking
The problem i see is you check on isset($_POST["password_1"]) and that is not in the form as you named your password field "password"
<input class="input_register" id="register_password_1" name="password" type="password"/><span class="register_span">-</span>
you need to check using isset($_POST["password"])

404 Not Found on Jquery AJAX JSON PHP POST

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'

Categories

Resources