Adding divs on the fly with jQuery and submit them through AJAX - php

I'm having some blocking issues with something I'm developing.
The idea is to have customers who may have more than one address. So, when you see the customer "profile" you have a Select box which have all his/her addresses tagged so you only see the one which is selected.
They are really there but hidden with some javascript/jquery.
So, the problem comes when adding new address. I don't know how could I add more dinamically. What I do is to have a hidden div which is empty so, when you press the Add address button it shows the div and let you fill the form however I don't know how to add more than one and then save them.
The issue is with usability and with programming. The usability part is that you may have visible the div with the Address you are about to add but what happens with that div if you try to add a new one? Should be hidden? If so, there should be a way to get them back just in case you need to change some data or if you don't hide them, you may end with a really big scroll bar.
And then, there is the way I save the info for each address div, I'll paste my code here:
$('.form-direcciones').each(function(){
var ajData = $(this).serialize();
var idDireccion = $(this).attr('id');
if (idDireccion === 'form-nueva-direccion'){
ajData = ajData + '&action=insertar'+
'&cod_cliente='+cod_cliente;
}
else{
idDireccion = idDireccion.split('-');
ajData = ajData + '&cod_dir='+idDireccion[2] +
'&action=' + action +
'&cod_cliente=' + cod_cliente;
}
$.ajax({
type: "POST",
url: "controllers/direccion.php",
async: false,
data: ajData,
dataType: "html",
cache: false
});
});
As you may see, it checks if the ID of the div is the one I use for that but even with that solutions it seems a little bit dirty to me.
Also, it comes the problem where I'm having repeated IDs...

Just take a look at this jsfiddle
http://jsfiddle.net/Z3JPW/12/
I have done the basics to give you an idea on how to do stuff client side. You can do everything such as editing and deleting and inserting all at client side and finally take the data to the server side persistence.

Related

Jquery/Php post without redirect

I am making a website that displays a list of hotels. I want to add a "favorite" button so that it stores that hotel with the user. From my understanding I need to use php/jquery based on some answers I saw on stackoverflow.
I have no experience with php/jquery. Absolutely none writing it or even adding some to my web page (this is the first website/web application I am trying to build.
After looking at a couple of stackoverflow answers on this topic I have checked out this website: http://code.tutsplus.com/tutorials/submit-a-form-without-page-refresh-using-jquery--net-59
and attempted to click on the recommended link for newbies: 15 Resources to get you Started with jQuery From Scratch.
but to no avail as the page is not found.
This is the html where I want to add the favorite button stored in "Bookmark for later". However, I know hypothetically even if my click worked I am not capturing the data of the specific hotel for which they clicked bookmark for later.
{% for hotel in close_hotels %}
<div id = "display_hotel">
<p><font color="blue" size="2"><b> {{ hotel.name }} </font></b></p>
<div id = "hotel_format">
<div id = "favorite_form">
<input id="bookmark" type="button" value="Bookmark for later!"
onclick= "function()"/>
</div>
This is my .js file. I tried following http://code.tutsplus.com/tutorials/submit-a-form-without-page-refresh-using-jquery--net-59 as best as I could, but recognized some differences. For example I am trying to capture information from a button(should I change this) instead of a form.
I didn't bother with the form validation since it is just a button.
$(function() }
//using a button to add hotel to favorites
$(".button").click(function() {
var hotel = $("input#bookmark").val();
//skipping form validation since no need -- using a button
});
});
//next part of the tutorial
$.ajax({
type: "POST",
url: "bin/process.php",
data: hotel,
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Hotel Favorited!</h2>")
.hide()
});
}
});
return false;
Ultimately there are two things I am wondering. Is a button most appropriate for what I am seeking? If not, what else should I use, but if so how can I capture the hotel information with the PHP. Second of all as I am not familiar with php/jquery will the code work?
From my understanding this line should be able to capture the hotel name I want, but again I don't even think my button would even send the information.
var hotel = $("input#bookmark").val();
Thanks for the help!
There are two main ways to submit information to the server (your PHP code):
Using an HTML <form>
AJAX
I'm guessing you want to do it via AJAX since you're not sending typical form data. For that you would do something like this in jQuery:
var req = $.ajax({
type: "POST",
url: "http://whatever.com/stuff",
data: { "some_key": "some_value" }
});
req.done(function (response) {
// code to run after the server handles your data and responds
});
req.fail(function(jq_xhr, text_status, error_thrown) {
// if you want to handle errors ...
});

Cross checking with database before rendering page

I am trying to cross check some values with what I have in the database before letting those data go any further.
I have a form and in this form I am post
pid, Name, size, category and qty.
I have a validation already for the qty.
In those data I am posting I am using those to find the price in the database. I AM NOT POSTING THE PRICE.
Because I am using those post data to find the price someone might want to mess about with them for an example change the category or size value to whatever. If they do this, it will still get posted and the page will render and it will look like
Name: qty: unit price: total item price:
size:
Although those table name shows NOTHING is getting shown which means the page is just rendering for nothing.
I know some of you might think "if the person whats to mess about with the values, that is their fault" and I totally agree but I still want to stop the page from rendering
if everything posted doesn't relate to any of the item with that product ID (Pid).
How can I use ajax to validate them before rendering it in the other page?
I already Have an ajax which looks like
$(document).ready(function(){
$('#selected').hide();
$('#button').click(function(){
var pid = $('#pid').val();
var size = $('#size').val();
var qty = $('#Qty').val();
var price = '\u00A3' + parseInt($('#pricetag').text().replace(/^\D/, ''), 10) * qty;
if (!/^[1-9]\d?$/.test(Qty)){
alert('Quantity should not be below 1 or null');
return false; // don't continue
}
else {
$('#sprice').text(price);
$('#ssize').text(size);
$('#selected').slideDown();
}
$.ajax({
url: 'cart.php',
type: 'POST',
data: { pid:pid,
size:size,
Qty:Qty,
Category:Category },
success: function(data)
{
}
});
});
});
in cart.php
is where I am posting those values to.
How can I do this please?
You want to ask the server to see if the data is valid. Aside from the form data, I would also post a flag telling PHP that this is the AJAX validation so it can tell the AJAX post from normal form submission.
In PHP, after the data validity is determined, it can just return true or false. Then your Javascript can determine what to do from that point on.
However, I think there are other ways to go about this. Maybe you shouldn't let the user modify these fields, or maybe you can post the form, and render the form again if the user has submitted invalid data. Another alternative is to limit the choices that the user can do, so their input is always valid.

POST to PHP page on div change

The below is my code. Div id jp_current_track_title changes automatically when other events occur. I am trying to capture whats gets into the div "Track_title and post it onchange to like.php. as of now i cant figure it out. Im getting something back into the result div but its not posting. What am i doing wrong?
$(document).ready(function() {
$('#track_title').change(function() {
var content = $('#track_title').html();
$.ajax({
url: 'like.php',
type: 'POST',
success: function(info){ $("#result").html(info)
},
data: {
content: content,
}
});
});
});
Instead of detecting changes in jp_current_track_title, can you capture the other events that caused the update to jp_current_track_title? If so, can you get the updated title from there?
You aren't going to get 'change' events when the contents of a div change, it doesn't work like that.
See here:
Fire jQuery event on div change
The main answer mentions how you can track DOMNodeInserted / DOMNodeRemoved / DOMSubtreeModified events, however those don't work in IE.
Your best bet is to use setTimeout() and check the innerHTML of the div on regular intervals to see if the value has changed.

how to refresh the data being loaded on the form after showing it off?

I have a a div, wherein, it displays the data, and beside it, is an edit button..if one clicks the edit button, it hides the div and shows a different div with input forms which allows the user to update the data..the problem now is, when the user submits the form, my script updates the data and hides this input forms and shows again the former div of data display, the data shown is not updated....my question now is,, how to show the updated data after the script show() it again ?
here's my jquery ajax code
$(function(){
$('#profileinfoedit').click(function(){
$('#profileinfomain').hide();
$('#profileinfoajax').show();
$('form#pdetails').submit(function(){
var cvid = $('#cvid').val();
var resumetitle = $('#resumetitle').val();
var name = $('#name').val();
var dob = $('#dob').val();
var gender = $('input[name=gender]:checked').val();
$.ajax({
type: "POST",
url: 'classes/ajax.personalupdate.php',
data: $("form#pdetails").serialize(),
success: function(data){
alert(data);
$('#profileinfoajax').hide();
$('#profileinfomain').show();
}
});
return false;
});
});
});
$('#datepicker').datepicker();
So location.reload is just refreshing the page, which as you have discovered is a quick and dirty fix.
If you want to do it without a page refresh, you would have to regenerate the html for just the 'profileinfomain' element from data received back from ajax.personalupdate.php. I would assume you would only want to do this on "success".
One approach would be to have the success data contain the html needed to regenerate the 'profileinfomain' element html. So perhaps have php return back data.profileinfomain_html, and then:
$('#profileinfomain').html(data.profileinfomain_html);
which will replace the inner content of the profileinfomain element.
If you are working in a framework of some sort, have the profileinfomain inner html content be a partial template included in so you only have to maintain its html in one place.
was able to sort it out via
$('#profileinfomain').show('normal',function(){
location.reload();
});
but, isn't there any better way to do this?

how can I get just a single div to refresh on submit as apposed to the entire page?

I am working with a dynamically generated page written in PHP. The divon the page contain contents listed FancyBox links that open editing screens.
Once editing is complete and the user closes the FancyBox modal the changes
need to be reflected on the parent page.
Right, so I was able to find a solution that refreshes the entire page on submit
using
parent.location.reload (true);
to refresh the entire parent page. But, that causes a browser prompt
that is confusing to users and a bit of over kill as I really only
need the information edited to refresh.
how can I get just a single div to refresh on submit as
apposed to the entire page??????
You need to submit the form through AJAX. Since your using something that uses jQuery, you can use it to do it.
Here you can find a tutorial on how to do it
I think the best way is loading page fragments with .load().
something like,
$('#pageNeedToBeRefreshed').load('test.html #pageNeedToBeRefreshed');
User ,
It should be pretty easy
have a div place holder like below
<div id="dataToRefresh"> </div>
Once you close the dialog, have a event handler...
$('dataToRefresh').html('testing'); // give your data here
it should upate the parts of the page
let me know if you need anything else
please go thruogh .html api for more info
http://api.jquery.com/html/
Suppose you have the below div to refresh:
Then write
$("#dataToRefresh").load();
Might it will be helping you
Instead of using submit in html you can submit your form using the ajax -
$('#formid').submit(function(){
var data = $(this).serialize(); //this gives you the data of all elements of form in serialized format
$.ajax({
type: 'POST',
dataType:"json",
url: 'your url',
data: data,
success: function(data){
//replace the contents of the div you want to refresh here.
}
});
});
jQuery('#id_of_div').load('/url/to/updated/html');
See jQuery docs for load()

Categories