I was trying to submit data to database without redirecting the page.is there any error in this code?
$('#saving').on('click', function() {
var fname = $('#fname').val();
var lname = $('#lname').val();
var company = $('#company').val();
var mnum = $('#mnum').val();
var dataString = 'fname=' +fname + '&lname=' + lname + '&company=' + company + '&mnum=' + mnum;
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
success: function() {
alert('');
$('#dialog-message').dialog('open');
}
});
});
I think you want preventDefault:
function(event) {
// ... ajax ...
event.preventDefault();
}
The documentation states:
If this method is called, the default action of the event will not be triggered.
Related
I have created a WebView for macOS app and it contains one AJAX call. The same WebView is working fine when the app calls my local URL, but when it calls the live URL, the AJAX call is not working.
$(document).ready(function () {
$('#pripolcheck').click(function () {
var pripolcheck = $('#pripolcheck').val();
var app = $('#app').val();
var user_id = $('#user_id').val();
var contact = $('#contact').val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'pripolcheck1=' + pripolcheck + '&app1=' + app + '&user_id1=' + user_id;
if (pripolcheck == '') {
alert('Please Fill All Fields');
} else {
// AJAX Code To Submit Form.
$.ajax({
type: 'POST',
url: 'http://mywebsite.com/ajaxformsubmit.php',
data: dataString,
cache: false,
success: function (result) {
// alert(result);
// $(".pripol").hide();
$('.pripolcheck').prop('checked', true);
$('input.pripolcheck').attr('disabled', true);
}
});
}
return false;
});
});
My local PHP version is 7.1.8 and my live server PHP version is 5.4.
Change your function to onclick of checkbox directly,put this code in your checkbox onclick="MyFuncion",why I'm telling this is for web view we need to give exact command in exact position it's not a browser
And your AJAX call will be like below,
function myFunction()
{
var pripolcheck = $("#pripolcheck").val();
var app = $("#app").val();
var user_id = $("#user_id").val();
var contact = $("#contact").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'pripolcheck1='+ pripolcheck + '&app1='+ app + '&user_id1='+ user_id;
if(pripolcheck=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "ajaxformsubmit.php",
data: dataString,
cache: false,
success: function(result){
// alert(result);
// $(".pripol").hide();
$('.pripolcheck').prop('checked', true);
$("input.pripolcheck").attr("disabled", true);
}
});
}
return false;
}
"My local PHP version is 7.1.8 and my live server PHP version is 5.4."
I think this explains everything.
However, try setting an absolute URL in your call:
url: 'ajaxformsubmit.php',
to
url: '/ajaxformsubmit.php',
Or whatever the actual path would be. Just a single slash will give you
http://wherever.com/ajaxformsubmit.php
if u use same site url plz use relative path not absolute path then its ok.
if use defrant site url plz comment me so give me new solution
PLZ try
$(document).ready(function () {
$('#pripolcheck').click(function () {
var pripolcheck = $('#pripolcheck').val();
var app = $('#app').val();
var user_id = $('#user_id').val();
var contact = $('#contact').val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'pripolcheck1=' + pripolcheck + '&app1=' + app + '&user_id1=' + user_id;
if (pripolcheck == '') {
alert('Please Fill All Fields');
} else {
// AJAX Code To Submit Form.
$.ajax({
type: 'POST',
url: '/ajaxformsubmit.php',
data: dataString,
cache: false,
success: function (result) {
// alert(result);
// $(".pripol").hide();
$('.pripolcheck').prop('checked', true);
$('input.pripolcheck').attr('disabled', true);
}
});
}
return false;
});
});
I am trying to send the parameter in a function but its in a loop so when i select the same function next time it first send me the previous value then send me the value that i want which causes the function to be empty and not take any value let me show you my code.
$(window).load(function(e) {
loadmore();
select_likes();
select_share();
// get_recieve_friend_requests();
// get_sent_friend_requests();
});
function loadmore() {
var lastID = $('.load-more').attr('lastID');
// alert(lastID);
jQuery.ajax({
type: 'POST',
url: '<?php echo base_url("user/get_all_post"); ?>',
data: {
id: lastID
},
dataType: 'json',
beforeSend: function(data) {
$('.load-more').show();
},
success: function(data) {
var ParsedObject = JSON.stringify(data);
var json = $.parseJSON(ParsedObject);
if (json == "") {
$("#bottom").append('<div class="btn btn-default col-md-6" >' + 'No More Results' + '</div>');
$("#Load_more_data").hide();
} else {
$postID = json[json.length - 1].id;
$('.load-more').attr('lastID', $postID);
$.each(json, function(key, data) {
var post_id = data.id;
var post_status = data.status;
var status_image = data.status_image;
var multimage = data.multimage;
if (!post_status == "" && !status_image == "") {
alert(post_id);
$("#status_data").append('<div class="media-body"><div class="input-group"><form action="" id="form_content_multimage"><textarea name="textdata" id="content_comment_multimage" cols="25" rows="1" class="form-control message" placeholder="Whats on your mind ?"></textarea><button type="submit" id="comment_button_multimage" onclick="comment_here_multimage(' + post_id + ');" >Comment</button><?php echo form_close();?></div></div></li></ul></div></div>');
}
});
}
}
});
}
function comment_here_multimage(post_id) {
$(document).on('click', '#comment_button_multimage', function(e) {
// this will prevent form and reload page on submit.
e.preventDefault();
var post_id_multimage = $('#post_id_multimage').val();
// here you will get Post ID
alert(post_id_multimage);
var Post_id = post_id;
alert(post_id);
if (post_id == post_id_multimage) {
var User_id = $('.id_data').attr('value');
var textdata = $('#content_comment_multimage').val();
alert(textdata);
alert(Post_id);
$.ajax({
type: 'POST',
url: '<?php echo base_url("user/post_comment"); ?>',
data: {
Post_id: Post_id,
User_id: User_id,
textdata: textdata
},
dataType: 'json',
success: function(data) {
console.log(data);
alert('you have like this');
jQuery('#form_content_multimage')[0].reset();
Post_id = "";
}
});
} else {
return false;
}
});
}
The post_id is being passed onclick event of the comment_here_multimage but whenver i click on it after first time same id is being passed again first then the next id passes. what can i fo to empty the post_id value once it completes.
look at these images and tell me if there is something you dont understand.
[![first time comment][1]][1]
[![second time comment][2]][2]
[![second time comment][3]][3]
[1]: https://i.stack.imgur.com/b36o4.png
[2]: https://i.stack.imgur.com/ahg3W.png
[3]: https://i.stack.imgur.com/taHAS.png
Your problem is not isolated in code. However according to my understanding.
You are binding "comment_here_multimage" function on click event of button when creating dynamic html.
Once context is loaded and user clicks that button you again binds another function on same button, which is ultimately added to the event stack.
If user clicks the button first time nothing will happen, there is no action on it. On first time it will register a handler with it.
If user click second time it will fire the handler attached on first click resulting in old postid supplied to it.
I think your problem is with passing parameter. You can set it in a custom parameter and get it later in click handler. Or you can change your handler like below.
You can change your code like this
onclick="comment_here_multimage(this,' + post_id + ');"
function comment_here_multimage(e,post_id) {
// this will prevent form and reload page on submit.
e.preventDefault();
var post_id_multimage = $('#post_id_multimage').val();
// here you will get Post ID
alert(post_id_multimage);
var Post_id = post_id;
alert(post_id);
if (post_id == post_id_multimage) {
var User_id = $('.id_data').attr('value');
var textdata = $('#content_comment_multimage').val();
alert(textdata);
alert(Post_id);
$.ajax({
type: 'POST',
url: '<?php echo base_url("user/post_comment"); ?>',
data: {
Post_id: Post_id,
User_id: User_id,
textdata: textdata
},
dataType: 'json',
success: function(data) {
console.log(data);
alert('you have like this');
jQuery('#form_content_multimage')[0].reset();
Post_id = "";
}
});
} else {
return false;
}
;
}
How to set jQuery AJAX outside .each on my script below?
$('#btnUpdate').click(function()
{
$('#result').html('');
$('.moduleIDInput').each(function()
{
var uid = $(this).attr('id');
var moduleID = $(this).val();
var chk = new Array();
$('#result').append('<h3>' +$(this).val() + '</h3>');
$('input[data-uid=' + uid + ']:checked').each(function()
{
chk.push($(this).val());
$('#result').append('<div>'+ $(this).val() + '</div>');
});
});
$.ajax(
{
url: "updateGroupAccess.php",
type: "POST",
data:
{
moduleID: moduleID,
chk: chk
},
dataType: "JSON",
success: function (jsonStr)
{
$("#btnUpdate").attr({disabled: true, value: "Update"}).addClass('btn_inact').removeClass('btn_act');;
}
});
});
If I put the AJAX function inside .each function it will submit more than 1.
But I need to put it outside, and found problem moduleID and chk not found.
Scope problem. Define uid and moduleID outside the click.
var uid="";
var moduleID="";
$('#btnUpdate').click(function()
{
$('#result').html('');
$('.moduleIDInput').each(function()
{
uid = $(this).attr('id'); // Assign value for uid
moduleID = $(this).val();
Define the variables in the global scope:
make a function called sendAjax and call it on button click.
In the mean time all your data will be stored in the data global variable (object).
var data={};
$('#btnUpdate').click(function()
{
$('#result').html('');
$('.moduleIDInput').each(function()
{
var uid = $(this).attr('id');
data.moduleID = $(this).val();
$('#result').append('<h3>' +$(this).val() + '</h3>');
$('input[data-uid=' + uid + ']:checked').each(function()
{
data.chk.push($(this).val());
$('#result').append('<div>'+ $(this).val() + '</div>');
});
});
sendAjax();
});
function sendAjax()
{
$.ajax(
{
url: "updateGroupAccess.php",
type: "POST",
data:
{
moduleID: data.moduleID,
chk: data.chk
},
dataType: "JSON",
success: function (jsonStr)
{
$("#btnUpdate").attr({disabled: true, value: "Update"}).addClass('btn_inact').removeClass('btn_act');;
}
});
}
I am trying to get a form to submit an action to an ip address without open the ip address.
So, when I hit the submit button I want it to send the post command to the ip (in this case 192.168.0.1) and just refresh the current page.
<div data-role="main" class="ui-content">
<form method="POST" action="http://192.168.0.1/">
<input type="submit" name="parser" value="thisguy"/>
</form>
</div>
My script that runs on submit:
<script src="http://ajax.googleapis.com/ajax/liubs/jquery/1.9.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data - {};
that.find('[name]').each(function() {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
$.ajax({
url: url,
type: method:,
data: data,
success: function(response) {}
});
});
return false;
});
</script>
Right now it submits the post and tries to open 192.168.0.1 as a webpage. Can someone help me out either by providing code with an explanation or pointing me to the command?
Any help is appreciated.
You need to prevent the default action (using e.preventDefault())
$('form.ajax').on('submit', function(e) {
e.preventDefault(); // Prevent default submit action (that is, redirecting)
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function() {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
$.ajax({
url: url,
type: method:,
data: data,
success: function(response) {}
});
});
return false;
});
Well, you can refresh the page after the POST is done in success method
success: function(response) {
window.location.reload();
}
Also do not forget to disable the form default behavior with
$('form.ajax').on('submit', function(event) {
event.preventDefault();
.
.
});
See documentation for more info
To enable debugging, you should wrap the whole submit handler in a try/catch because without it, errors will cause the default handler to submit the form, masking the errors. After the try/catch you can return false, so the page stays put.
<script src="http://ajax.googleapis.com/ajax/liubs/jquery/1.9.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$('form.ajax').on('submit', function() {
try {
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data - {};
that.find('[name]').each(function() {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
$.ajax({
url: url,
type: method:,
data: data,
success: function(response) {}
});
});
}
catch (err) {
console.log( 'submit handler error: ' + err.message );
}
return false;
});
</script>
You just had couple of typo, like - instead of = and extra :, else your code is fine, below is working example.
$(function(){
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function() {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
$.ajax({
url: url,
type: method,
data: data,
success: function(response) {
alert('posted')
}
});
});
return false;
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div data-role="main" class="ui-content">
<form method="POST" action="http://192.168.0.1/" class="ajax">
<input type="submit" name="parser" value="thisguy"/>
</form>
</div>
My script that runs on submit:
I have done correction to your code.
<script language="javascript" type="text/javascript">
$('form').on('submit', function(e) {
e.preventDefault();
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function() {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
$.ajax({
url: url,
type: method,
data: data,
success: function(response) {}
});
});
return false;
});
</script>
This code will submit the information from the form to a php file, everything works as it should, but when i write "hello this a text + - * " it remove the " + " sign from what i wrote, always. I dont know why, please help me out guys
$(document).ready(function(){
$("form#submit").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var fname = $('#fname').attr('value');
var lname = $('#lname').attr('value');
$.ajax({
type: "POST",
url: "Mail.php",
data: "fname="+ fname + "&lname=" + lname,
success: function(){
$('form#submit').show();
//$('form#submit :input').val("");
$('div.success').fadeIn();
}
});
return false;
});
});
Change this line:
data: "fname="+ fname + "&lname=" + lname,
to:
data: "fname="+ encodeURIComponent(fname) + "&lname=" + encodeURIComponent(lname),
You need to escape special characters for use in URL strings.
if fname and lname are text boxes, why not use the .val() to retrieve them?
var fname = $('#fname').val();
var lname = $('#lname').val();
or better, use form .serialize() directly on the ajax:
$(function () {
$("form#submit").submit(function () {
var form = $(this)
$.ajax({
type: "POST",
url: "Mail.php",
data: form.serialize() //turns the form data into a query string
success: function () {
$('form#submit').show();
$('div.success').fadeIn();
}
});
return false;
});
});
That's because the pluses are converted to spaces. Use encodeURIComponent to escape the input. Always use some kind of escaping to avoid injections.
Or you could use serialize():
$.ajax({
...
data: $(this).serialize()
...
});
This takes all the :input elements inside your form and encodes them properly for sending to a remote server. You could also do this:
data: {
fname: fname,
lname: lname
}
jQuery understands that you're trying to send an array of values and will automatically escape it.
Btw, this is not very portable:
var fname = $('#fname').attr('value');
The better way is this:
var fname = $('#fname').val();
var email = $('#email').val();
var data = 'email=' + encodeURIComponent(email);
var url = 'test.php'
var type = 'post'
var success = function(output){}
var error = function(){}
$.ajax({
url:url,
type:type,
data:data,
success:success,
error:error
});
work great for me