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
}
Related
Can someone help a JS newbie?
Almost everything is working, results are returned, nothing opens new tabs, forms submit to MC database....however I cannot get the result html to post to the correct DIV. All results are being posted to the footer div.
I am guessing my selectors are not specific enough? But I do not have the knowledge on how to structure correctly.
2 forms on page using AJAX submit.
1 pop up form and 1 form in footer..... but all the result html is posting the the div in the footer.
I have adjusted the function register names as suggested (and updated the code below), but form result data is still going to the footer div
//JAVASCRIPT
// FOOTER FORM. waits for form to appear rather than appending straight to the form. Also helps if you have more than one type of form that you want to use this action on.
$(document).on('submit', '#footer-mc-embedded-subscribe-form', function(event) {
try {
//define argument as the current form especially if you have more than one
var $registerFooterFormbutton= jQuery(this);
// stop open of new tab
event.preventDefault();
// submit form via ajax
register($registerFooterFormbutton);
} catch(error){}
});
// POP UP FORM. waits for form to appear rather than appending straight to the form. Also helps if you have more than one type of form that you want to use this action on.
$(document).on('submit', '#pop-mc-embedded-subscribe-form', function(event) {
try {
//define argument as the current form especially if you have more than one
var $registerPopUpFormbutton= jQuery(this);
// stop open of new tab
event.preventDefault();
// submit form via ajax
register($registerPopUpFormbutton);
} catch(error){}
});
// POP UP FORM. post result to div
function register($registerPopUpForm) {
$('#pop-mc-embedded-subscribe-form').val('Sending...');
$.ajax({
type: 'GET',
url: 'https://websitename.us16.list-manage.com/subscribe/post-json?u=.....&c=?',
data: $registerPopUpForm.serialize(),
cache: false,
dataType: 'jsonp',
contentType: 'application/json; charset=utf-8',
error: function (err) { alert('Could not connect to the registration server. Please try again later.') },
success: function (data) {
$('#pop-mc-embedded-subscribe-form').val('pop-subscribe')
if (data.result === 'success') {
// Yeahhhh Success
console.log(data.msg)
$('#pop-mce-EMAIL').css('borderColor', '#ffffff')
$('#pop-subscribe-result').css('color', 'rgb(53, 114, 210)')
$("#pop-subscribe-result").html(data['msg']);
$('#pop-mce-EMAIL').val('')
} else {
// Something went wrong, do something to notify the user.
console.log(data.msg)
$('#pop-mce-EMAIL').css('borderColor', '#ff8282')
$('#pop-subscribe-result').css('color', '#ff8282')
$("#pop-subscribe-result").html(data['msg']);
}
}
})
};
// FOOTER FORM. post result to div
function register($registerFooterForm) {
$('#footer-mc-embedded-subscribe-form').val('Sending...');
$.ajax({
type: 'GET',
url: 'https://websitename.us16.list-manage.com/subscribe/post-json?u=.....&c=?',
data: $registerFooterForm.serialize(),
cache: false,
dataType: 'jsonp',
contentType: 'application/json; charset=utf-8',
error: function (err) { alert('Could not connect to the registration server. Please try again later.') },
success: function (data) {
$('#footer-mc-embedded-subscribe-form').val('footer.subscribe')
if (data.result === 'success') {
// Yeahhhh Success
console.log(data.msg)
$('#footer-mce-EMAIL').css('borderColor', '#ffffff')
$('#footer-subscribe-result').css('color', 'rgb(53, 114, 210)')
$("#footer-subscribe-result").html(data['msg']);
$('#footer-mce-EMAIL').val('')
} else {
// Something went wrong, do something to notify the user.
console.log(data.msg)
$('#footer-mce-EMAIL').css('borderColor', '#ff8282')
$('#footer-subscribe-result').css('color', '#ff8282')
$("#footer-subscribe-result").html(data['msg']);
}
}
})
};
<!--HTML POP UP FORM-->
<form
action="mailchimp url"
method="post"
name="pop-form"
id="pop-mc-embedded-subscribe-form"
class=""
target="_blank"
novalidate
>
<div class="form-group">
<input
type="email"
name="EMAIL"
class="form-control required"
placeholder="Enter your e-mail"
id="pop-mce-EMAIL"
/>
<input
type="submit"
value="SUBSCRIBE HERE"
name="pop-subscribe"
id="pop-mc-embedded-subscribe"
class="button"
/>
</div>
<div id="pop-subscribe-result"></div>
</form>
<!--FOOTER FORM HTML-->
<form
action="mailchimp url"
method="post"
id="footer-mc-embedded-subscribe-form"
name="footer-form"
class=""
target="_blank"
novalidate
>
<div class="mc-field-group">
<label for="mce-EMAIL"
>Email Address <span class="asterisk">*</span>
</label>
<input
type="email"
value=""
name="EMAIL"
class="form-control required email"
id="footer-mce-EMAIL"
placeholder="Email Address *"
/>
</div>
<div class="mc-field-group">
<label for="mce-FNAME">First Name </label>
<input
type="text"
value=""
name="FNAME"
class="form-control"
id="mce-FNAME"
placeholder="First Name"
/>
</div>
<div class="mc-field-group">
<label for="mce-LNAME">Last Name </label>
<input
type="text"
value=""
name="LNAME"
class="form-control"
id="mce-LNAME"
placeholder="Last Name"
/>
</div>
<!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;" aria-hidden="true">
<input
type="text"
name="b_dc51fb25cd808abedc98e3ff2_ea4d259202"
tabindex="-1"
value=""
/>
</div>
<div class="footer-btn">
<input
type="submit"
value="Subscribe"
name="footer-subscribe"
id="mc-embedded-subscribe"
class="button"
/>
</div>
<div id="footer-subscribe-result"></div>
</form>
You have two functions with the same name "register" so when you press the submit button in either forms it runs in the register function in the footer since it has the same name as the one dedicated to the popup form
Use this code and your form will work as expected:
//JAVASCRIPT
// FOOTER FORM. waits for form to appear rather than appending straight to the form. Also helps if you have more than one type of form that you want to use this action on.
$(document).on('submit', '#footer-mc-embedded-subscribe-form', function(event) {
try {
//define argument as the current form especially if you have more than one
var $registerFooterFormbutton= jQuery(this);
// stop open of new tab
event.preventDefault();
// submit form via ajax
register1($registerFooterFormbutton);
} catch(error){}
});
// POP UP FORM. waits for form to appear rather than appending straight to the form. Also helps if you have more than one type of form that you want to use this action on.
$(document).on('submit', '#pop-mc-embedded-subscribe-form', function(event) {
try {
//define argument as the current form especially if you have more than one
var $registerPopUpFormbutton= jQuery(this);
// stop open of new tab
event.preventDefault();
// submit form via ajax
register($registerPopUpFormbutton);
} catch(error){}
});
// POP UP FORM. post result to div
function register($registerPopUpForm) {
$('#pop-mc-embedded-subscribe-form').val('Sending...');
$.ajax({
type: 'GET',
url: 'https://websitename.us16.list-manage.com/subscribe/post-json?u=.....&c=?',
data: $registerPopUpForm.serialize(),
cache: false,
dataType: 'jsonp',
contentType: 'application/json; charset=utf-8',
error: function (err) { alert('Could not connect to the registration server. Please try again later.') },
success: function (data) {
$('#pop-mc-embedded-subscribe-form').val('pop-subscribe')
if (data.result === 'success') {
// Yeahhhh Success
console.log(data.msg)
$('#pop-mce-EMAIL').css('borderColor', '#ffffff')
$('#pop-subscribe-result').css('color', 'rgb(53, 114, 210)')
$("#pop-subscribe-result").html(data['msg']);
$('#pop-mce-EMAIL').val('')
} else {
// Something went wrong, do something to notify the user.
console.log(data.msg)
$('#pop-mce-EMAIL').css('borderColor', '#ff8282')
$('#pop-subscribe-result').css('color', '#ff8282')
$("#pop-subscribe-result").html(data['msg']);
}
}
})
};
// FOOTER FORM. post result to div
function register1($registerFooterForm) {
$('#footer-mc-embedded-subscribe-form').val('Sending...');
$.ajax({
type: 'GET',
url: 'https://websitename.us16.list-manage.com/subscribe/post-json?u=.....&c=?',
data: $registerFooterForm.serialize(),
cache: false,
dataType: 'jsonp',
contentType: 'application/json; charset=utf-8',
error: function (err) { alert('Could not connect to the registration server. Please try again later.') },
success: function (data) {
$('#footer-mc-embedded-subscribe-form').val('footer.subscribe')
if (data.result === 'success') {
// Yeahhhh Success
console.log(data.msg)
$('#footer-mce-EMAIL').css('borderColor', '#ffffff')
$('#footer-subscribe-result').css('color', 'rgb(53, 114, 210)')
$("#footer-subscribe-result").html(data['msg']);
$('#footer-mce-EMAIL').val('')
} else {
// Something went wrong, do something to notify the user.
console.log(data.msg)
$('#footer-mce-EMAIL').css('borderColor', '#ff8282')
$('#footer-subscribe-result').css('color', '#ff8282')
$("#footer-subscribe-result").html(data['msg']);
}
}
})
};
You are defining the register() function two times with the same name. The second one overwrites the first and everytime you call the function with that name you call the second function. An easy solution is to change the name of the functions (i.e registerPopUpForm() , registerFooterForm() ) and use them accordingly.
I'm programming a commentary box for a Web Client.
I have two tables, one for the Comments and one for the Users. I want to send Input Data from my <input> tags in HTML form to my Java Service. In this Service, I handle the received data. My Problem now is, that I get an HTTP-415 error and I don't know what to do Right now.
I am using AJAX in JavaScript to post the Data.
HTML
ID: <input type="text" name="id" value="1" readonly/> <br/>
Author: <input type="text" name="author"/> <br/>
comment: <input type="text" name="comment"/> <br/>
<button id="submit" type="Button" >Submit</button>
Javascript
function addPost(givenID){
var $author = $("#author");
var $comment= $("#comment");
var $id = $("#id")
$("#submit").on("click", function(){
var post = $author.val()+"*"+ $id.val()+"*"+ $comment.val();
$.ajax({
type: "POST",
url: "api/kommentar",
data: post,
success: function(){
console.log("SUCCESS");
},
error: function(){
console.log("FAILIURE");
}
});
});}
Java
#Path("/kommentar")
public class KommentarService {
#EJB
private KommentarManagement postMgmt;
public KommentarService() { }
#POST
#Consumes("text/plain")
public void addPostsAsJson(String income) {
System.out.println(income);
//CODE TO HANDLE...
}
jQuery's default content type for the Ajax function is 'application/x-www-form-urlencoded; charset=UTF-8'.
Because the service is expecting 'text/plain' the content type needs changed.
Add a content type:
data: post,
contentType: 'text/plain', //<--- insert
success: function(){
This question already has answers here:
jQuery Ajax POST example with PHP
(17 answers)
Closed 5 years ago.
Hi i trying make form using ajax. But i get some problems to sending form vars to php file. I get error: Undefined index: name.
I check chrome dev tools and i see variable is sending. But when made echo json_encode i see in php file i get empty array. So i dont have any idea where i made misstake.
file Main.js
var name = $('#user_name').val();
var lname = $('#user_lastname').val();
function formLogin(name, lname)
{
$.ajax({ url: 'database/register.php',
data: {
'name' : name,
'lname' : lname
},
type: 'post',
dataType:'json',
success: function(data) {
alert(data);
}
});
}
Html form:
<form class="circleForm" id="registerForm">
Imię: <input type="text" id="user_name"><br>
Nazwisko: <input type="text" id="user_lastname">
<br>
<input class="btnCircle" type="button" id="submit" value="Przejdź dalej" onclick="formLogin(name, lname)">
</form>
Php Code:
$dane = $_POST;
echo json_encode($dane);
Chrome dev:
I just want figure how can i echo this variables(name,lname) in php file register.php
Version with serialize:
function formLogin() {
var dane = $('form').serialize();
$.ajax({
url: 'database/register.php',
data: {'dane': dane},
method: 'post',
success: function(data) {
console.log(data);
}
});
}
Then result console:
<pre class='xdebug-var-dump' dir='ltr'>
<small>D:\xampp\htdocs\szkola\database\register.php:8:</small>
<b>array</b> <i>(size=1)</i>
'dane' <font color='#888a85'>=></font> <small>string</small> <font color='#cc0000'>''</font> <i>(length=0)</i>
</pre>
jquery-3.2.1.min.js:4 XHR finished loading: POST "http://localhost/szkola/database/register.php".
But when i go to http://localhost/szkola/database/register.php
i get this:
D:\xampp\htdocs\szkola\database\register.php:8:
array (size=0)
empty
You need to change the way you define your variables in your Javascript and declare them inside your function, not outside :
function formLogin(){
var name = $('#user_name').val();
var lname = $('#user_lastname').val();
$.ajax({ url: 'database/register.php',
data: {
'name' : name,
'lname' : lname
},
type: 'post',
dataType:'json',
success: function(data) {
alert(data);
}
});
}
And you need to update your HTML the same way (formLogin() instead of formLogin(...,...)) :
<form class="circleForm" id="registerForm">
Imię: <input type="text" id="user_name"><br>
Nazwisko: <input type="text" id="user_lastname">
<br>
<input class="btnCircle" type="button" id="submit" value="Przejdź dalej" onclick="formLogin()">
</form>
Try using method instead of type.
The HTML:
<form class="circleForm" id="registerForm">
Imię: <input type="text" id="user_name" name="name"><br />
Nazwisko: <input type="text" id="user_lastname" name="lname"><br />
<input class="btnCircle" type="button" id="submit" value="Przejdź dalej" onclick="formLogin();">
</form>
The JavaScript:
function formLogin() {
// Serialize the form
var data = $('form').serialize();
// Ajax call
$.ajax({
url: 'database/register.php',
data: data,
method: 'post',
dataType: 'json',
success: function(data) {
console.log(data);
}
});
}
Also remember that you're requesting a JSON so you have to echo a json_encode($array) in your PHP file for a simple string will not be returned.
My form:
<form class="form-inline signup" action="php/signupForm.php" role="form" id="signupForm">
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Email address">
</div>
<div class="form-group">
<button type="submit" class="btn btn-theme ladda-button" data-style="expand-left">
<span class="ladda-label" id="notice">Get notified!</span>
</button>
</div>
</form>
the end of my php script
$response = array(
"status" => $status,
"message" => $message
);
echo json_encode($response);
My page is receiving data like:
{"status":0,"message":"This email is already on list!"}
using JS I need to parse that data and then update text within an element.
<span id="notice">Get notified!</span>
here's my script which doesn't work, after senging form data to my php script I get a white screen that shows the json strong
$(document).ready(function() {
$.ajax({
dataType: 'json',
$('#notice').text(data.message);
});
});
You have to handle the response in a callback.
$(document).ready(function() {
$('form').on('submit', function(e) {
e.preventDefault();
$.ajax({
data: $(this).serialize(),
url: $(this).attr('action'), // Or the path of the PHP file
dataType: 'json',
}).done(function(response) {
$('#notice').text(response.message);
});
});
});
See the related docs here
That ajax call is not well formed, missing success callback and url e.g:
$(document).ready(function () {
$.ajax({
url: '/the/url/where/your/data/comes/from/',
dataType: 'json',
success: function (data) {
$('#notice').text(data.message);
}
});
});
Your code as is, is just executing at page load and not on submission of a form. You need to attach an onsubmit event, prevent the default action of doing the form submit and do your ajax call in there. Also your ajax call itself was malformed
$("#yourFormID").submit(function(e){
e.preventDefault();
$.ajax({
url:"/urlToServerScript",
data:{} //any form data the script needs you should be put here,
dataType:"json" //type of response the server will output
}).then(function(data){
$('#notice').text(data.message);
});
});
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);
});
});