I want use jquery to sent form data to server,
and I follow this page↓
how do i submit a form using get method in jquery.
But is not working, has no any window alert.
I don't know why....
I already import the jquery script in head(version 1.11.3).
<script src="./static/jquery-1.11.3.js" type="text/javascript"></script>
this is my script.
<script>
function test(){
document.getElementById("form_test").submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
data : $(this).serialize(),
success : function( response ) {
alert( response );
},
error:function(){
alert("error");
}
});
return false;
});
}
</script>
this is my form code.
<form id="form_test" class="appnitro" method="post" action="">
<div class="form_description">
<p>test.</p>
</div>
<ul >
<li id="li_1" >
<label class="description" for="info">info</label>
<div>
<input id="info" name="info" class="setInfo" type="text" maxlength="16" value=""/>
<label id="infoMsg" class="Message"></label><br/>
</div>
</li>
<li class="buttons">
<button type="button" class="mbutton" onclick="test()">submit</button>
</li>
</ul>
</form>
Remove the submit handler from test()
document.getElementById("form_test").submit(function () {
This is not required as the function test is being called when user clicks on the button.
function test() {
var $form = $('#form_test');
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: $form.serialize(),
success: function (response) {
alert(response);
},
error: function () {
alert("error");
}
});
return false;
}
I would also suggest you to use jQuery on() to bind event
$('#form_test').on('submit', function () {
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function (response) {
alert(response);
},
error: function () {
alert("error");
}
});
return false;
});
You need to have a form submit event handler registered in the dom ready handler
$(function () {
$("#form_test").submit(function () {
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function (response) {
alert(response);
},
error: function () {
alert("error");
}
});
return false;
});
})
In your code, you are calling the test method on click of the button, which calls the form elements submit function with a callback
As you used inline js in submit button, no need for submit event handle for this. See code below :
<script>
function test(){
var myForm = document.getElementById("form_test");
$.ajax({
url : $(myForm).attr('action'),
type : $(myForm).attr('method'),
data : $(myForm).serialize(),
success : function( response ) {
alert( response );
},
error:function(){
alert("error");
}
});
return false;
}
Related
Firstly, I've been stuck between method and type as if I've defined method in form so I don't have to define it in ajax, and if so? ajax gives undefined in console.
Secondly, The following code gives 405 POST method not allowed.
Also, When I do succeed trying bunch of things ajax refreshes the whole page, I want to post data to server without refreshing the page.
Any help would do!!
Controller Function
public function storeDevSkill(Request $request, $user_id)
{
$this->validate($request,
[
'dev_skill_name' => 'required',
'dev_skill_exp' => 'required',
]);
try {
$data = array(
'dev_id' => $user_id,
'dev_skill_name' => $request->dev_skill_name,
'dev_skill_exp' => $request->dev_skill_exp,
);
DevSkill::create($data);
return back();
} catch (\Exception $exception) {
return back()->withError($exception->getMessage())->withInput();
}
}
Route:
Route::post('/developer/create/skill/{user_id}', 'SuperAdminControllers\DeveloperController#storeDevSkill')->name('store.developer.skill');
Form:
<form id="form_skill" method="POST" enctype="multipart/form-data" action= "{{route('store.developer.skill',$user->user_id)}}">
Button:
<button type="submit" id="addskillSubmit" value="{{$user->user_id}}" style="display: none;" class="btn btn-primary">Save</button>
Script:
<script>
$(document).ready(function () {
$('#form_skill').on('submit', function (event) {
console.log("Ajax Call")
event.preventDefault();
var action_url = '';
var user_id = $(this).attr('value');
console.log(action_url)
$.ajax({
url: action_url,
type: "post",
data: $(this).serialize(),
// dataType: 'json',
success: function (response) {
if (response.error) {
console.log('Ajax Success')
} else {
// var table = $('#addskilltable').DataTable();
// table.ajax.reload();
console.log(response.success)
}
}
});
});
});
</script>
You need to pass action attribute from the form to your ajax call like so
<script>
$(document).ready(function () {
$('#form_skill').on('submit', function (event) {
event.preventDefault();
$.ajax({
url: $(this).attr('action'),
type: "post",
data: $(this).serialize(),
dataType: 'json',
success: function (response) {
if (response.error) {
console.log('Ajax Success')
} else {
console.log(response.success)
}
}
});
});
});
</script>
Give it a try and see if that changes anything.
$(document).on('submit', '#form_skill', function(e){
e.preventDefault();
var nFormId = '#'+ $(this).attr('id');
var formData = $(this).serialize();
var url = $(this).attr('action');
$.ajax({
type: "POST",
url: url,
data: formData,
success: function (response) {
console.log(response);
$(nFormId)[0].reset();
},
error: function (jqXHR, exception) {
},
beforeSend: function () {
},
complete: function () {
}
});
});
Hope this answer help you.
I have an object that contains parameters . I want to upload an image to a server but just using javascript.
how can I do that?
<input id="imgItem" type="file" class="form-control">
<input type="text" id="title">
<input type="text" id="description">
<button onclick="handle();">
<script>
function handle(){
var params={
title:document.getElementById('title').value,
desc: document.getElementById('description').value,
img://i don't know what I must do,
};
postItem(params, function(data){
alert(JSON.stringify(data));
});
}
function postItem(param, callbackFunction){
$.ajax({
url:myUrl,
data:param,
type:'POST',
contentType:'application/x-www-form-urlencoded',
xhrFields:{withCredentials: false},
success: function(response){
callbackFunction(response);
}
});
}
</script>
You can use FormData
var data = new FormData();
data.append('title', document.getElementById('title').value);
data.append('desc', document.getElementById('description').value);
$("input[type='file']").each(function (index) {
try {
data.append($(this).attr('name'), $(this)[0].files[0], $(this).attr('name'));
} catch (ignore) {}
});
$.ajax({
method: 'POST',
url: url,
data: data,
cache: false,
contentType: false,
processData: false
}).done(function () {
//your code here
}).fail(function (xhr, status, error) {
//your code here
}).always(function () {
//your code here
});
Or use it as regular form submission and fill in title and description values in submit event.
I am trying to create a webpage that could check if a url is good or bad. The webpage is simple. There should be only a button on the webpage. Whenever the button is clicked it will check the status of the url. As a test case let's say I am checking for google.com. The problem is how do I connect the ajax function parameter with the html parameter?
Here is what I got so far.
<input type="button" id="home" onclick="validate()" value="Start"/>
<br>
<p>Google Status: %s</p>
<script>
$('#home').click(function(){
var string;
$.ajax({
type:'get',
url:"https://www.google.com/",
cache:false,
async:asynchronous,
dataType:json,
success: function(result) {
string = 'Working';
}
error: functionfunction(result){
string = 'Failed';
}
});
});
</script>
Update text after ajax response
<input type="button" id="home" onclick="validate()" value="Start"/>
<br>
<p id='status'>Google Status: %s</p><!-- >change<-->
<script>
$('#home').click(function(){
var string;
$.ajax({
type:'get',
url:"https://www.google.com/",
cache:false,
async:asynchronous,
dataType:json,
success: function(result) {
$("#status").html("Google Status: Working"); // change
}
error: functionfunction(result){
$("#status").html("Google Status: Failed");// change
}
}
);
});
</script>
You need to reference the HTML Controls with JQUery,
And you are missing some commas, look at this fiddle:
https://jsfiddle.net/0g9zbzqr/3/
$('#home').click(function(){
$.ajax({
url:$('#url').val(),
type:'get',
async:false,
success: function(result) {
$("#lblResult").html($('#url').val()+': Working');
},
error: function(result){
$("#lblResult").html($('#url').val()+': Failed');
}
});
});
There were many errors in the ajax call itself, but the main changes I have made are to update the html of the statusText paragraph inside the success and error handlers and removed the onClick event from the button since you are adding the event handler in javascript.
<input type="button" id="home" value="Start"/>
<br>
<p id="statusText">Google Status:</p>
<script>
$('#home').click(function(){
$.ajax({
type:'get',
url:"https://www.google.com/",
cache:false,
async:true,
dataType:'json',
success: function(result) {
$("#statusText").html("Google Status: Working");
},
error: function(result){
$("#statusText").html("Google Status: Failed");
}
});
});
</script>
I'm not sure what has gone wrong, but for some reason the success function in Ajax isn't calling the function. I'm asking it to call after the PHP is completed.
For the PHP I have $test = 'Hi'; echo json_encode($test);
Here is my code for the main page:
<?php
session_start();
if(!isset($_SESSION["b2_in"])){
header("Location: b2.php");
}
?>
<script>
$(document).ready(function(){
$("form input:submit").click(function() {
$.ajax({
type: "POST",
url: 'b2_send.php',
data: $('form').serialize(),
dataType: 'json',
//beforeSend: function(){ $("#send").val('Sending...');},
success: function(data) {
TestFunction();
},
statusCode: {
403: function(e) {
$("say").highlight();
$("#message").html(e.responseText);
}
}
});
return false;
});
});
function TestFunction(){
$("#message").val("");
}
</script>
<say>
<form>
<input type="text" name="message" class="Message" id="message"/>
<input type="submit" name="send" value='Say' id="send"/>
<span id="message" style="font-weight:bold;color:red;"></span>
</form>
</say>
Try this
span is a block element of DOM and hence to set data to it, you need to use $(id).html(data); and not val()
Also you should have different id for each elemnt in the dom, it always pick the first id that it gets in the dom, and in your case it is
<input type="text" name="message" class="Message" id="message"/> so it will change the value of this element
<script>
$(document).ready(function(){
$("form input:submit").click(function() {
$.ajax({
type: "POST",
url: 'b2_send.php',
data: $('form').serialize(),
dataType: 'json',
//beforeSend: function(){ $("#send").val('Sending...');},
success: function(data) {
TestFunction();
},
statusCode: {
403: function(e) {
$("say").highlight();
$("#message").html(e.responseText);
}
}
});
return false;
});
});
function TestFunction(){
$("#message").html("");
}
</script>
I've form that submit data to external URL and the same time I want to save in my database. I've tried ajax submit and try to sumbit normal POST in ajax success.
Here my code:
<form action="http://www.blabla/post" method="post" id="myfrom">
.....
....
</form>
<script>
$('#myfrom').submit(function() {
e.preventDefault();
$.ajax({
url: 'admin-ajax.php',
type: 'POST',
dataType: 'html',
data: $('#myfrom').serialize(),
success: function() {
$('#myfrom').submit();
},
error: function(e) {
console.log(e);
}
});
});
</script>
But here Ajax is not working form will submit normal post only.
change this:
$('#myfrom').submit(function() {
to this:
$('#myfrom').submit(function(e) {
You have not passed the event in the argument so form gets submitted.
This is another way as i see:
$('yourButton').on('click', function(e){
e.preventDefault(); // stops the buttons behavior
$.ajax({
url: 'admin-ajax.php',
type: 'POST',
dataType: 'html',
data: $('#myfrom').serialize(),
success: function() {
$('#myfrom').submit(); // submits the form if success
},
error: function(e) {
console.log(e);
}
});
});
<script>
$('#postData').click(function(e) {
e.preventDefault();
$.ajax({
url: 'admin-ajax.php',
type: 'POST',
dataType: 'html',
data: $('#myfrom').serialize(),
success: function() {
$('#myfrom').submit();
},
error: function(e) {
console.log(e);
}
});
});
</script>
<form action="http://www.blabla/post" method="post" id="myfrom">
<input type="button" value="post" id="postData">
</form>
you try this one. make a button in place of submit button.
return false after ajax call to stop the normal form submit like this:
$('#myfrom').submit(function() {
$.ajax({
url: 'admin-ajax.php',
type: 'POST',
dataType: 'html',
data: $('#myfrom').serialize(),
success: function() {
$('#myfrom').submit();
},
error: function(e) {
console.log(e);
}
});
return false;
});