Firstly, based on other suggestions, I've tried moving around the preventDefault() but haven't had success.
My feedback form uses this JavaScript to pass form fields to "process.php" and return with the relevant messages (ie: "sucesss" or "fail")
It's doing its job except that instead of staying on the same page 'feedback.php' it loads 'process.php' page with this ... {"Data":"Data Value"}
Heres the code:
$(document).ready(
function(){
$('form').submit(
function(event){
var formData =
{
'name' : $('input[name=name]').val(),
'page' : $('input[name=page]').val()
};
$('.form-group').removeClass('has-error'); // remove the error class
$('.error').remove(); // remove the error text
event.preventDefault();
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
.done(function(data){
if ( ! data.success)
{
if (data.errors.name)
{
$('#name-group').addClass('has-error'); // add the error class to show red input
$('#nameField').append(data.errors.name); // add the actual error name under our input
}
}
else
{
$('form').append('<div class="buttonError">Message Sent!</div>');
form.myButton.disabled = true;
}
}
);
.fail(function(data){
$('form').append('<div class="buttonError">Failed!</div>');
}
console.log(data);
);
event.preventDefault();
}
);
});
looks like syntax error calling $.ajax, it should be corrected like this:
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
}).done(function(data){
if ( ! data.success)
{
if (data.errors.name)
{
$('#name-group').addClass('has-error'); // add the error class to show red input
$('#nameField').append(data.errors.name); // add the actual error name under our input
}
}
else
{
$('form').append('<div class="buttonError">Message Sent!</div>');
form.myButton.disabled = true;
}
}).fail(function(data){
$('form').append('<div class="buttonError">Failed!</div>');
console.log(data);
});
Remove the method and action in the form tag in your HTML file. This looks fine. Let me know if it doesn't work.
Related
I'm trying to POST some data to another page with AJAX but no info is going, i'm trying to pass the values of two SELECT (Dropdown menus).
My AJAX code is the following:
$('#CreateHTMLReport').click(function()
{
var DeLista = document.getElementById('ClienteDeLista').value;
var AteLista = document.getElementById('ClienteParaLista').value;
$.ajax(
{
url: "main.php",
type: "POST",
data:{ DeLista : DeLista , AteLista : AteLista },
success: function(data)
{
window.location = 'phppage.php';
}
});
});
Once I click the button with ID CreateHTMLReport it runs the code above, but it's not sending the variables to my phppage.php
I'm getting the variables like this:
$t1 = $_POST['DeLista'];
$t2 = $_POST['ParaLista'];
echo $t1;
echo $t2;
And got this error: Notice: Undefined index: DeLista in...
Can someone help me passing the values, I really need to be made like this because I have two buttons, they are not inside one form, and when I click one of them it should redirect to one page and the other one to another page, that's why I can't use the same form to both, I think. I would be great if someone can help me with this, on how to POST those two values DeLista and ParaLista.
EDIT
This is my main.php
$('#CreateHTMLReport').on('click',function() {
$.ajax({
// MAKE SURE YOU HAVE THIS PAGE CREATED!!
url: "main.php",
type: "POST",
data:{
// You may as well use jQuery method for fetching values
DeLista : $('#ClienteDeLista').val(),
AteLista : $('#ClienteParaLista').val()
},
success: function(data) {
// Use this to redirect on success, this won't get your post
// because you are sending the post to "main.php"
window.location = 'phppage.php';
// This should write whatever you have sent to "main.php"
//alert(data);
}
});
});
And my phppage.php
if(!empty($_POST['DeLista'])) {
$t1 = $_POST['DeLista'];
# You should be retrieving "AteLista" not "ParaLista"
$t2 = $_POST['AteLista'];
echo $t1.$t2;
# Stop so you don't write the default text.
exit;
}
echo "Nothing sent!";
And I'm still getting "Nothing Sent".
I think you have a destination confusion and you are not retrieving what you are sending in terms of keys. You have two different destinations in your script. You have main.php which is where the Ajax is sending the post/data to, then you have phppage.php where your success is redirecting to but this is where you are seemingly trying to get the post values from.
/main.php
// I would use the .on() instead of .click()
$('#CreateHTMLReport').on('click',function() {
$.ajax({
// MAKE SURE YOU HAVE THIS PAGE CREATED!!
url: "phppage.php",
type: "POST",
data:{
// You may as well use jQuery method for fetching values
DeLista : $('#ClienteDeLista').val(),
AteLista : $('#ClienteParaLista').val()
},
success: function(data) {
// This should write whatever you have sent to "main.php"
alert(data);
}
});
});
/phppage.php
<?php
# It is prudent to at least check here
if(!empty($_POST['DeLista'])) {
$t1 = $_POST['DeLista'];
# You should be retrieving "AteLista" not "ParaLista"
$t2 = $_POST['AteLista'];
echo $t1.$t2;
# Stop so you don't write the default text.
exit;
}
# Write a default message for testing
echo "Nothing sent!";
You have to urlencode the data and send it as application/x-www-form-urlencoded.
So in my program, i have two tabs i am performing a post ajax request using form.
On load of ajax two different kinds of json will appear
the code is as below:
$('#myForm').submit(function () {
$.ajax({ // create an AJAX call...
data : $(this).serialize(), // get formdata
dataType : "json",
//async : false,
//timeout : 55000,
type : $(this).attr('method'), // GET or
// POST
url : url.A, // the file to call
success : function ( json ) {
// on success..
$('.ajaxloader').css("visibility", "hidden");
Graph = json;
draw(Graph);
}
});
$.ajax({ // create an AJAX call...
data : $(this).serialize(), // get formdata
dataType : "json",
type : $(this).attr('method'), //POST
url : url.B, // the file to call
success : function ( json ) {
// on success..
table= json;
plot(table);
}
});
}
Now on josn s arrival i am first showing the table, to view my other tab, i am writing a onclick event this way..
$(init);
function init () {
$('body').on('click', 'a.all',function(){
plot(table);
})
.on('click', 'a.domain',function(){
draw(Graph);
});
}
Now my problem is if i click on domain, the json would have still not loaded hence throwing a error,
How do i resolve this..
So far i tried async:false (it works fine but it shows a deprecated warning)
AjaxStop, works well the first time then when switching tabs it just shows no response
I also tried when but since i am new to java script I didn't understand the usage at all
You could try to use an Ajax global event like ajaxComplete().
var ajaxCounter = 0;
$(document).ajaxComplete(function(){
ajaxCounter++;
if(ajaxCounter == 2){
$(init);
}
});
I want to post javascript variable to another php file and I search using Ajax may help.I want to get back the data on another php file by "post" method.But I can't use $.ajax({}) directly inside javascript:
function input() {
$.ajax({
url : 'update_service.php',
type : 'POST',
data : {
name: name,
},
success : function(response) {
alert(response);
}
});
The error message said "unexpected function ajax()". How to fix it?
JQuery Version
$.post( "update_service.php", function( data ) {
alert( "Data Loaded: " + data );
});
I've written one AJAX function code as follows :
$('#form').submit(function(e) {
var form = $(this);
var formdata = false;
if(window.FormData) {
formdata = new FormData(form[0]);
}
var formAction = form.attr('action');
$.ajax({
type : 'POST',
url : 'manufacturers.php',
cache : false,
data : formdata ? formdata : form.serialize(),
contentType : false,
processData : false,
success: function(response) {
if(response != 'error') {
//$('#messages').addClass('alert alert-success').text(response);
// OP requested to close the modal
$('#myModal').modal('hide');
} else {
$('#messages').addClass('alert alert-danger').text(response);
}
}
});
e.preventDefault();
});
Now here in data attribute I want to send some additional parameters with values in data attribute. How should I send these parameters to PHP file?
For clear understanding of my issue refer the following AJAX function code that I've written previously :
function GetPaymentRequest(status){
var status = $('#status_filter').val();
$.ajax({
type: "POST",
url: "view_payment_request.php",
data: {'op':'payment_request_by_status','request_status':status},
success: function(data) {
// alert(data);
}
});
}
In above function code you can see that I've passed few parameters with values viz. 'op':'payment_request_by_status','request_status':status in data attribute.
Exactly same parameters I want to pass in first AJAX function code. The already mentioned parameter "formdata ? formdata : form.serialize()" should also be there.
How should I do this? Can someone please help me in this regard?
Thanks in advance.
Add by using $.param
form.serialize() + '&' + $.param({'op':'payment_request_by_status','request_status':status});
or use serializeArray() and push new items
var data = form.serializeArray();
data.push({name:'op',value:'payment_request_by_status'}).push({name:'request_status',value:status});
then pass data
What you can do is, add two hidden fields to your already existing form, name one of them as op and set the value as payment_request_by_status and another one as request_status and the value based on the status.
When the form is serialized, it will automatically send these values also.
I have a jquery ajax post and when a user wirte and press enter in a messagebox this ajax triggers. but I want to make a specific post, so when a user write specific message then the ajax triggers. I used something like:
if(input == "Hello")
AjaxPost(input);
but it works for the first time and when I write something else than "hello" and then I write "hello" it does not trigger my ajax. but I do not think this way works, how can I write a specific ajax message?
AjaxPost : function(data) {
$.ajax({
type : "POST",
url : "/api/user",
datatype : "application/json",
contentType: " text/plain",
data : dataAttribute,
success : function(data) {
},
error : function(error) {
},
If it's a input or a textarea, then bind the change or the blur event to the element.
$('messagboxIdentifier').change(function() {
if(this.value === 'Hello') {
// call the method here
}
});
$('#messagboxIdentifier').change(function() {
if(this.value === 'Hello') {
// call the method here
}
});
A # symbol is to be used with the id to bind it properly, was it done ?