I want to insert data into table using ajax so data will insert without reload of page.
This code insert data into table very well but code also reload the page.
But I want insert without reloading of page.
How can i do this ?
<?php
include('connection.php');
if(isset($_POST['cmt'])){
$comment = addslashes($_POST['cmt']);
$alertid = $_POST['alert_id'];
mysql_query("INSERT INTO `comments` (`id`, `alert_id`, `comment`, `username`) VALUES (NULL, '".$alertid."', '".$comment."', 'tomas')");
}
?>
<script>
function submitform(){
var comment = $("#comment").val();
var alertid = $("#alertid").val();
$.ajax({
type: "POST",
//url: "ana.php",
data:{cmt:comment,alert_id:alertid}
}).done(function( result ) {
$("#msg").html( result );
});
}
</script>
<form method = "POST" onsubmit = "submitform()">
<textarea onFocus = "myFunction(1)" onBlur = "myFunction(0)" style="margin: 0px 0px 8.99305534362793px; width: 570px; height: 50px;" rows = "6" cols = "40" id = "comment"></textarea><br />
<input type = "text" placeholder="Enter Maximium 100 Words" id = "alertid" value = "10">
<input type = "submit" name = "submit" value = "Comment">
</form>
try this add this to form onsubmit = "return submitform();"
function submitform(){
var comment = $("#comment").val();
var alertid = $("#alertid").val();
$.ajax({
type: "POST",
//url: "ana.php",
data:{cmt:comment,alert_id:alertid}
}).done(function( result ) {
$("#msg").html( result );
});
return false;
}
return false from your event handler function.
onsubmit="submitform(); return false;">
Consider moving to modern methods of event binding.
You have to create a php file that insert into your table the posted data and call it with ajax like that :
$.ajax({
url: "/file.php",
type: "POST",
cache: false,
dataType: "json",
data: postValue,
success: function(results) {
bootbox.alert(results.message, function() {
bootbox.setIcons(null);
window.location.reload();
});
},
error: function(results) {
bootbox.alert(results.message, function() {
bootbox.setIcons(null);
});
}
});
Related
Is it possible to send form elements (serialized with .serialize() method) and other parameters with a single AJAX request?
Example:
$.ajax({
type : 'POST',
url : 'url',
data : {
$('#form').serialize(),
par1 : 1,
par2 : '2',
par3: 232
}
}
If not what's the best way to submit a form together with other parameters?
Thanks
serialize() effectively turns the form values into a valid querystring, as such you can simply append to the string:
$.ajax({
type : 'POST',
url : 'url',
data : $('#form').serialize() + "&par1=1&par2=2&par3=232"
}
Alternatively you could use form.serialize() with $.param(object) if you store your params in some object variable. The usage would be:
var data = form.serialize() + '&' + $.param(object)
See http://api.jquery.com/jQuery.param for further reference.
I dont know but none of the above worked for me, Then i used this and it worked :
In form's serialized array it is stored as key value pair
We pushed the new value or values here in form variable and then we can pass this variable directly now.
var form = $('form.sigPad').serializeArray();
var uniquekey = {
name: "uniquekey",
value: $('#UniqueKey').val()
};
form.push(uniquekey);
If you want to send data with form serialize you may try this
var form= $("#formId");
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()+"&variable="+otherData,
success: function (data) {
var result=data;
$('#result').attr("value",result);
}
});
$("#add_form").submit(function(e) {
e.preventDefault();
var total_qty = $('#total_qty').text();
var total_amt = $('#total_amt').text();
$("#add_btn").val('adding....');
$.ajax({
url: 'action.php',
method: 'post',
data: $(this).serialize() + "&total_qty="+total_qty + "&total_amt="+total_amt,
success: function(data){
console.log(data);
}
});
});
pass value of parameter like this
data : $('#form_id').serialize() + "¶meter1=value1¶meter2=value2"
and so on.
Following Rory McCrossan answer, if you want to send an array of integer (almost for .NET), this is the code:
// ...
url: "MyUrl", // For example --> #Url.Action("Method", "Controller")
method: "post",
traditional: true,
data:
$('#myForm').serialize() +
"¶m1="xxx" +
"¶m2="33" +
"&" + $.param({ paramArray: ["1","2","3"]}, true)
,
// ...
encode in js :
var temp = $("#pay_property_amount").serialize();
temp = btoa(temp);
and pass in ajex
data: { temp_data : temp },
decode in php
$temp_data = base64_decode($this->input->post('temp_data'));
if($temp_data){
$temp_data = $this->unserializeForm($temp_data);
}
function unserializeForm($str) {
$returndata = array();
$strArray = explode("&", $str);
$i = 0;
foreach ($strArray as $item) {
$array = explode("=", $item);
if (preg_match('/(%5B%5D)/', $array[0])) {
$array[0] = str_replace('%5B%5D','',$array[0]);
if(array_key_exists($array[0],$returndata)){
$returndata[$array[0]][]=$array[1];
}else{
$returndata[$array[0]] =array();
$returndata[$array[0]][]=$array[1];
}
}else
{
$returndata[$array[0]] = $array[1];
}
}
return $returndata;
}
Those who want to add new data to form data can use this method.
Exemple:
$("form#myForm").submit(function(e){
e.preventDefault();
let formData = jQuery("#myForm").serializeArray();
let newData = [
{name:"city", value: "Ankara"},
{name:"jobs", value: "Full-Stack Web Developer"},
{name:"action", value: "ajax_proccess"}
];
let postData = formData.concat(newData);
console.log(formData);
console.log(newData);
console.log(postData);
jQuery(".alert").text("İş: " + postData[4]['value']);
jQuery.ajax({
url: jQuery("#myForm").attr('action'),
type: 'POST',
dataType: 'json',
data: postData,
success: function(data) {
//let response = JSON.parse(data);
console.log(data);
alert('Submitted.');
jQuery(".alert").text(newData[5]);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST" action="" id="myForm">
<input type="hidden" name="name" value="Mahmut Yüksel">
<input type="hidden" name="surname" value="Mert">
<input type="hidden" name="countary" value="Turkey">
<input type="submit" value="Gönder">
</form>
<div class="alert">İş: </div>
You can also use serializeArray function to do the same.
You can create an auxiliar form using jQuery with the content of another form and then add thath form other params so you only have to serialize it in the ajax call.
function createInput(name,value){
return $('<input>').attr({
name: name,
value: value
});
}
$form = $("<form></form>");
$form.append($("#your_form input").clone());
$form.append(createInput('input_name', 'input_value'));
$form.append(createInput('input_name_2', 'input_value_2'));
....
$.ajax({
type : 'POST',
url : 'url',
data : $form.serialize()
}
I fix the problem with under statement ;
send data with url same GET methode
$.ajax({
url: 'includes/get_ajax_function.php?value=jack&id='+id,
type: 'post',
data: $('#b-info1').serializeArray(),
and get value with $_REQUEST['value'] OR $_GET['id']
I have some page with form, which loading some data to POST when i submit it. Then it links user to the next page. On this page I catch data from POST, and I have two dropdownlists, where the second one depends on the first. The first get's value from POST data:
echo '<script type="text/javascript">
jQuery("#markid").val("'.$GLOBALS["i"].'"); </script>';
Where $GLOBALS["i"] = id from DB, which has kept in data from POST by previous page.
But it doesn't work for the second dropdownlist which depends on it:
echo '<script type="text/javascript">
jQuery("#comm").val("'.$GLOBALS["i1"].'"); </script>';
I think it can be from the part of code, which realises depending of the second dropdown list:
<script>
jQuery(function(){
var id = jQuery(".mark").val();
jQuery.ajax({
type:"POST",
url: "wp-content/com.php",
data: {id_mark: id},
success: function(data){
jQuery(".comm").html(data);
}
});
jQuery(".mark").change(function(){
var id = jQuery(".mark").val();
if(id==0){
}
jQuery.ajax({
type:"POST",
url: "wp-content/com.php",
data: {id_mark: id},
success: function(data){
jQuery(".comm").html(data);
}
});
});
Where "mark" - first dropdownlist, "comm" - the second one.
This is the first part of my problem.
The second: I have some value on the page which depends on the value of the second dropdownlist. I tried to:
jQuery(".comm").change(function(){
var id = jQuery(".comm").val();
if(id==0){
}
jQuery.ajax({
type:"POST",
url: "wp-content/pricecar.php",
data: {id_mark: id},
success: function(data){
jQuery(".price9").html(data);
var price1 = jQuery(".price1").val();
var price2 = jQuery(".price2").val();
var price3 = jQuery(".price3").val();
var price4 = jQuery(".price4").val();
var price5 = jQuery(".price5").val();
var price6 = jQuery(".price6").val();
var price7 = jQuery(".price7").val();
var price8 = jQuery(".price8").val();
var price9 = jQuery(".price9").val();
jQuery.ajax({
type:"POST",
url: "../wp-content/price.php",
data: {price1: price1,price2: price2,price3: price3,price4: price4,price5: price5,price6: price6,price7: price7,price8: price8, price9: data},
success: function(data){
jQuery(".summPrice").html(data);
}
});
}
});
But it works only one time, and i don't know why.
I'll be glad for any offers.
I don't have a full visibility of the rendered html and of the ajax responses, but I would give a try with:
Remove this lines
echo '<script type="text/javascript">
jQuery("#markid").val("'.$GLOBALS["i"].'");
</script>';
echo '<script type="text/javascript">
jQuery("#comm").val("'.$GLOBALS["i1"].'"); </script>';
And do something like this where you print the html
...
<select id="markid" data-val="<?php echo isset($GLOBALS["i"]) ? $GLOBALS["i"] : -1;?>"></select>
<select id="comm" data-val="<?php echo isset($GLOBALS["i1"]) ? $GLOBALS["i1"] : -1;?>"></select>
And in your javascript have something like
<script>
(function ($) {
//when everything is ready
$(fillUpCommOptions);
$(watchSelectsChanges);
function fillUpCommOptions() {
var id = $('#markid').data('val') ? $('#markid').data('val') : $('#markid').val();
$('#markid').removeAttr('data-val');//remove data-val, at next change event we want the select new val
$.ajax({
type: "POST",
url: "wp-content/com.php",
data: {id_mark: id},
success: function (data) {
//assuming data is something like
// '<option value="niceValue">nice value</option>
$("#comm").html(data);
if ($("#comm").data('val')) {
//apply values from post also for the second dropdown
// assuming that data contains and option with value == $("#comm").data('val')
$("#comm").val($("#comm").data('val'));
$('#comm').removeAttr('data-val');
$("#comm").change()//trigger change after setting the value
}
}
});
}
function watchSelectsChanges() {
$('#markid')
.off('change')//just in case, could not be needed
.on('change', fillUpCommOptions);
$('#comm')
.off('change')//just in case, could not be needed
.on('change', handleDependentValues);
}
function handleDependentValues() {
var id = $("#comm").val();
if (id) {
$.ajax({
type: "POST",
url: "wp-content/pricecar.php",
data: {id_mark: id},
success: function (data) {
jQuery(".price9").html(data);
var price1 = jQuery(".price1").val();
var price2 = jQuery(".price2").val();
var price3 = jQuery(".price3").val();
var price4 = jQuery(".price4").val();
var price5 = jQuery(".price5").val();
var price6 = jQuery(".price6").val();
var price7 = jQuery(".price7").val();
var price8 = jQuery(".price8").val();
var price9 = jQuery(".price9").val();
jQuery.ajax({
type: "POST",
url: "../wp-content/price.php",
data: {
price1: price1,
price2: price2,
price3: price3,
price4: price4,
price5: price5,
price6: price6,
price7: price7,
price8: price8,
price9: data
},
success: function (data) {
jQuery(".summPrice").html(data);
}
});
}
})
}
}
})(jQuery);
I have an working ajax function where the user types something in a textarea, press enter, and whatever the user types in, will be output to the screen. Right now I'm trying to find a way to clear the textarea after the user presses enter. How do I do that?
test1.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function ajaxPass(gotoUrl,getValueFrom,output) {
var input = document.getElementById(getValueFrom).value; // or $('#t').val();
$.ajax({
type: "POST",
url: gotoUrl,
data: { input : input },
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( output ).innerHTML = data;
}
});
}
</script>
<textarea id = 'textarea' rows = "25" cols = "50" onKeyDown="if(event.keyCode==13) ajaxPass('robotChat2.php','textarea','output')"> </textarea>
<div id = 'output'> </div>
test2.php
<?php
$input = $_POST['input'];
echo $input;
?>
Add $("#textarea").val(''); at the end of your function.
function ajaxPass(gotoUrl,getValueFrom,output) {
var input = document.getElementById(getValueFrom).value; // or $('#t').val();
$.ajax({
type: "POST",
url: gotoUrl,
data: { input : input },
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( output ).innerHTML = data;
}
});
$("#"+getValueFrom).val('');
}
I'm submitting a form via AJAX and utilising jQuery and I need to find out how I cna pass form arrays to it.
For example, my html would be something like:
<input id="standard_field" type="text" name="standard_name">
<input id="some_id_1" type="text" name="my_array[my_name_1]">
<input id="some_id_2" type="text" name="my_array[my_name_2]">
<input id="some_id_3" type="text" name="my_array[my_name_3]">
Now I know you can easily get the name of the standard field in jQuery using something like:
var foo = $('standard_field').val();
But I'm not sure how to get the array data? Also, it needs to be passed to the PHP script from ajax in exactly the same way the PHP script would get it as if the form was submitted without ajax.
So an example of how I would normally pass data:
var foo = $('standard_field').val();
var loadUrl = "some_script.php";
var dataObject = { foo: foo };
getAjaxData(loadUrl, dataObject, 'POST', 'json')
.done(function(response) {
//..........
})
.fail(function() {
//......
});
// End
function getAjaxData(loadUrl, dataObject, action, type) {
return jQuery.ajax({
type: action,
url: loadUrl,
data: dataObject,
dataType: type
});
}
So firstly how can I get the data to pass from the form and secondly how can I pass it from jQuery to the PHP script so PHP get's it as an array like it would if it was POST'ed straight to the PHP script?
You should use serialize
HTML:
<form id="form1" action="" method="post">
<input id="standard_field" type="text" name="standard_name">
<input id="some_id_1" type="text" name="my_array[my_name_1]">
<input id="some_id_2" type="text" name="my_array[my_name_2]">
<input id="some_id_3" type="text" name="my_array[my_name_3]">
</form>
JS:
var dataObject = $('#form1').serialize();
var loadUrl = "some_script.php";
getAjaxData(loadUrl, dataObject, 'POST', 'json')
.done(function(response) {
//..........
})
.fail(function() {
//......
});
// End
function getAjaxData(loadUrl, dataObject, action, type) {
return jQuery.ajax({
type: action,
url: loadUrl,
data: dataObject,
dataType: type
});
}
You can use this plugin http://malsup.com/jquery/form/
Example code:
JS:
$('#your_button').change(function() {
var options = {
url: 'your_url',
type: 'POST',
dataType: 'json',
beforeSubmit: function() {
// Callback function to be invoked before the form is submitted
},
success: function(data) {
// Callback function to be invoked after the form has been submitted
},
error: function() {
// Callback function to be invoked upon error
}
};
// do something
});
PHP:
var_dump($_POST);
You can use the String.slice method to extract the label name.
var input = $('#myform input');
var data = [];
var name, label, value = '';
for(var i in input) {
name = input.eq(i).attr('name');
label = name.splice(9, -1);
value = input.eq(i).val();
data[label] = value;
}
data = JSON.stringify(data);
And for detect when it's an array you can user String.indexOf('[') like
For an unknown array structure :
array_name = name.splice(0, name.indexOf('['));
label = name.splice(name.indexOf('['), name.indexOf(']'));
Hi i have jquery request like below ,
$('#filterForm').submit(function(e){
e.preventDefault();
var dataString = $('#filterForm').serialize();
var class2011 = document.getElementById("2011").className;
//var validate = validateFilter();
alert(dataString);
if(class2011=='yearOn')
{
dataString+='&year=2011';
document.getElementById("2011").className='yearOff';
}
else
{
document.getElementById("2011").className='yearOn';
}
alert (dataString);
$.ajax({
type: "POST",
url: "myServlet",
data: dataString,
success: function(data) {
/*var a = data;
alert(data);*/
}
});
and my Form is like ,
<form method="post" name="filterForm" id="filterForm">
<!-- some input elements -->
</form>
Well, I am triggering jquery submit on submit event of a form ,(it's working fine)
I want pass one extra parameter inside form which is not in above form content but it's outside in page
it's like below
[Check this image link for code preview][1]
So how can i trigger above event , on click of , element with class yearOn ( check above html snippet ) and class yearOff , with additional parameter of year set to either 2011 or 2010
$(document).ready(function () {
$('#filterForm').submit(function (e) {
e.preventDefault();
var dataString = $('#filterForm').serialize();
if ($("#2011").hasClass('yearOn')) {
dataString += '&year=2011';
$("#2011").removeClass('yearOn').addClass('yearOff');
}
else {
$("#2011").removeClass('yearOff').addClass('yearOn');
}
$.ajax({
url: "/myServlet",
type: "POST",
data: dataString,
success: function (data) {
/*var a = data;
alert(data);*/
}
});
});
});
1.) If you are using jQuery already, you can use the $.post() function provided by jquery. It will make your life easier in most cases.
2.) I have always had a successful post with extra parameters this way:
Build you extra parameters here
commands={
year:'2011'
};
Combine it with your form serialize
var dataString=$.param(commands)+'&'+$("#filterForm").serialize();
Perform your post here
$.post("myServlet",data,
function(data) {
/*var a = data;
alert(data);*/
}
);
OR use $.ajax if you really love it
$.ajax({
type: "POST",
url: "myServlet",
data: dataString,
success: function(data) {
/*var a = data;
alert(data);*/
}
In the end, here is the full code the way you are doing it now
$('#filterForm').submit(function(e){
e.preventDefault();
var class2011 = document.getElementById("2011").className;
//var validate = validateFilter();
alert(dataString);
if(class2011=='yearOn') {
dataString+='&year=2011';
document.getElementById("2011").className='yearOff';
} else {
document.getElementById("2011").className='yearOn';
}
commands={
year:'2011'
};
var dataString=$.param(commands)+'&'+$("#filterForm").serialize();
alert (dataString);
$.ajax({
type: "POST",
url: "myServlet",
data: dataString,
success: function(data) {
/*var a = data;
alert(data);*/
}
});