I am trying to figure out how to output the ajax response from a form submission to a particular div. The form is dynamically generated buttons with data from mysql as values and for each button generated there is also a div created for the result like this.
Example form id's:
id="form1"
id="form2"
id="form3"
id="form4"
div id's:
<div class="res" id="result1">Display form1 data</div>
<div class="res" id="result2">Display form2 data</div>
<div class="res" id="result3">Display form3 data</div>
<div class="res" id="result4">Display form4 data</div>
Here is my example form. $count is incrementing the id "form" inside a while loop.
echo '<form name="v" action="test.php" value="' . $row['data'] . '" method="post" id="form' . $count . '"><input name="v" type="hidden" value="' . $row['data'] . '"><input type="submit" class="btn" value="Submit"></form>';
I can get this to work but it will fill all of the divs with the success response from clicking the submit buttons if I just use ".res" for the class which is why I need the unique id's using the incremented numbers from $count. I am unsure how to achieve to this though.
$(document).ready(function(){
$(document).on("submit", "#form", function(event)
{
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: $(this).attr("method"),
dataType: "text",
data: new FormData(this),
processData: false,
contentType: false,
success: function(data, status) {
$(".res").html(data);
},
error: function() {
alert('An error occurred.');
}
});
});
});
Could somebody help me out? Thanks.
You could extend the form tag with an data attribute, containing the target div.
echo '<form name="v" action="test.php" value="' . $row['data'] . '" method="post" id="form' . $count . '" data-target="result' . $count . '">...';
and later inside your ajax success function, do something like this
$(document).ready(function(){
$(document).on("submit", "form[data-target]", function(event)
{
var $target = $('#' + $(this).data('target'));
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: $(this).attr("method"),
dataType: "text",
data: new FormData(this),
processData: false,
contentType: false,
success: function(data, status) {
$target.html(data);
},
error: function() {
alert('An error occurred.');
}
});
});
});
You can use the fact that .each() provides a counter variable:
$("form").each(function (i) {
$(this).on("submit", function () {
// ...
// in the ajax success callback:
$(".res").eq(i).html(data);
IDs need to be unique so instead do
$(document).on("submit", "form", function(event) {
event.preventDefault();
var id = this.id; // form1, form2 etc
....
or
$(document).on("submit", "form[name='v']", function(event) {
event.preventDefault();
var id = this.id; // form1, form2 etc
....
and then
$("#"+id.replace("form","result")).html(data); // result1, result2 etc
OR use a data attribute on the form:
echo "<form data-id='result".$count."' ....>
and have
$(document).on("submit", "form[name='v']", function(event) {
event.preventDefault();
var id = $(this).data("id"); // result1, result2 etc
....
and then
$("#"+id).html(data); // result1, result2 etc
Related
Here is my view:
<div class="form-group col-md-3">
<label class="sup col-md-12 control-label">Employees</label>
<?php
if(isset($hiddenEmpArray)){
if(is_array($hiddenEmpArray)){
foreach($hiddenEmpArray as $hiddenEmpArraySingle){
echo '<input type="hidden" name="selectall[]" id="selectall" value="'. $hiddenEmpArraySingle. '">';
}
}
}
?>
</div>
Javascript:
$('#form').submit(function(e){
e.preventDefault();
var selectall =$("#selectall").val();
$.ajax({
type: "POST",
url: "<?php echo base_url()?>",
data: {selectall:selectall},
success: function (data) {
//alert(data);
},
error: function () {
alert("Server Error! Please try again later.");
}
});
});
Here I want to Submit this form through javascript.Here selectall is an array.When I Submit the form,Only One value is received .How Can I pass this array through javascript.Please help me
The serialize() method creates a URL encoded text string by
serializing form values.
$('#form').submit(function(e){
e.preventDefault();
var formId = $(this).attr('id');//getting form id
$.ajax({
type: "POST",
url: "<?php echo base_url()?>",
data: $('#' + formId).serialize(),//jquery id selector for the form
success: function (data) {
//alert(data);
},
error: function () {
alert("Server Error! Please try again later.");
}
});
});
you can just use this
var selectall = $("input[name='selectall[]']").map(function(){return $(this).val();}).get();
and then in success just do console.log(data);
you may use jquery each function to collect data
var selectall=[];
$.each($("input[name='selectall[]']"), function(){
selectall.push($(this).val());
});
I have a Leaflet map, and a text input. I want to take the address from the textbox, run it through a PHP script, and get the result all through jQuery.
Here is my form:
<form id="mapcheck" method="POST" action="geo.php">
<input id="largetxt" type="text" name="checkAddress">
<input id="button" type="submit" name="submit" value="Check">
</form>
Here is part of the PHP:
<?php
if (isset($_POST["checkAddress"])) { //Checks if action value exists
$checkAddress = $_POST["checkAddress"];
$plus = str_replace(" ", "+", $checkAddress);
$json = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=' . $plus . '&key=GMAPSKEY');
$obj = json_decode($json);
$mapLat = $obj->results[0]->geometry->location->lat;
$mapLng = $obj->results[0]->geometry->location->lng;
$coords = ('' . $mapLat . ', ' . $mapLng . '');
return $coords;
}
?>
And the jQuery:
$(document).ready(function() {
$("#button").click(function(){
$.ajax({
url: "geo.php",
method: "POST",
data: {
checkAddress: $("#largetxt").val()
},
success: function(response){
console.log(response);
}
});
});
});
I need to listen on submit of the form via jQuery (NOT PHP), run it through a geocode script, then take that result and put it through regular JavaScript (Leaflet map.) I have played around with the AJAX feature of jQuery to no avail. There is a very simple solution to this, but I have not figured it out.
UPDATE: Problem resolved, thanks Vic.
You would need AJAX. Remove the form element but keep the inputs.
$("#button").click(function(){
$.ajax({
url: "geo.php",
method: "POST",
data: {
checkAddress: $("#largeText").val()
},
success: function(response){
console.log(response);
//your script
}
})
});
The code below sends the id of item to more.php to load more content. It works fine. Now to add some more features I need to send one more id to more.php through the same code.
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.show_more',function(){
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type:'POST',
url:'more.php',
data:'id='+ID,
success:function(html){
$('#show_more_main'+ID).remove();
$('.display').append(html);
}
});
});
});
</script>
Suppose second id is var catid = '<?php echo $cat ?>'; how to send this catid through the same ajax code. data : {id : id, catid : catid} is something I should do but can't get how to deal in current situation when my data carries data:'id='+ID,.
your should look like. specify your data as an object:
<script type="text/javascript">
$(document).ready(function () {
$(document).on('click', '.show_more', function () {
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type: 'POST',
url: 'more.php',
data: { id:ID, userid: userid },
success: function (html) {
$('#show_more_main' + ID).remove();
$('.display').append(html);
}
});
});
});
To retrieve multiple input's I suggest combining them in a Form:
first embed your inputs in an form with a submit button, you should also not use the same name twice because it won't work now, create unique names
<form action="GET" id="myForm">
<input id="string" type="text" name="string" />
<input id="string2" type="text" name="string" />
<input type="submit" value="Go" />
</form>
and write code to submit the ajax way
$('#myForm').submit(function(event) {
// Stop form from submitting normally
event.preventDefault();
var $form = $(this);
$.ajax({
type: "GET",
url: "retrieve.php",
data: $form.serialize(), //make it JSON
success: function() {
console.log("it worked");
}
});
});
I'm trying to display two PHP echo messages from a seperate PHP file onto my HTML body page. Whenever you click the submit button the echo message should popup in the HTML page without redirecting me to the PHP page.
I need to connect to my two files through Javascript so I wrote a script attemtping to connect the HTML file with the PHP file.
My HTML:
<div id="formdiv">
<form action="phpfile.php" method="get" name="fillinform" id="fillinform" class="js-php">
<input id="fillintext" name="fill" type="text" />
<input type="submit" id="submit1" name="submit1">
</form>
</div>
phpfile.php:
$q = $_GET['fill'];
$y = 2;
$work = $q * $y;
$bork = $work * $q;
echo json_encode($work) ."<br>";
echo json_encode($bork);
Javascript:
$(".js-php").submit(function()
var data = {
"fill"
};
data = $(this).serialize() + $.param(data);
$.ajax({
type:"GET",
datatype:"json",
url:"phpfile.php",
data: data,
success: function (data){
$(".formdiv").html(
""
"Your input: ")
}
You attached your logic to .submit() event and if you don't prevent default action, the form will be submitted to server. You can prevent it that way:
$(".js-php").submit(function(e) {
// your code goes here
e.preventDefault();
});
You'll have to append the data to your div like this:
success: function (data) {
$(".formDiv").append("Your input: " + data);
}
As per your html you should try this below code :
If you want to replace the whole html inside the div having id="formdiv"
success: function (data){
$("#formdiv").html("Your input: "+data)
}
or
success: function (data){
$("#formdiv").text("Your input: "+data)
}
If you want to append data to the div having id="formdiv"
success: function (data){
$("#formdiv").append("Your input: "+data)
}
Add curly braces after $(".js-php").submit(function(e) and close it after your ajax ends.
Add e.preventDefault() before you call ajax so it will not redirect
you to phpfile.php
Add alert(data) inside your function called at success of ajax.
there is a syntax error n line $(".formdiv").html("""Your input: ");
Your updated code should look like.
$(".js-php").submit(function(e){
var data = {
"fill"
};
data = $(this).serialize() + $.param(data);
$.ajax({
type:"GET",
datatype:"json",
url:"phpfile.php",
data: data,
success: function (data){
alert(data);
}
}
I have an HTML form that Is only composed of a button with a value. I would like to leave it this way. I am using AJAX/JQuery to pass the form data to a PHP script. But, for some reason, the button value is not sent. What could I be doing wrong?
HTML:
<form id="friend-send" method="post" action="">
<button type="submit" class="foll" name="approve-friend" value="4"> Approve </button>
</form>
AJAX/JQUERY:
$(document).ready(function() {
$("#friend-send").submit(function(e) {
var $this = $(this);
var dataString = $this.serialize();
e.preventDefault();
$.ajax({
type: "POST",
url: "relate.php",
data: dataString,
async: false,
success: function() {
$this.hide();
}
});
});
});
JQuery won't serialize a button, use a hidden field instead
<form id="friend-send" method="post" action="">
<input type="hidden" name="approve-friend" value="4" />
<button type="submit" class="foll"> Approve </button>
</form>
Also, You need to serialze the form by id, not the button by id
Instead of this
$("#friend-request-buttons")
It should be this
$("#friend-send")
Lastly, since you are using ajax to post, you can simplfy your form open tag to this...
<form id="friend-send">
<button>
tags are not supported by serialize https://api.jquery.com/serialize/
You would need to use an input of some kind. A hidden one would work.
Don't use serialize, create the input data yourself:
var dataString = {};
var $button = $this.find("[type=submit]");
dataString[$button.attr('name')] = $button.val();
When you provide an object as the data: argument to $.ajax, jQuery will serialize it automatically.
This answer would be if you are set on using the button alone
$(document).ready(function() {
$("#friend-send").submit(function(e) {
var $this = $(this);
var dataString = "?" + $(this).find('button').attr('name') + "=" + $(this).find('button').attr('value');
e.preventDefault();
$.ajax({
type: "POST",
url: "relate.php",
data: dataString,
async: false,
success: function() {
$this.hide();
}
});
});
});