i am building a webapp to keep track of some customers details and other various information
what im chasing is a simple ajax function that i can reuse multiple times in the same page the send data to another page from various forms like a new customer form and say new lead form or do i need to create different ajax functions for each
i have this demo code from my login page however its for a specific form i would like for it to be able to just be given a varibale of the form name and submit all the fields in that form to another page is this possible
<script type='text/javascript'>
$('#form').on('submit',function(event){
event.preventDefault();
var wa_username = $('#wa_username').val();
var wa_password = $('#wa_password').val();
var datas='wa_username='+wa_username+'&wa_password='+wa_password;
$.ajax({
type: 'POST',
url: '/limitless/functions.php',
dataType: 'json',
data: datas,
success: function(data) {
if(data.status == '1')
{
document.location.href = '/limitless/dashboard';
}
if(data.status == '2')
{
$('#info').addClass('alert alert-danger no-border').html(data.message);
}
}
})
});
</script>
The .serialize() method on a form creates a text string in standard URL-encoded notation.
$(this).serialize() //this produces wa_username=test&wa_password=123
you could split this like below or instead of creating the datas just call the line above
$('#form').on('submit',function(event){
event.preventDefault();
postForm($(this).serialize());
});
function postForm(formData){
$.ajax({
type: 'POST',
url: '/limitless/functions.php',
dataType: 'json',
data: formData,
success: function(data) {
if(data.status == '1')
{
document.location.href = '/limitless/dashboard';
}
if(data.status == '2')
{
$('#info').addClass('alert alert-danger no-border').html(data.message);
}
}
})
}
Related
var getLoginpasssystem = function(getPassForgotSystem,getLoginCheckSystem){
$(document).ready(function() {
$('#login' || '#lostpasswordform').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'http://www.virtuelles-museum.com.udev/spielelogin/logsystem.php',
data: $(this).serialize(),
success: function(response) {
var data = JSON.parse(response);
if (data.success == "accepted") {
document.getElementById('inner').innerHTML = 'Herzlich Willkommen';
// location.href = 'index.php';
} else {
alert('Ungültige Email oder Password!');
}
}
});
});
})
}
The question is how to use two forms in one request with ajax. In this code I used ||, but it doesn't work. I mean the #login form works well but the #lostpasswordform doesn't work. When I click on the button it reloads the page instead of giving an alert.
The reason for this is the way you do your jQuery selection. Selecting multiple elements is done like this: $( "div, span, p.myClass" )
In other words it should work if you replace $('#login' || '#lostpasswordform') with $('#login, #lostpasswordform')
You can read more in detail about this in the jQuery docs
elector be used to select multiple elements. $("#login,#lostpasswordform").submit()
Use below code :
var getLoginpasssystem = function(getPassForgotSystem,getLoginCheckSystem){
$(document).ready(function() {
$("#login,#lostpasswordform").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'http://www.virtuelles-museum.com.udev/spielelogin/logsystem.php',
data: $(this).serialize(),
success: function(response) {
var data = JSON.parse(response);
if (data.success == "accepted") {
document.getElementById('inner').innerHTML = 'Herzlich Willkommen';
// location.href = 'index.php';
} else {
alert('Ungültige Email oder Password!');
}
}
});
});
})
}
Bear with me I'm my javascript is a little rusty. So I'm trying to use a call by ajax to a PHP file and give it a plan type then make sense of it check to see if it then return a true or false if some allowed slots are less than some slots used up for the plan. Here is the Form in XHTML.
<form method="post" action="/membership-change-success" id="PaymentForm">
<input type="hidden" name="planChosen" id="planChosen" value="" />
</form>
On the same file. The ( < PLAN CHOICE > ) gets parsed out to the current plan.
<script>
var hash = window.location.hash;
var currentPlan = "( < PLAN CHOICE > )";
$(".planChoice").click(function(event){
var isGood=confirm('Are you sure you want to change your plan?');
var success;
$("#planChosen").val($(this).data("plan"));
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: ({plan: $(this).data("plan")}),
success: function (data) { //This is what is not working I can't get it to return true
success = data;
}
});
if(success) {
if (isGood) {
$("#PaymentForm").submit();
}
window.location = '/membership-change-success';
} else {
alert('Please make sure you deactivate your listings to the appropriate amount before you Downgrade.')
}
});
My PHP for the ajax response looks like this.
<?php
require ('../includes/common.php');
include_once ('../includes/db-common.php');
require ('../includes/config.php');
$membership = new membership($dbobject);
$listing = new listing($dbobject);
$totalAvailableListings = ($membership->get_listingsAmount($_POST['plan']));
if($totalAvailableListings>=$listing->get_active_listings($user->id)){
echo json_encode(true); // I've tried with out jason_encode too
} else {
echo json_encode(false);
}
And that's pretty much it if you have any suggestions please let me know.
So I've tried to do it another way.
$(".planChoice").click(function (event) {
var isGood = confirm('Are you sure you want to change your plan?');
var success;
$("#planChosen").val($(this).data("plan"));
if (false) {
if (isGood) {
$("#PaymentForm").submit();
alert('you did it');
}
} else {
alert(isSuccessful($(this).data("plan")));
//alert('Please make sure you deactivate your listings to the appropriate amount before you downgrade.');
}
});
and I have an ajax function
function isSuccessful(plan) {
return $.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: {plan: plan}
});
}
The alert tells me this [object XMLHttpRequest]
any suggestions?
$.ajax() returns results asynchronously. Use .then() chained to $.ajax() call to perform task based on response
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: {plan: $(this).data("plan")}
})
.then(function(success) {
if (success) {
$("#PaymentForm").submit();
}
// if `form` is submitted why do we need to set `.location`?
// window.location = '/membership-change-success';
} else {
alert('Please make sure you deactivate your listings to the appropriate amount before you Downgrade.')
}
}, function err(jqxhr, textStatus, errorThrown) {
console.log(errorThrow)
})
You should use the following form for your ajax call
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: ({plan: $(this).data("plan")}),
success: success = data
})
.done(function(response) {
if(success) {
if (isGood) {
$("#PaymentForm").submit();
}
window.location = '/membership-change-success';
}
else {
alert('Please make sure you deactivate your listings to the
appropriate amount before you Downgrade.')
}
});
the .done() clause ensures that you perform that code after the ajax call is finished and the response is obtained.
hey guys i'm trying to make changes in my blade template using ajax , when i press the button it changes the value of data in database and i want to display this data at once on my blade template .
that's my java script code :
(function($){
$('.wishlistForm').on('submit', function(){
var form = $(this);
$.ajax({
url: form.attr('action'),
data: form.serialize(),
method: 'post',
dataType: 'json',
success: function(response){
var wishlistButton = form.find("button[type='submit']");
var x = parseInt($('.wish-btn-count').text());
if(response.actiondone == 'added') {
$('.wish-btn-count').text(x++);
console.log(x);
wishlistButton.text(response.message);
} else if(response.actiondone == 'removed') {
$('.wish-btn-count').text(x--);
console.log(x);
wishlistButton.text(response.message);
}
}
});
return false;
});
})(jQuery);
and here is the part i want to change in my template :
<div class="wish-btn-count" id="wishlist">
{{$wishlistcount}}
</div>
so how can i do it ? and for record it returns the value right in the console but don't show it in my view
Prevent the default submit event, so you can trigger the ajax
$('.wishlistForm').on('submit', function(e){
e.preventDefault();
This may be the solution.
If you are receiving json object response from the ajax call,first you have to parse that object and then use it.
Try this,
(function($){
$('.wishlistForm').on('submit', function(){
var form = $(this);
$.ajax({
url: form.attr('action'),
data: form.serialize(),
method: 'post',
dataType: 'json',
success: function(response){
/*Add this in your code*/
var response = JSON.parse(response.trim());
var wishlistButton = form.find("button[type='submit']");
var x = parseInt($('.wish-btn-count').text());
if(response.actiondone == 'added') {
$('.wish-btn-count').text(x++);
console.log(x);
wishlistButton.text(response.message);
} else if(response.actiondone == 'removed') {
$('.wish-btn-count').text(x--);
console.log(x);
wishlistButton.text(response.message);
}
}
});
return false;
});
})(jQuery);
I am having a form which gets value from the user and stores it to the database.
On submitting the form ,it calls the action.php file using ajax call.
e.preventDefault();
$.ajax({
type: "POST",
url: "action.php",
data: senData,
dataType: "JSON",
success: function(data) {
$("#name").val("");
$('.msg').fadeIn(500);
$('.msg').text("" + data.result + "");
}
});
The values are stored in the database without any errors, but I want to display a notification to the user after submitting the form inside the msg div.
In my action.php file I have added a JSON Encode statement to return a message too.
$msg = 'Thanks Yo Yo';
echo json_encode(array("result" => $msg));
But it is not working i.e, when I submit the form, it stores the data to the database and the webpage refreshes itself without displaying any message inside the .msg div.
Am I doing something wrong and is there a better way to do it??
You need to parse the JSON when it is returned to your javascript.
// Parse the response to JSON
var res = JSON.Parse(data);
$('.msg').text(res.result);
Your code should look like this.
e.preventDefault();
$.ajax({
type: "POST",
url: "action.php",
data: senData,
dataType: "JSON",
success: function(data) {
var res = JSON.Parse(data);
$("#name").val("");
$('.msg').fadeIn(500).text(res.result);
}
});
I have a problem with my html webpage, I am trying to use a code to show determinate window's login, the problem is no matter what statement(if-else, if-if, or other) I use...always display the same window (mean always display the window I coded on deslogeado.php, I can't make display the window coded on logeado.php).
Some details: msg is an string which can bring the word 'cero'(here will display a window to user can login) or other word (here will display a window where user is already logged).
<script type="text/javascript">
$(document).ready(function()
{
var flag = 'cero';
var msg = $.ajax({type: "GET", url: "getSesion.php", async: false}).responseText;
console.log(msg);
if(msg === flag)
$('#apDiv7').load('deslogeado.php');
if(msg !== flag)
$('#apDiv7').load('logeado.php');
}
);
</script>
or
<script type="text/javascript">
$(document).ready(function()
{
var flag = 'cero';
var msg = $.ajax({type: "GET", url: "getSesion.php", async: false}).responseText;
tipo=typeof msg;
console.log(msg,flag);
if(msg == flag)
{
$('#apDiv7').load('deslogeado.php');
}else{
$('#apDiv7').load('logeado.php');
}
}
);
</script>
or
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "getSesion.php",
success: function(data)
{
var flag='cero';
console.log(data,flag);
if(data === flag)
{
$('#apDiv7').load('deslogeado.php');
}else{
$('#apDiv7').load('logeado.php');
}
}
})
}
);
</script>
or
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({ url: "getSesion.php", dataType: "json" }).done(function(data)
{
if(data.message == flag)
{
$('#apDiv7').load('deslogeado.php');
}else{
$('#apDiv7').load('logeado.php');
}
});
});
</script>
Tried with 1,2 and 3 equal on if, I don't know if an html attribute problem or what. I really hope someone can help me! My regards!
When sending data via ajax in the future, consider formatting it with JSON, which will alleviate the ambiguity of free text (with possible spaces before/after).
You are using AJAX which is asynchronous. You should use the "success" callback, or the done() method of the Deferred Ajax call.
$.ajax({ url: "getSesion.php", dataType: "json" }).done(function(data) {
if(data.message == flag) {
$('#apDiv7').load('deslogeado.php');
}else{
$('#apDiv7').load('logeado.php');
}
});
Your php script should return a json formatted object like:
{ "message":"cero" }