Get data with AJAX and save them as variables - ajax

I'm totally new to AJAX and I don't seem to know the best way to search what I'm looking for. So trying to explain it here.
I have a table which lists my users. I want to be able to edit any row of the table without refreshing. So I added a button for each row, by clicking which you'll be able to edit that user with the help of Bootstrap modals.
There's this button which initiates the action:
<span class="updateInfo" user-id="<?php echo $users_array['id']; ?>" data-target=".editInfo" data-toggle="modal"><i class="fa fa-pencil" ></i></span>
$users_array is an array fetched earlier from a table in database. The table also has 'id, name, email, phone' as columns.
So, what I basically have in my JS code is this:
jQuery(document).ready(function() {
$('.updateInfo').click(function(){
var userID = $(this).attr('user-id');
$.ajax({
url: "edit.php",
method: "POST",
dataType: 'json',
data: {
selected_user_id: userID,
},
success: function(data) {
// I don't know what to do here :(
}
});
});
});
The codes included in edit.php file are as followed:
$user_id=$_POST['selected_user_id'];
$get_user=mysql_query("SELECT * FROM users WHERE id='$user_id'");
$user_array=mysql_fetch_row($get_user);
echo json_encode($user_array);
I didn't put the codes that establish database connection and the like, since they're basics and work fine.
I have several problems here:
I have no idea if the way I've written the code so far is correct.
How I'm supposed to get those results and save them as variables for a later use.
I don't know if I can use the newly created variables as placeholders or pre-defined values in a modal that exists in the original file.
P.S: The modal has a simple form with simple inputs for name, email and phone number:
<div class="modal fade editInfo" tabindex="-1" role="dialog" aria-labelledby="myNote" data-backdrop="static" aria-hidden="true">
<form method="POST">
<input name="fullname" value="" />
<input name="email" value="" />
<input name="phone" value="" />
</form>
</div>

set Id for each html element
jQuery(document).ready(function() {
$("#fullname").val("USer One ");
$("#email").val("User#gmail.com");
$("#phone").val("987654");
$('.updateInfo').click(function(){
var userID = $(this).attr('user-id');
$.ajax({
url: "edit.php",
method: "POST",
dataType: 'json',
data: {
selected_user_id: userID,
},
success: function(data) {
console.log(data);
$("#fullname").val(data.fullname);
$("#email").val(data.email);
$("#phone").val(data.phone);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div class="modal fade editInfo" tabindex="-1" role="dialog" aria-abelledby="myNote" data-backdrop="static" aria-hidden="true">
<form method="POST"> <input id="fullname" name="fullname" value="" /><input id="email" name="email" value="" /> <input id="phone" name="phone" value="" /> </form>
</div>
and then bind like this :

Related

AJAX form $('form')[0].reset(); on submit not clearing values. What am I missing?

thank you in advance for any help given. I'm just learning jQuery and AJAX and would appreciate some help with the following code. All validation rules work, the form submits and the page does not refresh. The problem is that the form values are not clearing/resetting to default after the submit has triggered. Thoughts?
**********EDITED to include HTML markup*************
<div id="form">
<h1 class="title">Contact Us</h1><!-- title ends -->
<p class="contactUs">Ask about our services and request a quote today!</p><!-- contactUs ends -->
<div id="success"><p>Your message was sent successfully. Thank you.</p></div>
<p id="required">* All fields required.</p>
<form name="form" id="contactMe" method="post" action="process.php" onSubmit="return validateForm()" enctype="multipart/form-data">
<input class="txt" type="text" maxlength="50" size="50" required name="name" value="<?php echo $_GET['name'];?>" placeholder="Name" />
<div id="nameError"><p>Your name is required.</p></div>
<input class="txt" type="text" maxlength="50" size="50" required name="email" value="<?php echo $_GET['email'];?>" placeholder="Email Address" />
<div id="emailError"><p>A valid email address is required.</p></div>
<textarea name="message" rows="6" cols="40" required placeholder="Message"></textarea>
<div id="messageError"><p>A message is required.</p></div>
<input type="hidden" maxlength="80" size="50" id="complete" name="complete" placeholder="Please Keep This Field Empty" />
<input type="submit" value="SUBMIT" name="submit" />
<input type="reset" value="RESET" name="reset" />
</form>
</div><!-- form ends -->
//hide form submit success message by default. to be shown on successfull ajax submission only.
$(document).ready(function() {
if ($('#success').is(':visible')){
$(this).hide()
}
});
//form validation
function validateForm() {
//name
var a=document.forms["form"]["name"].value;
if (a==null || a=="")
{
$('#nameError').fadeIn(250);
return false;
}
//email address
var c=document.forms["form"]["email"].value;
var atpos=c.indexOf("#");
var dotpos=c.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=c.length)
{
$('#emailError').fadeIn(250);
return false;
}
//message
var e=document.forms["form"]["message"].value;
if (e==null || e=="")
{
$('#messageError').fadeIn(250);
return false;
}
}//javascript form validation ends
//ajax submit and clear form on success
$(function () {
$('form').on('submit', function (e) {
var myForm = validateForm();
if (myForm == false){
e.preventDefault();//stop submission for safari if fields empty
}
else{
$.ajax({
type: 'post',
url: 'process.php',
data: $('form').serialize(),
success: function () {
$('#success').fadeIn(250);
if ($('#nameError, #emailError, #messageError').is(':visible')) {
$('#nameError, #emailError, #messageError').fadeOut(250);
}
$('form')[0].reset();//clear form after submit success
}//success ends
});//ajax ends
e.preventDefault();//prevent default page refresh
}//else ends
});//submit ends
});//function ends
//if reset button is clicked AND messages displayed, remove all form html messages
$(document).ready(function() {
$('#form input[type="reset"]').click(function() {
if ($('#success, #nameError, #emailError, #messageError').is(':visible')) {
$('#success, #nameError, #emailError, #messageError').fadeOut(250);
}
});
});
By giving your input id="reset" and/or name="reset", you effectively overwrote the form.reset method of the form because by doing so you made form.reset target the reset button. Simply give it a different id and name value.
Never give elements name or id attributes that equal the name of a property of a dom node.

ajax contact form Id, bugged

i have a contact form on http://daniloportal.com/NPC2/contact.html
Now this ajax script works very well, but i have other contact forms that i would like to use the same script for. so when i tried to create mulitple instances of the script, i noticed it stopped working because the ID name is not specifically ajax-contact-form. take a look at the code:
<form id="ajax-contact-form" action="">
<input type="text" name="name" value="Name *" title="Name *" />
<input type="text" name="email" value="Email " title="Email *" />
<input type="text" name="email" value="Email *" title="Email *" />
<textarea name="message" id="message" title="Message *">Message *</textarea>
<div class="clear"></div>
<input type="reset" class="btn btn_clear" value="Clear form" />
<input type="submit" class="btn btn_blue btn_send" value="Send message!" />
<div class="clear"></div>
</form>
and heres the JS
$("#ajax-contact-form").submit(function() {
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "contact_form/contact_process.php",
data: str,
success: function(msg) {
// Message Sent - Show the 'Thank You' message and hide the form
if(msg == 'OK') {
result = '<div class="notification_ok">Your message has been sent. Thank you!</div>';
$("#fields").hide();
} else {
result = msg;
}
$('#note').html(result);
}
});
return false;
});
Now if i were to switch that ID name on both and MATCH them, the script stops working- Theoretically it should work- not sure whats wrong with this.
as always any help is appreciated, thanks!
If you are trying to access two elements with the same id with jQuery - nothing gonna happen. Each element must have a unique identifier, otherwise you should use classes.
However, can you give us the markup of another form?

Submitting form into a div

Can anyone tell me why this is not working or give me another way into doing what I want.
I have a form on a page when click submit I want it to process into add.php and for it to open up in a DIV called right.
Form page
<script>
$("#Submit").click(function() {
var url = "add.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#myForm").serialize(), // serializes the form's elements.
success: function(html){ $("#right").html(html); }
});
return false; // avoid to execute the actual submit of the form.
});
</script>
</head>
<body>
<form action="add.php" method="post" enctype="multipart/form-data" id ="myForm">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name = "email"><br>
Phone: <input type="text" name = "phone"><br>
Photo: <input type="file" name="photo"><br>
<input type="submit" value="Upload">
</form>
</body>
Now if I add action to form to direct it to add.php all works fine so other script is ok yet when i do it this way,nothing happens it does not load add.php into the 'right' div like I want it to.
Anyone got any suggestions?
Your $("#Submit") selector does not match anything (the submit button has no id and is defined after that bind attempt), so the function is not bound to any event, thus never executed.
Instead the form acts the way it should: upon submit it posts its content to the url specified in the 'action' attribute. This is what happens, that div is never touched.
you have to go back to understand how jquery selectors work. How to bind a function to an event.
Is this your exact code? There are a few issues:
$("#Submit").click should be wrapped in a document ready
handler so it doesnt run before the page has actually loaded.
There is no button that matches #Submit
There is no div that matches #right
Try
<script type="text/javascript">
jQuery(document).ready(function($) {
$("#Submit").click(function() {
var url = "add.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#myForm").serialize(), // serializes the form's elements.
success: function(html){ $("#right").html(html); }
});
return false; // avoid to execute the actual submit of the form.
});
});
</script>
</head>
<body>
<div id="right">
</div>
<form action="add.php" method="post" enctype="multipart/form-data" id ="myForm">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name = "email"><br>
Phone: <input type="text" name = "phone"><br>
Photo: <input type="file" name="photo"><br>
<input type="submit" value="Upload" id="Submit">
</form>
you have to create on div in body tag which id will be right and
<input id="submit" type="submit" name="upload" >
add new div in body tag like this
<div id="right"></div>

how do I add an ajax response to my form without adding a new js file?

I have this simple submission form and I want to "ajaxify" it so the user isn't redirected to this page thanks.php after submission. I want the content from thanks.php to respond and show inside the div.
What jquery code will plug right into this to show the response.
<div ><form method="post" action="http://domain.com/thanks.php">
<input type="text" placeholder="Enter Email" name="email" id="email" >
<input type="submit" name="submit" value="Submit" ></form></div>
I would give 'form' and 'div' a class or id so it is not so generic, but this should work.
$("form").submit(function (){
$.ajax({
url: "http://{url}/thanks.php",
type: 'POST',
data: {email: $("#email").val()},
success: function ( data ) {
$("div").html(data);
}
});
return false;
});

Ajax .load() with php value from db

Basically i have a value from a database ($learner->idnumber)
I then have a form which posts using submithandler to process.php (this edits database)
Now this is the bit im stuck on, im trying to get the php db value $learner->idnumber to update without page refresh once the form has been processed.
I have found:
$("#pinnumber").load("profile.php #pinnumber");
but im not quite sure on how to implement this.
This is my code:
<a id="pinlink">edit</a>
<div id="results"><div>
<div id="pinnumber">
'.$learner->idnumber.'
<div>
<div id="pincontent" style="display:none;">
<form name="myform" id="myform" method="POST">
<input type="text" name="idnumber" id="idnumber" size="20" value=""/>
<input type="submit" name="submit" value="Update">
</form>
<div>
$(document).ready(function(){
$("#pinlink").click(function () {
$("#pincontent").show();
});
$("#myform").validate({
debug: false,
rules: {
idnumber: "required",
},
messages: {
idnumber: "Please enter your PIN",
},
submitHandler: function(form) {
$("#pincontent").hide();
// do other stuff for a valid form
$.post('process.php', $("#myform").serialize(), function(data) {
$('#results').html(data);
});
}
});
});
Any help would be greatly appreciated.
I included:
print "".$_POST['idnumber']."";
in process.php before the save to db code.
this then printed into:
<div id="results"><div>
when form was submitted.

Resources