On the click of a button, I want to capture a form's data and send it to a php page using ajax, json. Now, the alert "hello hello" comes on the click of a button ONLY WHEN I HAVE COMMENTED OUT MY AJAX PORTION.
When i include the ajax portion by un-commenting it, not only do i not get any errors but also my "hello hello" alert doesnt show up.
I find this odd. Why does it happen so?
Here is my ajax:
<script>
$(document).ready(function () {
$("#btn").click( function() {
alert('hello hello');
/* Coomenting starts here
$.ajax({
url: "connection.php",
type: "POST",
data: {
id: $('#id').val(),
name: $('#name').val(),
Address: $('#Address').val()
}
datatype: "json",
success: function (status)
{
if (status.success == false)
{
alert("Failure!");
}
else
{
alert("Success!");
}
}
});
*/
//commenting ends here.
//basically i just commented out the ajax portion
});
});
</script>
You are missing a comma after "data":
$.ajax({
url: "connection.php",
type: "POST",
data: {
id: $('#id').val(),
name: $('#name').val(),
Address: $('#Address').val()
}, // Missing comma!
datatype: "json",
success: function (status)
{
if (status.success == false)
{
alert("Failure!");
}
else
{
alert("Success!");
}
}
});
As #dystroy pointed out, since your code can't compile, this malformed block will potentially prevent other code (such as a simple alert) from firing.
Check comma syntax after data parameter:
data: {
id: $('#id').val(),
name: $('#name').val(),
Address: $('#Address').val()
},
You are missing a comma after the data part:
<script>
$(document).ready(function () {
$("#btn").click( function() {
alert('hello hello');
/* Coomenting starts here
$.ajax({
url: "connection.php",
type: "POST",
data: {
id: $('#id').val(),
name: $('#name').val(),
Address: $('#Address').val()
},
datatype: "json",
success: function (status)
{
if (status.success == false)
{
alert("Failure!");
}
else
{
alert("Success!");
}
}
});
*/
//commenting ends here.
//basically i just commented out the ajax portion
});
});
</script>
Related
When I run submit, an alert message occurs as many times as you send it before you reload.
For example.
first run submit occur success message
not refresh second run submit two repeat occurs success message
not refresh third run submit three repeat occurs success message
...
not refresh n run submit n repeat occurs success message
Why does it run like this?
How can I solve this problem?
My code is as follows.
$(document).ready(function() {
$('#my_modal').on('show.bs.modal', function(e) {
var p_index = $(e.relatedTarget).data('p_index');
$(e.currentTarget).find('input[name="p_index"]').val(p_index);
$("button#submit").click(function() {
$.ajax({
type: "POST",
async: false,
url: "../receipt/send.php",
data: $('form.send_p_index').serialize(),
success: function(data) {
alert("success")
$("#send_p_index")[0].reset()
$("#my_modal").modal('hide');
},
error: function() {
alert("Error");
}
});
});
});
}
WRONG
$(document).ready(function() {
$('#my_modal').on('show.bs.modal', function(e) {
var p_index = $(e.relatedTarget).data('p_index');
$(e.currentTarget).find('input[name="p_index"]').val(p_index);
$("button#submit").click(function() {
$.ajax({
type: "POST",
async: false,
url: "../receipt/send.php",
data: $('form.send_p_index').serialize(),
success: function(data) {
alert("success")
$("#send_p_index")[0].reset()
$("#my_modal").modal('hide');
},
error: function() {
alert("Error");
}
});
});
});
}
CORRECT: Put this outside of modal.shown because every time the modal shown, it will write a submit function that repeats as many as it shown.
$(document).on('click', 'button#submit', function() {
$.ajax({
type: "POST",
async: false,
url: "../receipt/send.php",
data: $('form.send_p_index').serialize(),
success: function(data) {
alert("success")
$("#send_p_index")[0].reset()
$("#my_modal").modal('hide');
},
error: function() {
alert("Error");
}
});
});
My code works well in Chrome and Edge, but I'm getting this error in Firefox:
TypeError: 'key' called on an object that does not implement interface Storage
function goToNextStep() {
$.post("../manager.php", {
dados: sessionStorage,
action: "save"
}, function(response) {
if (response === "1") {
$.ajax({
type: "GET",
url: "../final.php",
success: function(data) {
$('#content').html(data);
}
});
}
});
}
You're attempting to pass the entire sessionStorage object in an AJAX request. Don't do that. Instead pull out the specific keys that you require. Something like this:
function goToNextStep() {
$.post("../manager.php", {
dados: {
foo: sessionStorage.getItem('foo'),
bar: sessionStorage.getItem('bar')
},
action: "save"
}, function(response) {
if (response === "1") {
$.ajax({
type: "GET",
url: "../final.php",
success: function(data) {
$('#content').html(data);
}
});
}
});
}
I'd also suggest that you return JSON instead of plain text, as the latter can lead to issues with whitespace causing unexpected results. It's also better typed, so you can return a boolean state flag, eg:
if (response.success) {
// your logic here...
}
I was able to solve this with the following workaround:
function goToNextStep() {
$.post("../manager.php", {
dados: JSON.parse(JSON.stringify(localStorage)), // <----- change
action: "save"
}, function(response) {
if (response === "1") {
$.ajax({
type: "GET",
url: "../final.php",
success: function(data) {
$('#content').html(data);
}
});
}
});
}
$.ajax({
type: 'POST',
url: '/Base/SetCookie',
data: {
key: 'area',
value: addrId
},
success: function (data) {
console.log(window.location); //window.location is 'localhost:12345/Cart'
window.location.reload(true);
}
})
It took me back to localhost:12345 instead of my current page which is localhost:12345/Cart
Any idea what's wrong?
UPDATE :
Complete Code
$('.cartindexaddress').on('ifClicked', function (event) {
var addrId = $(this).val();
$.ajax({
url: '/Membership/GetUserAreaById/',
data: {
id: addrId
},
success: function (data) {
$.ajax({
type: 'POST',
url: '/Base/SetCookie',
data: {
key: 'area',
value: addrId
},
success: function (data) {
window.location.reload(true);
}
})
}
})
})
tried :
window.location.reload(true);
location.reload();
window.location.href = window.location.href;
window.location.href = '/Cart';
window.location.href = window.location;
Everything is not working, still took me back to first page.
please use $.post instead of $.ajax in my code everything is ok by using $.post
I want to run a function inside beforesend() in jquery ajax. Depending on the return value of that function I want to change the URL of ajax request. For an example refer below.
If myFunction() returns a value grater than 1, I want to run url1 otherwise I want to run url2. How to achieve that?
myFunction() gives a value grater than 1. But always ajax runs the url2.
$.ajax({
type: "POST",
data: {
fname: $('#com').val()
},
dataType: "json",
beforeSend: function () {
myFunction($('#com').val())
},
url: (myFunction($('#com').val()) > 1) ? url1 : url2,
success: function (data) {
if (data == 'success') {
window.location.href = 'index.php?r=site/index';
} else {
alert("Already registered email");
}
},
failure: function (errMsg) {
alert(errMsg);
}
});
try this
$.ajaxSetup({
beforeSend: function(jqXHR, settings) {
settings.url ="new Url";
}
});
Create a global variable something like:
var urlToSend;
and then assign it in beforeSend
$.ajax({
type: "POST",
data: {
fname: $('#com').val()
},
dataType: "json",
beforeSend: function () {
urlToSend=myFunction($('#com').val()) > 1 ? url1 : url2;
},
url: urlToSend,
success: function (data) {
if (data == 'success') {
window.location.href = 'index.php?r=site/index';
} else {
alert("Already registered email");
}
},
failure: function (errMsg) {
alert(errMsg);
}
});
$.ajax({
type: "POST",
data: {
fname: $('#com').val()
},
dataType: "json",
beforeSend: function () {
url = myFunction(parseInt($('#com').val())) > 1 ? url1 : url2;
},
url: url,
success: function (data) {
if (data == 'success') {
window.location.href = 'index.php?r=site/index';
} else {
alert("Already registered email");
}
},
failure: function (errMsg) {
alert(errMsg);
}
});
I'm trying to figure out once the callback to the remote function is made for either the username or email address, that if the data returned is equal to "n" it should trigger the message to be displayed.
JS:
$(document).ready(function() {
var validator = $("form").validate({
rules: {
username: {
minlength: 6,
maxlength: 12,
remote: {
type: 'post',
url: 'register/is_username_available',
data: {
'username': function() {
return $('#username').val();
}
},
dataType: 'json',
success: function(data) {
alert(data);
if (data == 'y') {
alert('available');
}
else {
alert('no available');
}
}
}
},
email_address: {
email: true,
remote: {
type: 'post',
url: 'register/is_email_available',
data: {
'email_address': function() {
return $("#email_address").val();
}
},
dataType: 'json',
success: function(data) {
alert(data);
if (data == 'y') {
alert('available');
}
else {
alert('no available');
}
}
}
}
},
messages: {
username: {
remote: 'The username is already in use'
},
email_address: {
remote: 'There is already an account set up that uses that email address!'
}
}
});
});
Your "dataType" is incorrect.. right now your telling it to get and use JSON, you on the other hand are outputting or expecting a string or "text"/"html" rather than "json"
change your dataType to html or text, and see how that does ya.
if you wanted to keep it at json.. your output from the php side would have to be
{"response":"y"}
and your javascript in the sucess would have to be like
if(data.response == "y")