Jquery submit radio button without reload and - php

So because my experience with jquery is zero i have no idea how to run my mysql script when the form is submitted without reloading a page?
in short
form radio button submit --> form sended --> query without reload
My script:
<form id="myForm" method="get">
<div class="row">
<div class="span4 info1">
<section class="widget">
<img src="../bootstrap/img/thumb/0.jpg" width="auto" height="auto">
<?php if ($selectedBg == '0') {
echo '<h2>Current one</h2>';
} ?>
<input type="radio" name="options[]" value="0" onclick="document.getElementById('myForm').submit();"/>
Choose Background
</section>
</div>
</div>
<?php
$checked = $_GET['options'];
for ($i = 0; $i < count($checked); $i++) {
$sql = 'UPDATE blog_users SET background = '.$checked[$i].' WHERE username=?';
$bg = $db->prepare($sql);
$bg->execute(array($session->username));
}
?>
</form>
So my question is how do I submit my form without reloading the page + running my query?

you will need to create a separate page that accepts the form data, and use jQuery's ajax functions to asynchronously submit the data.
Here is some pseudocode to show how you would accomplish this:
$('form').on('click', 'input:radio', function() {
$.get('NEW_PAGE_URL' + $(this).serialize(), function(data) {
// this function is the success function.
// your page should return some kind of information to let this function
// know that the submission was successful on the server side as well.
// This was you can manipulate the DOM to let the user know the submission
// was successful.
});
});

What you are describing is a technique that is called AJAX. It is a technique that is not specific to jQuery, php, or mysql. With that said, it is a common task for JQuery to help assist with.
You may want to check this post out: https://stackoverflow.com/a/5004276/1397590
Or if you're looking for more of a tutorial, then take a peak here: http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
Either way, there's lots of resources out there to get started learning about AJAX.

Related

JQuery-AJAX post workflow

EDIT
Forgot a couple of improtant points.
I am doing this to eliminate the page from having to refresh and therefore jumping back up to the top of the page.
The success function of the ajax function will kick back an entire new div id="comments" to replace the existing one with either an error msg or the new comment with all other below it.
END EDIT
I have been trying to this jquery-ajax function under wraps unsuccessfully. I have X number of posts on a page with each having a form for inserting comments under each post. I think I am pretty close and have tried to debug it using firebug, but honestly I don't really know what I am looking at or for in firebug.
All code is below, any help would be much appreciated!
HTML form and structure (because of the repetative forms, I feel I should use the parent jquery selection method, rather than iterating each post-comment partition in my output script)
<div id="content_body_right">
<div id="activity">
....this is the area for each post....
</div>
<div id="comments">
<p class="comments_label">' . $reply_count . ' Comment</p>
<div id="comment1">
<div id="comment_user_img">
' . $imgOutputReply . '
</div>
<div id="comment_user">
<p class="user_text_comment">' . $firstNameReply . ' ' . $lastNameReply . '</p><p class="date_text_comment">' . $date_timeReply . '</p>
<p class="message_text_comment">' . $messageReply . '</p>
</div>
</div>
<div id="add_comment">
<form id="formAddComment" action="dashboard.php" enctype="multipart/form-data" method="post">
<div id="add_comment_left">
<textarea id="comment" name="comment" cols="75" rows="2">Add a Comment...</textarea>
</div>
<div id="add_comment_right">
<input id="userID" name="userID" type="hidden" value="' . $userID . '" />
<input id="actID" name="actID" type="hidden" value="' . $actID . '" />
<input id="btnComment" name="btnComment" type="submit" value="" title="Add Comment" />
</div>
</form>
</div>
</div>
</div>
OK, now the JQuery markup
<script type="text/javascript">
$(document).ready(function(){
$("#formAddComment").submit( function(e) {
e.preventDefault();
var form = $(this);
var div_add_comment = form.parent();
var div_comments = div_add_comment.parent();
$.ajax({
type: "POST",
data: form.serialize(),
url: "includes/comment.php",
success: function(msg){
$div_comments.html(msg);
}
});
return false;
});
});
</script>
Lastly the external php script (NOTE: I will only post the initial lines where i localize the data feed into php vars.)
if(isset($_POST['actID'])){
$actID = mysql_real_escape_string($_POST['actID']);
$userID = mysql_real_escape_string($_POST['userID']);
$comment = mysql_real_escape_string($_POST['comment']);
............other processing here...........
}
I am suspicious of my jquery script mostly.
Thanks again,
I dropped the general structure into a jsfiddle at http://jsfiddle.net/cori/JsLWq/, and when I submit the form I do indeed get an ajax POST to the non-existant http://fiddle.jshell.net/cori/JsLWq/show/includes/comment.php due to the relative ajax url, so that's not the problem as far as I can tell. What I do think is the problem is that you're mixing your variable naming rules.
You start off naming your variables like plain-old javascript objects
var form = $(this);
var div_add_comment = form.parent();
var div_comments = div_add_comment.parent();
but then in your success handler you switch to the fairly-common $x convention, often used to indicate that a variable is a jQuery instance:
$div_comments.html(msg);
however at that point there is no variable $div_comments; only div_comments. If you submit the form in http://jsfiddle.net/cori/JsLWq/1/, which has an ajax error handler, and look at your firebug console, you'll see that you get a ReferenceError because $div_comments is undefined.
EDIT
Incorporating kgarrigan's suggestions, if in your php you loop over the forms you want to create, and keep track of your position using an index, you could rename your forms with the index, so your form php/html code would look something like:
<form id="formAddComment-' . $index . '" action="dashboard.php" enctype="multipart/form-data" method="post">
so you would end up with form elements with ids like formAddComment-1.
Then in your jquery you would select all the forms using the startsWith selector and bind the submit event to them, thusly:
$('[id^="formAddComment"]').submit( function(e) {
// do your ajax
});
That way each form will have it's own submit handler.
jquery works with selectors. When you write $(something) something is the selector. It can be an id, a class name, a variable, html elements. So instead of
$("#formAddComment").submit( function(e) {
You could use
$(".someclassName").submit( function(e) {
just like css, use # for id, . for class. Just make sure you add the class attribute to your form with the same name. You could also try
$("form").submit(function(e) {
which should select any form elements. I think the rest of your function should work fine with this change, since you are using 'this' and parent() instead of any direct references.
In firebug, click on console, then on all. When you click on the button to trigger your ajax call you should see a line pop up, probably with a loading icon that shows a post request being sent. You should be able to click on the tabs to see what data is being posted and what response is given as well as a response status code...
In your edit, you say the success function will send out a new div id="comments" to replace the existing one, but as you have it written now, I believe it will just add a div id="comments" inside the existing one. Don't know if this would cause your problem though.
If you have multiple forms on the same page, with the same id's this will cause the problem. Especially the # formAddComment id, which is attached to the submit () call. If there are multiple of these ids, this won't work

How do I refer to a php variable in jQuery?

I'm a complete beginner with jQuery and I have this bit of script here and I want to mix jQuery with PHP. I have Courses and in those Courses are Lessons. A Teacher is assigned to teach a Course. What I want is a link where if I press it a popup appears and in it shows the Lesson details or Course details. My problem is that I will be having multiple links and thus dialogs/modal windows in a page such that $l['id'] and $c['id'] will be different. How can I therefore use $l['id'] and $c['id'] in or with jQuery given that the jQuery script is inside the view file and I'm creating the actual content itself in the controller and passing it onto view. Sorry if I don't make sense cause I'm still quite confused about all this myself.
view.php
<script type="text/javascript">
$(function(){
// setup ul.tabs to work as tabs for each div directly under div.panes
$("#tabs").tabs();
$('#dialog').dialog({
modal: true
});
})
</script>
<h1>Student Hub: Courses for <?php echo $studentName;?></h1>
<div id="tabs">
<?php echo $content;?>
</div>
controller.php
This is in a foreach loop
<div class="lessonDetails">
<p>Lesson Details:<p>
<div id="lessonDialog'.$l['id'].'" title="Lesson Details">
'.$l['name'].'
</div>
</div>
<div class="courseDetails">
<p>Course Timetable & Resources<p>
<div id="courseDialog'.$c['id'].'" title="Course Details">
<p>'.$c['fullname'].'</p>
<p>'.$c['summary'].'</p>
<p>Upcoming Lessons: </p>
</div>
Technical answer is you don't as one is a server-side language and one is a client-side language; you can't access PHP variables via JavaScript (jQuery). You can, however, drop your PHP variables into your HTML page on generation, and then pick them up with JavaScript or jQuery.
Reading your scenario, I think your over-complicating things. Think of your application; don't think of the technical aspects, but more the way it should be laid out. I'm guessing you have a students controller, a lessons controller, and a courses controller. Those controllers will have actions, called view or similar, and then these actions will take an ID to display a particular student/course/lesson.
In your HTML page/view/template, you should have just vanilla URLs. JavaScript should then be used to enhance the website. So in your case, I would have mark-up it up similar to as follows:
<ul class="courses">
<?php foreach ($courses as $course): ?>
<li><?php echo $course->title; ?></li>
<?php endforeach; ?>
</ul>
I'd then, in an external JavaScript file, have a function that listens for a click on the <a> tag and instead of navigating to that URL, instead displays the page content in a pop-up/modal window.
<script>
$('.courses a').click(function(e) {
e.preventDefault();
// load external page and display it in a modal
});
</script>
This way, if for some reason JavaScript's not available then the user will be taken to the course details page. If they do have JavaScript, then they'll get a fancy modal pop-up.
Hope this helps. If you need anything clearing up then let me know, as I have wrote this in the early hours after a few JD and Cokes!
you can create in every link some extra attributes and using jQuery retrieve the information with the attr function $('a').attr('courses').
somethig like
<a href="#" class=".information" teacher="idTeacher" course="idCourse" >list </a>
then using jquery
$('.information').click(function(){
teacher= $(this).attr('teacher');
course=$(this).attr('course');
});
remember to use $('.information').live() if you are using some AJAX to get the data from the server and the parse it to create the links
You can place tags within your JavaScript code. Since that code is server side, it will "render" to your JavaScript client side code. So your JavaScript can access values stored by your PHP script.
Here's a solution using jQueryUI dialog. No ID's are required however should they be needed add them as a data attribute to that links
<p><a href="#courseInfo'.$c['id'].'" data-id="'.$c['id'].'" >Course Timetable & Resources</a><p>
This allows easily getting ID with jQuery data() method.
Dialog is created and destroyed each use. As noted in comments, no idea what content goes in dialog. I can easily adjust if it is ajax from href
$('.lessonDetails a, .courseDetails a').click(function(){
var $this=$(this);
/* if need the id associated to link*/
var id=$this.data('id');
var content= ''/* ??????? */
var title=$this.parent().next().attr('title')
loadDialog(title, content);
return false; /* stop browser following href*/
})
function loadDialog(title, content) {
var dialogOpts = {
modal: true,
title: title,
width: 800,
close: function() {
/* remove this dialog from DOM on close*/
$(this).remove()
}
};
$('<div>').append(content).dialog(dialogOpts);
}
Maybe you can create forms that have hidden values in it.
<?php foreach($lesson as $l): ?>
<form method="POST" action="">
<input type="hidden" name="lesson_id" value="<?php echo $l['id']; ?>" />
Click
</form>
<?php endforeach; ?>
javascript:
$(document).ready(function() {
$('.modal_window').click(function() {
var form = $(this).closest('form');
var lesson_id = $(form).find('input[name=lesson_id]').val();
// Do something with lesson_id
});
});
The idea is the same for courses.
****** Edit ********
Maybe you can try using input arrays. Assumming you have something like this
<input type="hidden" name="courses[]" value="1" />
<input type="hidden" name="courses[]" value="2" />
javascript:
var courses = $(form).find('input[name^=courses]');
$(courses).each(function() {
var course = $(this).val();
});

how to call a php function on button click

These are two files
Calling.php
<html>
<body>
<form action="Called.php" method="get">
<input type="button" name="B1" value="B1">
<input type="button" name="B2" value="B2">
<input type="Submit" name="Submit1"/>
<!-- Google
yahoo
-->
</form>
</body>
</html>
And Called.php
<?php
if(isset($_GET("Submit1")))
{
echo("<script>location.href = 'http://stackoverflow.com';</script>");
}
if(isset($_GET["B1"]))
{
echo("<script>location.href = 'http://google.com/';</script>");
exit();
}
if(isset($_GET["B2"]))
- List item
{
echo "<meta http-equiv='refresh' content='0;url=http://www.yahoo.com'>";
exit();
}
?>
When i click the buttons "B1" and "B2", page will blink but now where redirect and third one "Submit" button will redirect to new page and there i am getting the out put as "Called.php".
Please spend few seconds for this php beginner.
You can't directly because the button click is a client side activity and PHP is server side. If you make all the inputs submit then the one the user clicked will be submitted as part of the $_GET array but that only works if the user clicks one of them and doesn't submit the form by, say, hitting Enter in a text input.
You could attach AJAX events to the button and have them trigger off a PHP script to run the function you want to run, but that has its own set of issues.
EDIT: I should note that your method of redirecting is rather inelegant to say the least. You can just use header() to do the redirection, it would be much cleaner than all this messing around with echoing out javascript.
You need to use Ajax to do this. If you are using jQuery ajax the code will look something like this
$(function(){
$('input[type="button"]').click(function(){
var name = $(this).attr('value');
$.ajax({
type :'GET',
url : 'Calling.php',
data :{name:name}
success : function(data) {
//do smthng
}
})
})
})
//Code is not tested. Need to verify.

Combing JS and PHP on one button. Is it possible?

Hiya:
i know some people would be so tired of my questions, but I'm working on a uni project and need to get it done as soon as possible. This question is about using JS on a button(button) and sending a php_my_sql update on the same button. The problem is JS uses button, right? but PHP uses button(submit). How can I get these two to work on one of these buttons, cuz there has to be only one button.
this is my code for JS
<script type="text/javascript">
function formAction(){
var x=document.getElementById("collect")
x.remove(x.selectedIndex)
}
</script>
HTML
<form method="post">
<select id="collect" name="Select1" style="width: 193px">
<option>guns</option>
<option>knife</option>
</select> <input type="**submit/button**" onclick="formAction()" name="Collect" value="Collect" /></form>
PHP
<?
if (isset($_POST['Collect'])) {
mysql_query("UPDATE Player SET score = score+10
WHERE name = 'Rob Jackson' AND rank = 'Lieutenant'");
}
?>
This can be a way
Submit the form through JS after removing parameter
<script type="text/javascript">
function formAction(){
var x=document.getElementById("collect")
x.remove(x.selectedIndex);
document.forms[0].submit();
}
</script>
Input type button
<input type="button" onclick="formAction()" name="Collect" value="Collect" />
Embed jQuery and use $.post() to send an AJAX request.
JavaScript can interact with the button whilst the user is navigating the page and entering data into the form. The instant the user pushes the submit button and the request for the form submission is sent JS no longer has control. The request is sent to the form's action (most likely a PHP file) which processes the request and gives an answer back.
If you really need to combine the two, look into AJAX.
<?php print_r($_POST); ?>
<script type="text/javascript">
function formAction(){
var x=document.getElementById("collect");
x.remove(x.selectedIndex);
submit_form();
}
function submit_form() {
document.form1.submit();
}
</script>
<form method="post" name='form1'>
<input type='hidden' name='Collect'/>
<select id="collect" name="Select1" style="width: 193px">
<option>guns</option>
<option>knife</option>
</select> <input type="button" onclick="formAction()" name="Collect" value="Collect" /></form>
<?
if (isset($_POST['Collect'])) {
//do whatever update you want
}
?>
Simple Solution
Make this modification in the form tag
<form method="post" onsubmit="return formAction()">
In JavaScript function add a line "return true;" at the end of the function.
Voila ..!!! you are done..!!
Enjoy..!!

Linking page in a div with html forms and php

So I have this html code
<div id="wrap">
<div id="header">
</div>
<div id="content">
<form method="POST" action="code.php">
Name:
<input type="text" name="name" size="50">
<input type=submit value="Get Code">
</form>
</div>
<div id="footer">
</div>
Is it possible to load the code.php after the user clicks submit into the #content div?
Essentially, what I want is when the user clicks the submit button, the code.php after processing is loaded onto the same #content div.
So let say in my code.php, after processing the inputted data, I come up with this lilne of code,
<?php
some processing code here;
$name = 'john';
echo $name;
?>
So then after hitting submit, user would see
<div id="content">
john
</div>
Hope I didn't complicate my question by repeating myself, please let me know if this is possible with javascript, php or whatever.
Thanks for the read!
#JohnP yes, $.load is a good solution. However, you'll need to send the form data in the request:
UPDATED [3] for sending a POST with multiple fields and checkboxes:
$('form').submit(function(){
// create an object to send as a post
var form = this,
fields = form.elements,
el,
post = {};
for (var i = fields.length; i--; ) {
el = fields[i];
if (el.name) {
switch (el.type) {
case 'checkbox':
case 'radio':
post[el.name] = (el.checked) ? el.value : '';
break;
default:
post[el.name] = el.value;
}
}
}
// send the form data in the load request...
$('#content').load(this.action, post);
return false;
});
This will send the data as a POST.
Since you've tagged jQuery, I'll use a jQuery example
$(document).ready(function(){
$('form').submit(function(){
$('#content').load('code.php');
return false;
})
})
This makes a couple of assumptions here
This assumes that code.php is in the same path that you are in now.
There is only one form in the page.
As #johnhunter points out, this example obviously won't work with post. You can send the post data along with the method. See here for usage : http://api.jquery.com/load
EDIT
Here's a fiddle example : http://jsfiddle.net/jomanlk/J4Txg/
It replaces the form area with the content from jsfiddle/net/echo/html (which is an empty string).
NOTE 2 Make sure to include the code in $(document).ready() or include it at the bottom of the page. It goes without saying you need jQuery in your page to run this.
You might want to check out jquery form plugin http://jquery.malsup.com/form/#
in simple way use
<div id="content">
if(isset($_POST['submit'] && !empty($_POST) )
{
// do your all post process
$name ='John';
echo $name;
}
else {
<form method="POST" action="$_SERVER['PHP_SELF']">
<label for="uname" >Name:</label><input type="text" name="uname" id="uname" size="50">
<input type=submit value="Get Code" name="submit">
</form>
}
</div>

Categories