How to reset div data which I am appending on click? - php

Here I want to reset the appended data on click. So I can get the fresh data by removing the old data. Now actually data is coming, but the new data is getting appended with the old data which I need to remove.
$("#button").click(function(){
etc=$("#etc").val();
$.ajax({
url: 'db4.php',
type: 'POST',
data: {
etc: etc
},
error: function() {
$('#div1').html('<p>An error has occurred</p>');
},
success: function(data) {
var result = $.parseJSON((data));
$.each(result,function(i,field){
document.getElementById("div1").innerHTML=field.name;
$('body').append(document.getElementById("subasish123").innerHTML);
$('#subasish123').slice(0).hide();
});
}
});
});
<form>
<input id="etc" type="text" name="etc">
<label id="button">Click</label>
</form>
<div id="subasish123">
<div id="div1"></div>
</div>

Try redirecting your output to some other element instead of body.
Emptying the body of your HTML wouldn't be desirable.
Look at this fiddle for example:
jsfiddle.net

Related

value is not coming $POST array in php

I am building a simple sign up form using ajax when I creating a data object and pass to PHP file.It shows variables and doesn't show values of that PHP variable.
The code of HTML of form is
<form id="myForm" name="myForm" action="" method="POST" class="register">
<p>
<label>Name *</label>
<input name="name" type="text" class="long"/>
</p>
<p>
<label>Institute Name *</label>
<input name="iname" type="text" maxlength="10"/>
</p>
<div>
<button id="button" class="button" name="register">Register »</button>
</div>
</form>
The code of js is
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var form=$("#myForm").serialize();
$("#button").click(function(){
$.ajax({
type:"POST",
url: "mainlogic.php",
data:form,
success: function(result){
alert(result);
}
});
});
})
</script>
The code of PHP is
(mainlogic.php)
if(isset($_POST)) {
print_r($_POST);//////varaibles having null values if it is set
$name=trim($_POST['name']);
echo $name;
}
You are serializing your form on document load. At this stage, the form isn't filled yet. You should serialize your form inside your button click event handler instead.
$(document).ready(function(){
$("#button").click(function(){
var form=$("#myForm").serialize();
$.ajax({
type:"POST",
url: "mainlogic.php",
data:form,
success: function(result){
alert(result);
}
});
});
})
In this code you serialize blank form, just after document is ready:
<script>
$(document).ready(function(){
var form=$("#myForm").serialize();
$("#button").click(function(){
$.ajax({
type:"POST",
url: "mainlogic.php",
data:form,
success: function(result){
alert(result);
}
});
});
})
</script>
Valid click function should begins like:
$("#button").click(function(){
var form=$("#myForm").serialize();
$.ajax({...
It means - serialize form right after button clicked.
var form = $("#myForm").serialize();
That is the line that collects the data from the form.
You have it immediately after $(document).ready(function() { so you will collect the data as soon as the DOM is ready. This won't work because it is before the user has had a chance to fill in the form.
You need to collect the data from the form when the button is clicked. Move that line inside the click event handler function.
The problem is that you calculate the form values at the beginning when loading the page when they have no value yet. You have to move the variable form calculation inside the button binding.
<script>
$(document).ready(function(){
$("#button").click(function(){
var form=$("#myForm").serialize();
$.ajax({
type:"POST",
url: "mainlogic.php",
data:form,
success: function(result){
alert(result);
}
});
});
})
</script>
Alpadev got the right answer, but here are a few leads that can help you in the future:
ajax
You should add the below error coding in your Ajax call, to display information if the request got a problem:
$.ajax({
[…]
error: function(jqXHR, textStatus, errorThrown){
// Error handling
console.log(form); // where “form” is your variable
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
$_POST
$_POST refers to all the variables that are passed by the page to the server.
You need to use a variable name to access it in your php.
See there for details about $_POST:
http://php.net/manual/en/reserved.variables.post.php
print_r($_POST); should output the array of all the posted variables on your page.
Make sure that:
⋅ The Ajax request ended correctly,
⋅ The print_r instruction is not conditioned by something else that evaluates to false,
⋅ The array is displayed in the page, not hidden by other elements. (You could take a look at the html source code instead of the output page to be sure about it.)

AJAX Page with Boostrap Modal Form - Submit don't work

i searched a lot about this problem, but I didn't find a solution, yet.
At first a short description about my setup to make my problem clearer.
Settings.php Page with a Menu, where you can select different settings categories
By clicking on one menu point the corresponding loads by ajax and is displayed.
$('#content').load("http://"+ document.domain + "/domainhere/settings/menupoint1.php");
On the menupont1.php page I got a list with mysql data.
I implemented a "edit" button for each row - while clicking on the edit button, a boostrap modal appears with a form and the corresponding data filled in and ready to edit.
When i now click on "Save changes", the POST-Request is always empty.
To realize the form submit, I already tried several codes:
e.g.:
$.ajax({
type: "POST",
url: "php/form-process.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
}
}
});
or
$(function(){
$('#editform').on('submit', function(e){
e.preventDefault();
$.ajax({
url: url, //this is the submit URL
type: 'GET', //or POST
data: $('#editform').serialize(),
success: function(data){
alert('successfully submitted')
}
});
});
});
At the moment:
while($xy= $xysql->fetch_assoc()) {
<div class="modal fade" id="edit-<?php echo $xy["id"] ?>" [..]>
<button id="submit>" class="btn btn-default">Save</button>
</div>
<script>
$(function() {
$('button#submit').click(function(){
$.ajax({
type: 'POST',
url: './test2.php',
data: $('form#modal-form').serialize(),
success: function(msg){
$('#test').html(msg)
$('#form-content').modal('hide');
},
error: function(){
alert('failure');
}
});
});
});
</script>
Maybe someone here could help me out with this problem?
thank you very much :)
I've set up a minimal example of how this would work:
example html of two modals, which are produced in a loop in your case.
I've now done it without a unique id, but with selecting via class.
<div class="modal">
<!-- // this classname is new and important -->
<form class="editform">
<input name="test" value="value1">
<button class="btn btn-default">Save</button>
</form>
</div>
<div class="modal">
<form class="editform">
<input name="test" value="value2">
<button class="btn btn-default">Save</button>
</form>
</div>
Your javascript would be something like this:
$(function() {
var formsAll = $('.editform');
// changed this to onSubmit, because it's easier to implement the preventDefault!
formsAll.on('submit',function(e){
e.preventDefault();
var formData = $(this).serialize();
console.log(formData);
// add your ajax call here.
// note, that we already have the formData, it would be "data: formData," in ajax.
});
});
Note, that I don't have your real html structure, so details might vary. But you get the idea.
also available here:
https://jsfiddle.net/a0qhgmsb/16/

Modal shows the content of html instead of its own content

I don't get why the modal is showing my html's body content when I submit an input instead of the result of php.
I tried debugging it,then i found out that the modal shows its own content when I add data-toggle and data-target to the input/form, but the problem is that the modal shows after I click on the input even before I can even type something,and even I managed to type something, the same problem still exists
Here's the form:
<form id="form_id" action="some_php.php" method="POST">
<input id="input_id" type="text" name="input_name">
</form>
Here's the script:
$(document).ready(function()
{
$("#form_id").submit(function(e)
{
e.preventDefault();
$.ajax({
type: 'POST',
data: $("form_id").serialize(),
url: 'some_php.php',
success: function(data) {
$("#fetched-data").html(data);
$("#myModal").show('show');
}
});
return false;
});
});

ajax request not working?

I am sending ajax request to a php page on a button click. Here is my request being sent
$("#enteruser").on('click',function(){
console.log("entered here");
var name=$("#ename").val();
var email=$("#eemail").val();
var role=$("#erole").val();
var data={name: name, email:email, role:role};
var url='addemployee.php';
$.ajax({
url : url,
data: data,
type: 'POST',
success: function(response)
{
if(response=="success")
{
$("#rmsg").text("Hello World");
}
else
{
}
}
});
});
My this line is not working and URL after returning back contains the values I sent. So If I resend request the request is not sent again due to url. If I put the following line
window.location="anotherpage.html"; in the success block the page is redirected to the that page. Then why the rmsg paragraph is not being written?
I am adding the form dynamically using the following code
$("#create").on('click',function(){
var htmc='<div class="testbox">\n\
<h1>Create Employee</h1>\n\
<form>\n\
<hr>\n\
<label id="icon" for="eemail"><i class="icon-envelope "></i></label>\n\
<input type="text" name="eemail" id="eemail" placeholder="Email" required/>\n\
<label id="icon" for="ename"><i class="icon-user"></i></label>\n\
<input type="text" name="ename" id="ename" placeholder="Name" required/>\n\
<label id="icon" for="erole"><i class="icon-road"></i></label>\n\
<input type="text" name="erole" id="erole" placeholder="Role" required/>\n\
<button id="enteruser" class="button">Enter</button>\n\
</form>\n\
</div>';
$("#view").html(htmc);
});
$(document).on("#enteruser",'click',function(e){
e.preventDefault();
console.log("entered here");
var name=$("#ename").val();
var email=$("#eemail").val();
var role=$("#erole").val();
var data={name: name, email:email, role:role};
var url='addemployee.php';
$.ajax({
url : url,
data: data,
type: 'POST',
success: function(response)
{
if(response=="success")
{
alert(response);
$("#rmsg").text("Hello World");
}
else
{
}
}
});
});
One thing i like to do when troubleshooting HTTP calls is to view the actual network event in a debugging tool.
In Google Chrome, use CTRL + SHIFT + I to open up the debugging tools. Then click on the Network tab. In here, you may view the POST and Response and verify that your response is correct.
In MS IE, you can hit F12 to view the developer tools there
Try this
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<input type="text" id="ename" />
<input type="text" id="eemail" />
<input type="text" id="erole" />
<span id="rmsg"></span>
<button id="enteruser">Button</button>
<script type="text/javascript">
$("#enteruser").on('click',function(){
console.log("entered here");
var name=$("#ename").val();
var email=$("#eemail").val();
var role=$("#erole").val();
var data={name: name, email:email, role:role};
var url='addemployee.php';
$.ajax({
url : url,
data: data,
type: 'POST',
success: function(response)
{
if(response=="success")
{
$("#rmsg").text("Hello World");
}
else
{
}
}
});
});
</script>
</body>
</html>
PHP:
<?php session_start(); echo 'success'; ?>
You are not preventing default behaviour for a form. YOu should say to your app: "do nothing with the form and make it handled by js".
Also you are using a delegated function in the wrong way.
To do so change this:
$("#enteruser").on('click',function(){
console.log("entered here");
to this:
$("#enteruser").click(function(e){
e.preventDefault();
console.log("entered here");
all the other part of your code can remain as now if the form is in the dom from the beginning.
$(document).on('click',"#enteruser",function(e){
e.preventDefault();
console.log("entered here");
if the form is added to the page after it is loaded. YOu can also replace document with any element already in the page that is before the form in the dom structure

jQuery Ajax post for newbie

First let me say I'm new to Ajax. I've been reading articles from jquery.com and some tutorials but I didn't figured it out yet how this works on what I'm trying to achieve.
I am trying to get the weather for a searched city using Google's Weather API XML, without page refresh.
I managed to retrieve the Weather XML and parse the data but everytime I search for a different place, the page reloads since my weather widget is under a tab.
This is what I have in my HTML:
<script type="text/javascript">
$(document).ready(function(){
// FOR THE TAB
$('.tab_btn').live('click', function (e) {
$('.tab_content').fadeIn();
});
$(".submit").click(function(){
$.ajax({
type : 'post',
url:"weather.php",
datatype: "text",
aysnc:false,
success:function(result){
$(".wedata").html(result);
}});
});
});
</script>
<style>.tab_content{display:none;}</style>
</head><body>
<input type="button" value="Show Content" class="tab_btn">
<div class="tab_content">
<h2>Weather</h2>
<form id="searchform" onKeyPress="return submitenter(this,event)" method="get"/>
<input type="search" placeholder="City" name="city">
<input type="hidden" placeholder="Language" name="lang">
<input type="submit" value="search" class="submit" style="width:100px">
</form>
<div id="weather" class="wedata">
</div>
</div>
And here is the actual demo I'm working on: http://downloadlive.org.
Now, if I add action="weather.php" on the search form I get the results, but I get redirected to weather.php which is logical. Without the action="weather.php", everytime I search my index which I'm on, adds up /?city=CITY+NAME which shouldn't. This should be added to weather.php, get the results and then retrieve them back into my index, if that makes sense?
This is my php code for weather.php: http://pastebin.com/aidXCeQg
which can be viewed here: http://downloadlive.org/weather.php
Can someone please help me out with this please?
Thanks alot
You just need to return false; from the click event handler. This will prevent the default action from occuring - in this case, submitting the form. Also, remove the async: false setting. You almost never want synchronous ajax requests.
$(".submit").click(function(){
$.ajax({
type : 'post',
url:"weather.php",
datatype: "text",
success: function(result){
$(".wedata").html(result);
}
});
return false;
});
Alternately you can pass a parameter name to the callback and then use event.preventDefault() to accomplish the same result as above:
$(".submit").click(function(e){
$.ajax({
type : 'post',
url:"weather.php",
datatype: "text",
success: function(result){
$(".wedata").html(result);
}
});
e.preventDefault();
});
You need to send the form data with the POST. It's super-easy to do this using .serialize().
$(".submit").click(function(){
$.ajax({
type : 'post',
url:"weather.php",
data: $(this.form).serialize(),
datatype: "text",
success: function(result){
$(".wedata").html(result);
}
});
return false;
});

Categories