save data to database with click of button/link - php

I am making a simple jQuery mobile app, where one of the pages is about a restaurant.
On that page, I want to have a button that, when clicked, saves the information of the restaurant to a database.
I already have a php code that can save data to my database, and i have this javascript code that works together with it.
Though this is used for saving data from a google maps infowindow when closed. I just need a on click button.
var url = "phpsqlinfo_addrow.php?name=" + name + "&address=" + address + "&description=" + description + "&lat=" + latlng.lat() + "&lng=" + latlng.lng();
downloadUrl(url, function (data, responseCode) {
if (responseCode == 200 && data.length <= 1) {
infowindow.close();
document.getElementById("message").innerHTML = "Location added.";
}
}
What is the easiest approach to this?
Thanks.
EDIT:
Is it possible to do like this, if i create a button with id #btn_save :
$(document).ready(function() {
$(document).on("click","#btn_save",function() {
"phpsqlinfo_addrow.php?name=" + john + "&address=" + lolstreet 12 +
"&description=" + this is restaurant john + "&lat=" + xx.xx() +
"&lng=" + yy.yy();
}); });
Sorry, i know i should be learning the basics first.. :/

If I understood correctly, you need to add button onClick event handler? If so, here you go (using jquery 1.9+):
$(document).ready(function() {
//onClick event handler for button with id "btn_save"
$(document).on("click","#btn_save",function() {
//Your code here
});
});

Related

issue trying to get a div and clone it via jquery

I'm pretty new to web programming so, making a logic for a web-page, I made a mistake and now I'm in trouble.
I named some divs like "Dv_1.2.1.3" (without knowing the problems linked to using the dot) and I have issues trying to clone (via jquery called by button) some of these.
The button id contains the id of the div I want to clone, so, my logic is:
1) extract the id of the div;
2) get the div and clone it (giving a new id).
I'm stuck with getting the div because of the dots in the id.
The below code is what I've done so far:
$('.CloneDiv').click(function () {
var SplittedId = (this.id).split('_');
if (SplittedId[0]=='Clone'){
alert('SplittedId 1 =' + SplittedId[1]);
//Modify id to use it to find the div to clone
var UsableId = SplittedId[1].replace(/\./g, '\\\\.');
alert('UsableId =' + UsableId);
//Count existing elements
var ClonedNum = $('#' + 'Dv_' + UsableId + '_').length;
ClonedNum++;
var OrigElem = $('#' + 'Dv_' + UsableId).length;
alert('OrigElem =' + OrigElem); //THIS IS 0
//NO ELEMENTS FOUND BUT THE ELEMENT EXISTS
//Clone the element and give new id
var ClonedElem = $('#' + 'Dv_' + UsableId).clone().attr('id', function( i, val ) {
return val + '_' + ClonedNum;
});
ClonedElem.find("input").val("");
if (ClonedNum > 1){
ClonedNum--;
var AnteId = '#' + 'Dv_' + UsableId + '_' + ClonedNum;
alert(AnteId);
$(AnteId).after(ClonedElem);
}else{
var AnteId = '#' + 'Dv_' + UsableId;
alert('AnteId = ' + AnteId);
$(AnteId).after(ClonedElem);
};
}else if(SplittedId[0]=='Del'){
alert(SplittedId[0]);
alert('Del');
}else{
//error
};
});
Might these help: developer.mozilla.org/en-US/docs/Web/API/CSS/escape , Polyfill: github.com/mathiasbynens/CSS.escape/blob/master/css.escape.j‌​s

A button when pressed from another page reloads the page being viewed by all visitors. Which languages are needed to be learnt for this?

I'm learning JavaScript but I want the following thing in my little (self-started) project as soon as possible.
Suppose the page of my website is www.mywebsite.com/myPage.html
Here is a scenario that 10 users are viewing myPage.html from my website. As I make any change to myPage.html from server (being admin), I want all viewers of myPage.html to see refreshed page with new changes taken effect just after I make any change in myPage.html. It should be very fast.
For this I think I'll have to create a button which will refresh the page myPage.html. As I'll make changes to myPage.html, I'll press that button and that button will reload every viewer's browser's page (myPage.html). And they will see the result of modified myPage.html in their browsers.
Kindly explain your answer properly, since I'm a beginner. Which Languages are needed for this?
i think the best option here would be some kind of push implementation / web sockets ... here are a few links to get you started in the right direction ...
Websockets : Using modern HTML5 technology for true server push
Push Notifications to the Browser With Server Sent Events
In the case of socket.io in client side(browser) subscribe every client with a particular channel and make the page reload with javascript when request from server via that channel is recieved. And in server you can broadcast message to that particular channel whenever you want to reload the page.
you can create an AJAX function that is executing in intervals(like every 10 seconds) and this function will connect to server to ask for any update from mysql, so if there's any updates! you notify the user.
so you should create a table in DB to be updated with page update info when you update a page.
AJAX(asynchronous javascript and xml ) is a technology connect to your server without having to use Forms to post, and you can refresh part of your page automatically.
now here is an example:
I wanted to create an online chat, so here is the code:
this code use ajax to post to ChatNotifyController.php to see if theres anyone online,if there's any it will notify the user.
//notify user if someone has or had send a message
setInterval(function(){
xmlhttp.open("POST" , "../controller/ChatNotifyController.php" , true);
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4)
{
if(xmlhttp.status == 200)
{
if((xmlhttp.response).length > 4)
{
var friendName = (xmlhttp.response).replace(/^\s*$[\n\r]{1,}/gm, '');
var responseArea = document.getElementById( friendName + 'ChatArea');
var x = friendName ;
if(x.indexOf('.') > 0)
{
x = x.replace('.', '\\.');
}
var link = $('#' + x);
var input = $('#' + x + 'ChatInput');
var e = jQuery.Event("keydown");
e.which = 13;
if(link.length > 0)
{
link.click();
input.trigger(e);
}
else
{
var html = "<li><a class=\"onlineUserLink\" id=\"" + friendName + "\" onclick=\"chat(" + "'" + friendName + "'" + ")\" >" + friendName + "</a></li>";
html += "<div class=\"chatDialog\" title=\"'" + friendName + "\"' id=\"'" + friendName + 'ChatDialog' + "'\">";
html += "<div class=\"chatArea\"" + " id=\"'" + friendName + "ChatArea" + "'\">" + "</div>";
html += "<input class=\"chatInput\"" + " id=\"'" + friendName + 'ChatInput' + "'\" size=\"21\" onkeydown=\"chatController(event , '" + friendName + "' , '" + window.user + "')>" + "</div>";
window.onlineArea.innerHTML += html;
var THIS = $('#' + x + 'ChatDialog');
$(function() {
THIS.dialog({
stack: false
});
});
link.click();
input.trigger(e);
}
}
}
else
{
//alert("Error during AJAX call. Please try again #003");
}
}
};
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("user=" + window.user);
} ,5000);

Process dynamically created web form with JQuery and PHP

I've been wrestling with a problem that I just cannot seem to solve. I've got a web form that is built from a MySQL query that's run from PHP and returned to JQuery that displays a gallery of movies that the user can give a numeric rating. I'm wanting to send the form back to PHP for processing and writing to the database.
function loadGallery()
{
$('content').append('<form id="movieRatings" action="../php/saveRatings.php" method="post">).html();
$.get('../php/getMovies.php')
.done(function(data) {
var query = $.parseJSON(data);
for (var i = 0, len = query.length; i < len; i++) {
var galleryMovies = '<div class="movContainer">' +
'<div class="movie">' +
'<a title="' + query[i].mov_title + '" href="../' + query[i].mov_title + '.html">' +
'<h3>' + query[i].mov_title + '</h3>' +
'<img src="../imgs/' + query[i].poster_path + '" /></a>' +
'<input type="number" name="' + query[i].mov_title + '" >' +
'</div>' +
'</div>';
$('#content').append(galleryMovies).html();
}
$('#content').append('<input type="submit" value="Submit"></form>');
})
.fail(function() {
$('#content').html("Epic Fail!") ;
});
}
The form displays without any issues, but clicking the submit button doesn't even send the request for the "saveRatings" PHP file. I'm sure I'm missing something simple, I just can't seem to figure out what that is. My first thought was that it was because the gallery isn't part of the actual html, but from what I've read that shouldn't have anything to do with it.
And pointers/sugestions/insight would be appreciated.
instead of
$('#ID').click(function(){
// do something here
});
switch to
$(document).on("click", "#ID", function(){
// do smth here
});
Your first assumption was true, if the element is not part of the initial html, then any events bound to it won't work unless you go with my second approach. You can find more about this behavior in the jquery documentation.
L.E: same goes for the submit action, in case i was not clear with the click example:
$(document).on("submit", 'form#formID',function(){
// do smth here...
});

Replaced Inefficient Javascript with JQuery with language errors

In the process of trying to be more efficient I have been learning a bit of JQuery, but obviously don't know enough.
I need a script that will get each checked function $(':checked').each(function() . Then if a hidden field id (combined with this fields alt tag's) title is not equal to this check boxes title to perform jquery load.
I could go on with trying to explain this but I would rather show what I mean. If you look at the code below the 2 elements which cannot exist are :alt and :title. If you can see what I'm trying to do then any ideas how I would get it working. Data driven site has left me few alternatives.
function product_analysis_global() {
$(':checked').each(function () {
if ($('#product_quantity_PRI_' + ':alt').title != ':title') {
$('#product_' + ':alt').load(':title');
$('#product_quantity_PRI_' + ':alt').title = ':title';
$('#product_quantity_PRI_' + ':alt').value = ':value';
} else if ($('#product_quantity_PRI_' + ':alt').title != 'http://www.divethegap.com/update/blank2.html') {
$('#product_' + ':alt').load('http://www.divethegap.com/update/blank2.html');
$('#product_quantity_PRI_' + ':alt').title = 'http://www.divethegap.com/update/blank2.html';
} else
return false;
});
}
Many Thanks,
ps. Implementation can be seen here where by the radio buttons and checkboxes should load in the appropriate products. You will need to click on Beginners to load the form.
http://www.divethegap.com/update/diving-trips/adventure-training
In the future, please format your code so others can easily read it when asking for help.
Your description isn't exactly clear, and the page you linked to has no radio buttons or checkboxes, but I believe you are looking for:
function product_analysis_global() {
$(':checked').each(function() {
var alt = $(this).attr('alt');
var title = $(this).attr('title');
if ($('#product_quantity_PRI_' + alt).attr('title') != title) {
$('#product_' + alt).load(title);
$('#product_quantity_PRI_' + alt).attr('title', title);
$('#product_quantity_PRI_' + alt).val($(this).val());
} else if ($('#product_quantity_PRI_' + alt).attr('title') != 'http://www.divethegap.com/update/blank2.html') {
$('#product_' + alt).load('http://www.divethegap.com/update/blank2.html');
$('#product_quantity_PRI_' + alt).attr('title', 'http://www.divethegap.com/update/blank2.html');
} else return false ;
});
}
I am a bit lost. On your example page I see no instances of checkboxes or radio buttons? :checked can only be used with these elements. Perhaps you can do a jsfiddle and give a better understanding of what you are trying to achieve?

jQuery not generating correct queryString

I have been working on a website that uses a combination of PHP, jQuery, MySQL and XHTML in order to register students for a piano recital. This has no official purpose other than a learning exercise for me in getting all of these to work together. However, I have had a lot of problems getting the PHP to talk with the database and I'm not sure what my problem is. But before that can be tackled there is a really annoying issue that I've run across. For some reason my jQuery is not building a complete post URL for the PHP.
I am using jQuery version: 1.4.2 from Google. The query string is being built by using:
var ajaxOpts = {
type: "post",
url: "../php/addRecital.php",
data: "&performance=" + $("#performanceType :selected").text() +
"&groupName=" + $("#groupName").val() +
"&student1fName=" + $("#firstName").val() +
"&student1lname=" + $("#lastName").val() +
"&student1id=" + $("#studentID").val() +
"&student2fname=" + $("#Second_Student_firstName").val() +
"&student2lname=" + $("#Second_Student_lastName").val() +
"&student2id=" + $("#Second_Student_studentID").val() +
"&skillSelect=" + $("#skillSelect :selected").text() +
"&instrument1=" + $("#instument1 :selected").text() +
"&otherInstrument1=" + $("#otherInstrument1").val() +
"&instrument2=" + $("#Instument2 :selected").text() +
"&otherInstrument2=" + $("#otherInstrument2").val() +
"&location=" + $("#locationSelect :selected").text() +
"&roomNumber=" + $("#roomNumber").val() +
"&time=" + $("#timeSlotSelect :selected").text()
,
success: function(data) { ...
There is more than the above function, but I didn't think that it would pertain to here. I then call the code using:
$.ajax(ajaxOpts);
However, instead of creating the entire query string I get:
http://sterrcs123.mezoka.com/schoolProject/assign/assign13.html?groupName=&firstName=Samuel&lastName=Terrazas&studentID=23-343-3434&Second_Student_firstName=&Second_Student_lastName=&Second_Student_studentID=&otherInstrument=&Second_Student_Instrument=&roomNumber=2
Which as you can tell is missing a number of keys and their values. I would appreciate any help I can get because this is really driving me insane. Thanks.
It appears that your form is simply submitting itself without using your AJAX operation. Did you attach to the form's submit event and THEN run your ajax call? You will also want to return false from the submit event handler to prevent the default behavior you are seeing above.
Example:
$('#formid').submit(function(){
//your ajax code here.
return false;
});
If you're talking to an ASP.Net web service then you would need data to be a JSON string of your arguments. Otherwise, you can pass your data in by using an object literal (truncated for brevity):
var ajaxOpts = {
type: "post",
url: "../php/addRecital.php",
data: {
performance: $("#performanceType :selected").text(),
groupName: $("#groupName").val(),
student1fName: $("#firstName").val(),
student1lname: $("#lastName").val()
},
success: function(data)
}
As per the missing values, make sure you're capturing the button click / form submit.
$('form').submit(function (e) {
$.ajax(ajaxOpts);
return false;
});

Categories