i have the following form,
<form action="localhost/xyz.aspx" method = "post" enctype="multipart/form-data">
<input type="text" name="name">
<input type="text" name="age">
<input type="text" name="submit">
</form>
My requirement is to complete the action using AJAX & jQuery and without a form tag explicitly added in html.
TIA
update1
i have tried
function onButtonClicked()
{
$.ajax({
type: 'POST',
url: "xyz.aspx",
data : {"name" : "john", "age" : "22"},
crossDomain : true,
beforeSend: function (x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("multipart/form-data");
}
},
success: function(data){
alert("Success");
},
error: function(data){
alert("on start process error");
}
});
}
sample.html
<html>
<body>
<input type="button" onclick = "onButtonClicked()">
</body>
</html>
It returns Unsupported Media Type 415.
I want send form data using ajax
You can select the individual inputs and use them in an array to post. This way doesn't need a wrapper:
// Click button with ID #submit
$("button#submit").click(function () {
// Send to submit.php
$.post("submit.php", {
// Send these values via POST
val1: $("#val1").val(), // Get value from input #val1
val2: $("#val2").val() // Get value from input #val2
}, function(result){
// Output result to #output element
$('#output').html(result);
});
});
Related
i want to get data form database using ajax, but it doesn't work. what should i change?
function getdata()
{
alert();
$.ajax
({
type:'post',
url:'view.php',
data:{
num: "num",
name : "name",
univ : "univ",
ex: "ex",
line : "line"
},
success: function(response)
{
alert(response);
// if (response!=""){
// $("#table").html(response);
// }
}
});
}
and this is the button
<input type="submit" name="submit" onclick="getdata()" value="Submit"/>
the error called "ajax is not a function". thank you
What happens when you make the same request with a tool such as postman?
We're going to need a little more context to form be helpful.
A little demo to show that it basically works once you include jQuery:
function getdata()
{
$.ajax
({
type:'post',
url:'https://jsonplaceholder.typicode.com/posts',
data:{
num: "num",
name : "name",
univ : "univ",
ex: "ex",
line : "line"
},
success: function(response)
{
alert(JSON.stringify(response));
if (response!=""){
$("#out").html(JSON.stringify(response));
}
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="submit" name="submit" onclick="getdata()" value="Submit"/>
<pre id="out"></pre>
I have a very simple script in php that is supose to send a request to ajax and return the string im putting in the .php file but when the request respond, it sends an object instead of the string. I dont know why this is hapening because i already have done this the same way previusly and works fine.
this is the form that send the request
<form method="POST" id="personForm">
<div class="form-group col-md-6">
<label for="NameInput">Name</label>
<input type="text" name="name" class="form-control" id="NameInput">
</div>
<div class="form-group col-md-6">
<label for="lNameInput">Last Name</label>
<input type="text" name="lastname" class="form-control" id="lNameInput">
</div>
<input type="button" name="Send" class="btn btn-info" onclick="ajaxRequest($('#NameInput').val(), $('#lNameInput').val())" value="Send">
</form>
<hr>
<div id="result">
</div>
This is the script that send the ajax request
function ajaxRequest(name, lastn) {
var params = {
"name" : name,
"lastn" : lastn
};
$.ajax({
url: './process/resquestAjax.php',
method: 'POST',
data: params,
beforeSend: function() {
$('#result').html('<p>Procesando Peticion...</p>');
},
complete: function(completeResult) {
$('#result').html(completeResult);
},
sucess: function(successResult) {
},
error: function(jqXHR,estado,error){
alert('There was an error!: '+estado+' name-> '+error+' otro-> '+jqXHR);
alert("Please contact support ias soon as posible...!");
}
}); // End Ajax Call
}
and the php file is just this
$nombre = $_POST['name'];
$apellido = $_POST['lastname'];
echo "¡Hello! your name is : ". $nombre ." and your last name: ". $apellido;
I dont know why im not getting the string of that echo in the response of the ajax. it sends an object instead. I'm trying to make other project with database with this but i have the same issue.
See the documentation. You're using the complete callback, which receives the jqXHR object as its first argument.
Instead, you want to use the success (two cs, note), not complete, if you want to use the returned data. success receives the data as its first argument. (You can also use complete to remove the in-progress message, etc.)
So for instance:
function ajaxRequest(name, lastn) {
var params = {
"name" : name,
"lastn" : lastn
};
$.ajax({
url: './process/resquestAjax.php',
method: 'POST',
data: params,
beforeSend: function() {
$('#result').html('<p>Procesando Peticion...</p>');
},
complete: function(completeResult) {
// If you wanted to do something whether the request
// succeeded or failed, you'd do it here. Otherwise,
// remove this handler.
},
success: function(successResult) {
$('#result').html(successResult);
},
error: function(jqXHR,estado,error){
alert('There was an error!: '+estado+' name-> '+error+' otro-> '+jqXHR);
alert("Please contact support ias soon as posible...!");
}
}); // End Ajax Call
}
So I have an ajax form handler that deletes a payment method. When the user clicks "delete" it shows a confirmation popup. However, even if the user clicks "cancel" it still runs the form and deletes the payment method. What do I need to change?
HTML:
<form class="sg-inline-form" method="post" action="">
<input type="hidden" name="sg_customer_id" value="customerID">
<input type="hidden" name="sg_card_id" value="cardID">
Delete
</form>
AJAX:
$('.delete-card').click(function() {
$('.ajax-loading').show();
const $form = $(this).parent();
const customer = $form.find('input[name=sg_customer_id]').val();
const card = $form.find('input[name=sg_card_id]').val();
$.ajax({
url: sg_obj.ajaxurl,
data: {
'action': 'sg_delete_payment_source',
'customer' : customer,
'card' : card
},
success:function(data) {
// This outputs the result of the ajax request
$('.ajax-loading').hide();
$('#ajax-messages').addClass('alert alert-success').html('The payment source has been deleted. Refresh Page');
},
error: function(errorThrown){
$('.ajax-loading').hide();
$('#ajax-messages').addClass('alert alert-danger').html('An error occurred.');
}
});
});
Do not make the two separate onClick bindings. You can do your functionality by changing you code like this
HTML:
<form class="sg-inline-form" method="post" action="">
<input type="hidden" name="sg_customer_id" value="customerID">
<input type="hidden" name="sg_card_id" value="cardID">
Delete
</form>
AJAX:
$('.delete-card').click(function() {
if(confirm('Are you sure?')) {
$('.ajax-loading').show();
const $form = $(this).parent();
const customer = $form.find('input[name=sg_customer_id]').val();
const card = $form.find('input[name=sg_card_id]').val();
$.ajax({
url: sg_obj.ajaxurl,
data: {
'action': 'sg_delete_payment_source',
'customer' : customer,
'card' : card
},
success:function(data) {
// This outputs the result of the ajax request
$('.ajax-loading').hide();
$('#ajax-messages').addClass('alert alert-success').html('The payment source has been deleted. Refresh Page');
},
error: function(errorThrown){
$('.ajax-loading').hide();
$('#ajax-messages').addClass('alert alert-danger').html('An error occurred.');
}
});
}
});
It's because you're using listening to the onclick and the .click events. You can put the confirm in an if to stop on the user clicking "Cancel".
$(function(){
$("#continues").click(
function(){
alert("FIRES EITHER WAY");
});
$("#stops").click(function(){
if(confirm("TEST")){
alert("CONTINUED");
} else {
alert("STOPED");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a id="continues" href="#" onclick="return confirm('Continues')">Continues</a>
<a id="stops" href="#">Stops</a>
You don't have a condition to test what the confirm() actually says. this link shows how to get the actual confirm() response and you should test if the response was true or false before submitting the $.ajax request
<html>
<body>
<form method="POST">
<label>username</lable>
<input id="username" name="username" type="text">
<label>emailid</lable>
<input id="emailid" name="emailid" type="text">
<button id="enter" type="submit">submit</button>
</form>
<script type="text/javascript">
$(document).ready(function () {
var userName = $("#username").val();
var emailId = $("#emailid").val();
$($enter).click(function () {
$.ajax({
type: 'POST',
url: ".....rest service url....",
dataType: JSON,
data: {
"UserName": userName,
"EmailId": emailId
},
success: function (data) {
alert("success");
}
error: function (e) {
alert("error" + e)
}
});
});
});
</script>
</body>
</html>
I'm trying to post the form field in rest service which expects a JSON response.
I'm getting an alert error message (object Object)
I'm not getting where the error is.
You can try $.post instead of $.ajax
$.post( "your url",{ UserName: userName, EmailId: emailId }, function( data ){
alert("Success");
});
Just make sure that parameters you are passing matches with your REST service.
$($enter).click(function () {
this part of code looks invalid, provide a correct selector to the click function.
First change this
$($enter).click(function to
$("#enter").click(function () {
Are you sure the the service you written for this task is a post service...some times i do the mistake like post data and write service for getting data.If you can show your service structure it will help to have a better insight.
Here is my HTML. Just a simple form:
<form>
Username:
<input type="text" id="username"/>
<br/>
Password:
<input type="password" id="password"/>
<br/>
<input type="submit" id="submit" value="submit"/>
</form>
Here is my JS associated with it:
function init(){
$("#submit").click(function() {
var url = "http:example.com/mail";
alert("what?");
$.ajax(url, {
type : 'post',
data : {
'username' : $("#username").val(),
'password' : $("#password").val()
},
success : function() {
alert("done");
}
});
});
}
After I clicked on the submit button, the $.ajax function is supposed to do a post to the URL where I keeps my server running.
However, from my server side log or firebug network monitoring, I didn't see any sign of the POST method. (The first alert was triggered but the second wasn't.)
They are two different applications that I developed, so after I did some research, here is one explanation:
Since $.ajax() uses XMLHttpRequest, it is subject to XHR's cross-domain restriction. Are your SiteA and SiteB on different hosts/ports? If so, you're seeing the expected behavior.
Is that so? If so, is there any workaround?
You need return false; at the end of the click handler to prevent the default submission of the form. Although once you prevent the form from submitting, you will still have the cross-domain restriction, which is not trivial to solve. Look into jsonp for a possible solution.
Change your event handler to this...
function init(){
$("#submit").click(function(event) {
event.preventDefault();
var url = "http:example.com/mail";
alert("what?");
$.ajax(url, {
type : 'post',
data : {
'username' : $("#username").val(),
'password' : $("#password").val()
},
success : function() {
alert("done");
}
});
});
}
This will stop the form from actually doing a full POST to the server.
I think this will work
function init(){
$("#submit").click(function(event) {
event.preventDefault();
var url = "http:example.com/mail";
alert("what?");
$.ajax(url, {
type : 'post',
data : {
'username' : $("#username").val(),
'password' : $("#password").val()
},
cache: 'false',
async: 'false',
success : function() {
alert("done");
}
});
});
}