Submitting Form using jquery AJAX [duplicate] - javascript

This question already has answers here:
jQuery AJAX submit form
(20 answers)
Closed last year.
I am trying to submit my form using jQuery ajax, but my data isn't posting to PHP it returns empty array nothing in $_POST array.
This is my code - here is my form:
<form action = "/webdevelopmentpakistan/send_mail.php" method = "post" class = "myForm" >
<div class="row">
<div class="col-md-3 col-sm-12">
<div class="form-group">
<input class="form-control" id="fname" type="text" required name= "full_name" placeholder="Full Name"
/>
</div>
</div>
<div class="col-md-3 col-sm-12">
<div class="form-group">
<input class="form-control" type="tel" required name = "phone" placeholder="+92" id="phone" onkeypress="return isNumberKey(event)" />
</div>
</div>
<div class="col-md-3 col-sm-12">
<div class="form-group">
<input class="form-control" type="email" required name = "email" id="email" placeholder="Email"/>
</div>
</div>
<div class="col-md-3 col-sm-12">
<div class="form-group">
<input class="btn popup" type="submit" name = "submit" value="CONTACT OUR CONSULTANT"/>
</div>
</div>
</div>
</form>
its an ajax part:
$('form').on('submit', function (e) {
e.preventDefault();
var url = $(this).attr("action");
var form_data = $(this).serialize();
$.ajax({
type: 'POST',
url: url,
data: $('.myForm').serialize() ,
dataType : 'JSON',
//contentType: "application/x-www-form-urlencoded",
success: function (data) { // here I'm adding data as a parameter which stores the response
console.log(data); // instead of alert I'm changing this to console.log which logs all the response in console.
},
error:function(xhr, textStatus, thrownError, data)
{
console.log("Error: " + thrownError);
console.log("Error: " + textStatus);
}
});
// var popup = document.getElementById("myPopup");
// popup.classList.toggle("show");
console.log(form_data);
});
PHP CODE using at other page:
if(isset($_POST)) {
echo json_encode($_POST);
}
and this is my serialize array which I am getting on submission of form but it isn't getting passed to php
full_name=talha&phone=012345678&email=admin%40gmail.com

welcome to stackoverflow, here are the changes, hope it will works
$.ajax({
type: 'POST',
url: url,
data: $('.myForm').serialize() ,
dataType : 'json', // changing data type to json
success: function (data) { // here I'm adding data as a parameter which stores the response
console.log(data); // instead of alert I'm changing this to console.log which logs all the response in console.
}
});
in php
if(isset($_POST)) {
echo json_encode($_POST);
}
this should print array of post parameters in your console, however you will get an array in php.

The form action needs to be either absolute url i.e. https://somewebsite.com or a relative url on you site so ideally it should be /some-url.php. Read about form action here
So your form opening tag should be,
<form action = "/web-development-in-pakistan.php" method = "post" class = "myForm" target="_self">
So in your javascript code when you do
var url = $(this).attr("action");
I also believe that in your ajax call, the type needs to be method, so,
$.ajax({
method: "POST",
.....
})

Related

how to solve Ajax post request show 500 (Internal Server Error) in laravel

In my project i want to store data in to database using ajax but when i submit the post request it show the error like (500 (Internal Server Error)) i google it several time but still same issue
this is my ajax code
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#form-insert').on('submit', function(e){
e.preventDefault();
var data = $(this).serialize();
var url = $(this).attr('action');
var post = $(this).attr('method');
$.ajax({
type: post,
url: url,
data:{
_token: '{!! csrf_token() !!}',
data
},
dataType: 'json',
success:function(data){
console.log(data)
}
})
})
this is my view
<form method="post" id="form-insert" action="{{ URL::to('item/store')}}">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name">
</div>
<div class="form-group">
<label for="text">Email address:</label>
<input type="email" class="form-control" name="email">
</div>
<div class="form-group">
<label for="contact_no">Contact No:</label>
<input type="text" class="form-control" name="contact_no">
</div>
<button type="submit" class="btn btn-primary pull-right" id="add">Submit</button>
</form>
this is my route
Route::post('/item/store', 'AjaxCrudController#store');
this is my controller
public function store(Request $request)
{
if($request->ajax()){
$item = AjaxCrud::create($request->all());
return response($item);
//return response($request->all());
}
}
You are trying to insert the data you are submitting in your ajax request:
data:{
_token: '{!! csrf_token() !!}',
data
}
That means that you are trying to create an AjaxCrud resource containing two keys: _token and data. I suppose that you just want to store the data contained into the data object, that is your serialized form and should contain a name attribute.
So you have multiple solutions, the first one is to create your AjaxCrud resource from the data object:
$item = AjaxCrud::create($request->get('data'));
The other solution is to send only the data you want in your ajaxRequest, and set your CSRF token into the headers of your request.

Submit a form with a file without refresh

Hello guys i don't know to submit a form without page refresh.
This is my code:
My form:
<form method="POST" id="post123" action="" enctype="multipart/form-data">
<input class="form-control input-lg" name="book_name" id="inputLarge" type="text">
<input class="form-control" name="book_price" type="number">
<textarea class="form-control" id="exampleTextarea2"
name="book_description" maxlength="100" rows="7"></textarea>
<textarea class="form-control" name="book_content" id="exampleTextarea4" maxlength="200" rows="7"></textarea>
<input type="file" name="file" id="imgInp44" >
<button type="submit" name='action' id="sendbutton21" value="post1" class="btn btn-primary">
Submit
</button>
</form>
Javascript:
$("#sendbutton21").click(function() {
var url = "http://localhost:5000/magazin_insert"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#post123").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
How i can modify my code to submit along with text a file towards the mysql db?
Your first issue is in this line:
<button type="submit" name="action" ... />
You have two possibilities:
change type="submit" to type="button"
use event.preventDefault() in your $("#sendbutton21").click(function() {
After, your ajax call can be changed in order to include the file:
var form = document.getElementById('post123');
var formData = new FormData(form);
$.ajax({
url: url,
data: formData,
type: 'POST',
processData: false,
success: function(data) {
alert(data);
}
});
$("#sendbutton21").click(function() {
var url = "http://localhost:5000/magazin_insert"; // the script where you handle the form input.
// for testing...
url = 'https://api.github.com/repositories';
var form = document.getElementById('post123');
var formData = new FormData(form);
$.ajax({
url: url,
data: formData,
type: 'GET',
processData: false,
success: function (data) {
console.log(data[0].id);
}
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<form method="POST" id="post123" action="" enctype="multipart/form-data">
<input class="form-control input-lg" name="book_name" id="inputLarge" type="text">
<input class="form-control" name="book_price" type="number">
<textarea class="form-control" id="exampleTextarea2"
name="book_description" maxlength="100" rows="7"></textarea>
<textarea class="form-control" name="book_content" id="exampleTextarea4" maxlength="200" rows="7"></textarea>
<input type="file" name="file" id="imgInp44" >
<button type="button" name='action' id="sendbutton21" value="post1" class="btn btn-primary">
Submit
</button>
</form>
Try https://jquery-form.github.io/form/ plugin to easily send form via ajax sample code:
$('#post123').ajaxForm(function() {
// SUCCESS CALLBACK
});
To submit a form without refresh, use event.preventDefault().
$("#sendbutton21").click(function(event) {
event.preventDefault();
var url = "http://localhost:5000/magazin_insert"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#post123").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
Instead of
$("#sendbutton21").click(function() {
use
$("#post123").submit(function() {

button type submit refreshes page instead of triggering ajax network request [duplicate]

Alright, I have a simple form comprising of only a text field. Data written in the text field is stored in DB when we hit submit (Stored via ajax). The ajax works fine and data is submitted, however, the page get's refreshed automatically and the URL contains the content of the input field.
My Form :-
<form class="form-horizontal">
<fieldset>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="message"></label>
<div class="col-md-5">
<input id="message" name="message" type="text" placeholder="message" class="form-control input-md" required="">
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="submit_message"></label>
<div class="col-md-4">
<button id="submit_message" name="submit_message" class="btn btn-success">Enter</button>
</div>
</div>
</fieldset>
</form>
Ajax :-
$("#submit_message").click(function() {
var message = $("#message").val();
$.ajax({
type: "POST",
url: "ajax_getter.php?requestid=2",
data: { message: message, c: c },
dataType: "html"
}).done(function( msg ) {
//load_content();
alert(msg);
});
});
PHP :-
//...
if($chat->insert("chat_threads", $arr))
{
echo 1;
}
else
{
echo 0;
}
After the result is show in the popup, the page refresh and the URL becomes something like :- chat.php?message=454545&submit_message=
Why is the page being refreshed ?
Seems that your form is being submitted. Try preventing the default event (i.e. submission):
$("#submit_message").click(function(e) {
e.preventDefault(); // This prevents form from being sumbitted
// the rest of your code
});

How to submit form using Ajax in MVC

I am getting problem to save my form data in the database. I am done small code on that which is shown below, when i enter data in form and click on my submit button it not work.
$(".btn").click(function(e) {
e.preventDefault();
var form = $("#frm");
$.ajax({
url: '/Form/Index',
data: form.serialize(),
type: 'POST',
success: function(data) {
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form role="form" id="frm">
<div class="form-group">
<div class="col-sm-6 col-lg-12 col-md-12">
<div class="form-group">
<label for="name" style="color:black;">Product Name</label>
<input type="text" class="form-control" id="name"
placeholder="Product Name" style="color:black;">
</div>
<div class="form-group">
<label for="name" style="color:black;">Product Date</label>
<input type="text" class="form-control" id="Text1"
placeholder="Date" style="color:black;">
</div>
<div class="form-group">
<label for="name" style="color:black;">Product Price</label>
<input type="text" class="form-control" id="Text2"
placeholder="Date" style="color:black;">
</div>
</div>
</div>
<button type="submit" class="btn btn-default" id="ok" >Submit</button>
</form>
Above is my code please give me solution on that
As I've checked you code, client side code is working fine, The only problem I can imagine in this case is you url path.
make sure you are providing correct url path.
You should check if its hitting the that page or not.
Which Framework you are using. Different framework has different syntax to pass the value in URL. Check the path you are getting in the page source page view in URL parameter or you can check the error in console log after the submit. It may be not getting the correct path of your action.
Make sure ajax library loaded successfully, and try to have alert messages to have forward step where you reached, have this test:
$(".btn").click(function(e) {
e.preventDefault();
var form = $("#frm");
$.ajax({
url: '/Form/Index',
data: form.serialize(),
type: 'POST',
success: function(data) {
},
beforeSend: function() {
alert('before send alert')
},
error: function (request, status, error) {
alert(error);
},
});
});
if beforeSend not executed so your issue is related to ajax library.
use this :
$("#ok").click(function(e) {
// your code
}
Refer to id in javascript rather than class attribute.
If you refer class attribute than once it has click javascript perform preventDefault on that class so that if not refresh your page, The button is not working.
Put preventDefault function at last of your function.
Remove the type="submit" from button
You have to get the form submit with id and serialize the form data
`
$("#formid").submit(function(e) {
var url = "urlpathtohandlerequest";
$.ajax({
type: "POST",
url: url,
data: $("#formid").serialize(),
success: function(response)
{
alert(response);
}
});
e.preventDefault(); // stops default submit.
});
`

Ajax POST always returns error

I'm trying to submit a form via ajax POST to a servlet, process the parameters and then send a response. It always winds up giving me an error.
Form html :
<form id="login" >
<div class="form-group">
<label for="username"> Username : </label>
<input id="username" name="username" type="text" class="form-control" placeholder="Name">
</div>
<div class="form-group">
<label for="password"> Password : </label>
<input id="password" type="password" name="password" class="form-control" placeholder="*******">
</div>
<button id="loginBtn" onclick="posaljiLogParametre()" value="Submit" class="btn btn-primary" type="submit"> Uloguj se </button>
</form>
Ajax post :
$.ajax({
type: "POST",
url: "LogInServlet",
dataType: 'text',
data: $("#login").serialize(),
success: function (data) {
$loginParagraf.css("display","block");
alert("DA");
},
error: function(data, textStatus, errorThrown) {
alert(textStatus);
alert(errorThrown);
alert(data.message);
}
});
Servlet :
String username = request.getParameter("username");
String pass = request.getParameter("password");
JSONObject jsonReply = new JSONObject();
System.out.println(username);
System.out.println(pass);
response.setStatus(200);
PrintWriter out = response.getWriter();
response.setContentType("application/json");
jsonReply.put("success",true);
jsonReply.put("message", "Please work this time");
System.out.println(jsonReply.toString());
out.print(jsonReply);
The system prints work just fine, and the username and password are printed out in the console.
From what I can tell I have recreated your setup using an index.jsp page which includes the form and ajax call, and a servlet with a doPost method that includes your code. The code appears to work as expected. I get a successful response with the JSON message.
My first thought was changing dataType: 'text' to 'json', but it appears to work either way.
I had to wrap a try/catch (JSONException) around your jsonReply.put statements to appease the compiler.
One thing that might be causing trouble is that your form includes a submit button which will fire the onclick event and submit the form. I changed it to type="button" so that only the onclick event would fire.

Categories