I tried a jquery function using jQuery and it's not working
It's pretty weird. I put some alerts in the js file, but when I click on the button (with id="gettotalnutrients"), none of the alerts from the js file happen.
this is where I grab the data for the js file (and display the data):
<div id="feedback"></div>
<br />
<form id="form_date_nutrient_getter" action="account-overview.php" method="POST">
Select a start date: <input id="datestart" type="text" name="beginday_calendar"><br />
Select a end date: <input id="dateend" type="text" name="endday_calendar"><br />
<input type="button" id="gettotalnutrients" value="Get the total nutrients" ><br /><br /><br /><br /><br /><br /><br />
</form>
</div>
js file:
$('#gettotalnutrients').click(function(){
alert('test');
var datestart = $('#datestart').val();
alert(datestart);
var dateend = $('#dateend').val();
alert(dateend);
$.post('getTotalNutrients.php',(beginday_calendar: datestart, endday_calendar: dateend), function(data){
$('#feedback').text(data);
});
});
wrap your click() function in $(document).ready() or something like that:
$(document).ready(function() {
$('#gettotalnutrients').click(function(){
// the rest of your code goes here
});
});
Also, are you seeing any errors in the js console?
Did you try chnaging the brackets to {
$(function(){
$('#gettotalnutrients').click(function(){
//remaining code
$.post('getTotalNutrients.php',{ beginday_calendar: datestart, endday_calendar: dateend}, function(data){
$('#feedback').text(data);
});
});
});
Related
I'm trying to create a search feature that searches a database based on the criteria a user has entered. Right now, I'm just trying to get the jQuery variable data into PHP. I've decided to use the shorthand AJAX $.post method because this is just a demo project. I know there are numerous similar questions like mine, but I have yet to find an answer to any of them that I can use.
So what I'm trying to do is, the user will click on a drop down menu and select an option. AJAX then sends the selected value to the PHP file and the PHP will eventually perform a database search based on what was selected. The issue is, in PHP, I'm getting a string of "Search" when the data is parsed and I echo it but when I do a console log on the variable that was sent, I'm getting the correct text. Can anyone tell me where I'm going wrong?
Here's what I have so far.
AJAX
$("#search_form").on("submit", function(ev){
ev.preventDefault();
$.post("../php/test.php", $(this).serialize(), function(data){
console.log(data);
})
})
PHP
ob_start();
require("../includes/header.php");
$criteria = $_POST["search"];
ob_clean();
echo $criteria;
HTML
<form id="search_form" method="post">
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="text" name="search" id="search" />
<input type="submit" class="button" value="Search_Now" />
</fieldset>
As Requested
Here is a fiddle of the drop down menu to show how it works.
http://jsfiddle.net/xvmxc0zo/
Your form is being submitted via default form submission; the ajax call is misplaced, it should be within the submit handler, which should prevent default form submission.
Note that I have removed both name and id attributes from the submit button; you do not need them. Just let the submit button do it's job and listen for the submit event on the form where you would then use event.preventDefault(); to make sure the form does not submit, then you can make your ajax call.
$("#searchBy").on("click", ".option", function(){
$('#search').val( $(this).text() );
});
$('form').on('submit', function(e) {
e.preventDefault();
$.post("../php/test.php", $(this).serialize(), function(data){
//jsonData = window.JSON.parse(data);
console.log( data);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="hidden" name="search" id="search" />
<input type="text" name="search_text" id="search_text" />
<input type="submit" class="button" value="Search" />
</fieldset>
</form>
In your PHP use echo $criteria; instead of echo json_encode($criteria);.
I'd suggest to use the way of jQuery documentation to check changes in your drop down.
$( "select" ).change(function () {
$( "select option:selected" ).each(function() {
$.post("../php/test.php", {search: $(this).text()}, function(data){
jsonData = window.JSON.parse(data);
});
});
})
You are getting "Search" on the PHP side because that is the value of your submit button.
You want the post to occur when you click on an option? Try adjusting your selector as follows:
$("#searchBy .option").on("click", function () {
var search = $(this).text().trim();
$.post("../php/test.php", { search: search }, function (data) {
jsonData = window.JSON.parse(data);
})
});
I think your header.php is provoking the error. I created a test file myself with your code and that works perfectly fine:
<?php
if($_POST)
{
ob_start();
//require("../includes/header.php");
$criteria = $_POST["search"];
ob_clean();
echo json_encode($criteria);
exit;
}
?>
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="text" name="search_text" id="search_text" />
<input type="submit" name="search" id="search" class="button" value="Search" />
</fieldset>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$("#searchBy").on("click", ".option", function(){
var search = $(this).text();
$.post("<?=$_SERVER['PHP_SELF']?>", {search: search}, function(data){
jsonData = window.JSON.parse(data);
console.log(jsonData); //Prints the correct string
})
});
</script>
Hi I am using AJAX for the first time and I'm watching this tutorial so I can implement the feature on my website: https://www.youtube.com/watch?v=PLOMd5Ib69Y. What I'm trying to do is make a contact us form where the user can write a message and when he click a button the message is sent to my email. With AJAX I'm trying to change the button content without reloading.
I have this AJAX code:
<script src="/js/jquery-1.4.3.min.js" type="text/javascript"></script>
<script>
var ajax =
{
send: function()
{
var userName = $("input[name=un]").val();
var userEmail = $("input[name=email]").val();
var userMsg = $("input[name=msg]").val();
if(userName == "" || userEmail == "" || userMsg == "")
{
alert("All fields are required!");
}
else
{
ajax.SetText("Sending...");
$.post("sendMSG.php", {
name : userName, email : userEmail, message : userMsg
}, function(data){
ajax.SetText(data);
});
}
},
SetText: function(text)
{
$("input[type=button]").val(text);
}
}
</script>
And the html form:
Name: <br> <input type="text" size="40" name="un">
<br>
Email: <br> <input type="text" size="40" name="email">
<br>
Write us a Message!
<br>
<textarea rows="4" cols="50" name="msg" id="content"></textarea>
<br/>
<input type="button" value="Send Message!" onClick="ajax.send()" />
For some reason when I click on the button nothings happens. As I said this is my first time using AJAX and I don't have idea how to use AJAX code. So please take it easy on me if the answer is simple :p
Thanks
You seem to be using a rather old version of jQuery. You should use the latest one which can be found on the jQuery Website.
Now for this example we'll use the submit event listener.
First you need to set up a form correctly:
<form id="myform" method="post">
Name: <br> <input type="text" size="40" name="un">
<br />
Email: <br> <input type="text" size="40" name="email">
<br />
Write us a Message!
<br />
<textarea rows="4" cols="50" name="msg" id="content"></textarea>
<br />
<input type="submit" value="Send Message!"/>
</form>
Now for the jQuery (as stated above; we'll be using the submit event.) But first we have to ensure the DOM element is loaded before running our jQuery. That is done by using:
$(document).ready(function(){});
Setting up our jquery is as simple as writing what we want to do in our submit event listener:
$(document).ready(function(){
$('#myform').submit(function(e){
e.preventDefault();
$.post('sendMSG.php',{name: userName, email: userEmail, message: userMsg}, function(data) {
console.log(data);
});
});
});
Obviously doing all the proccessing you require before running the $.post ajax request.
A Few Notes:
You could use e.preventDefault() or return false; within your event to stop the default actions taking place. (see below)
e.PreventDefault()
$('#myform').submit(function(e){
e.preventDefault();
// do ajax and processing stuff
});
return false;
$('#myform').submit(function(e){
// do ajax and processing stuff
return false;
});
You should look into using jQuery.ajax instead of the jQuery.post as it gives you more options.
I think you are using jquery,So you should put each code in
$(document).ready(function(){});
I would like to get select form with variable amount of fields. To achive this first I connect to db and converting data from php to javascript. Then i got array (wynik) with values, but when i try to print it i get empty select form and all values shown next to it. There is my javascript function:
<script language="javascript">
function addInput() {
document.getElementById('text').innerHTML += "<select name='add' /><br />";
for (i=0;i<wynik.length;i++)
{
document.getElementById('text').innerHTML += "<option value=" + "wynik[i]" + " />" + wynik[i] + "</option />";
}
document.getElementById('text').innerHTML += "</select />";
}
</script>
And HTML code:
<form name="add" action="add_form.php" method="post">
<div id="text">
</div>
<br>
<input type="submit" value="Submit" />
</form>
<input type="button" onclick="addInput()" name="add" value="Add value" />
Please help me to put that into form.
The browser will attempt to fix the DOM each time you write HTML to it, consequently you cannot write just a start tag to innerHTML.
Build all your HTML up in a string and then insert it in one go.
Better yet, use createElement, appendChild and friends instead.
Perhaps you need to remove <br /> after <select name='add' /> . Also </select /> does not need a / in the end (it has it in the begining) - </select>.
Another approach you can try with ajax:
<!-- Script -->
<script type="text/javascript">
$(function(){
$("#add").on('click', function(){
$.ajax({
url : 'ajax.php',
type : 'POST',
success : function(resp){
$("#backend").html(resp);
},
error : function(resp){
}
});
});
});
</script>
<!-- HTML -->
<div id="text"><select id="backend" name=""></select></div>
<input type="button" id="add" value="Add value" />
<!-- Backend ajax.php -->
<?php
#your query here to fetch $wynik
$str = "";
foreach($wynik as $value){
$str .= '<option value="'.$value.'">'.$value.'</option>';
}
return $str;
My current working situation looks something like this:
<!-- collect user info -->
<form method="GET">
<input name="param1" type="text" />
<input name="param2" type="text" />
<input type="submit" />
</form>
<!-- display image based on user info -->
<img src="color.php?param1=<?php echo $_GET['param1']; ?>param2=<?php echo $_GET['param2']; ?>" alt="" />
This is working perfectly. Now I would like only the image being updated by ajax, while the rest of the HTML remains unchanged. I tried this:
<form method="GET" id="formId">
<input name="param1" type="text" />
<input name="param2" type="text" />
<input type="submit" />
</form>
<div id="result"></div>
<script type="text/javascript">
var frm = $('#formId');
frm.submit(function(){
$.ajax({
type: 'GET',
success: function () {
$('#result').html('<img src="color.php?' + frm.serialize() + '" />');
}
});
return false;
});
</script>
In fact this solution works more or less. However, I have some issues here:
Is this good jquery / ajax code or is it silly (yes, I am new to jquery)?
The field "result" does update only if one of the fields changes. Can I make it update whenever the submit button is being klicked?
I would like to display a spinning load.gif while the color.php calculates the picture. I tried it this way, without success:
var ajax_load = "<img class='loading' src='img/load.gif' alt='loading...' />";
$('#result').html(ajax_load).html('<img src="color.php?' + frm.serialize() + '" />');
Thank you!
To the jQuery ajax call add the parameter cache : false, to force to refresh the image. To use the loader, just play with the attributo src. Copy / paste the code:
<form method="GET" id="formId">
<input name="param1" type="text" />
<input name="param2" type="text" />
<input type="submit" />
</form>
<div id="result">
<img id="preview" src="img/load.gif" />
</div>
<script type="text/javascript">
var frm = $('#formId');
frm.submit(function(){
$('#preview').attr('src', 'img/load.gif' );
$('#preview').attr('src', 'color.php?' + frm.serialize() + '&_' + new Date().getTime() );
return false;
});
</script>
I have a form which I want to submit without refreshing the whole page.
I've found a ready source code and implemented it on my pages, but it refuses to work!
here is the html form I need to submit:
<form method="POST" action="" name="actionForm" id="actionForm" class="actionForm">
<input type="hidden" name="adID" value="'.$row['adID'].'" />
<input type="hidden" name="adStatus" value="'.$row['adStatus'].'" />
<input type="submit" name="editAd" value="ערוך מודעה" class="actionButtons" />
<input type="submit" name="upgradeAd" value="הקפץ מודעה" class="actionButtons" />
<input type="submit" name="changeAdStatus" class="actionButtons" value="';
if ($row['adStatus'] == "disabled")
echo 'הצג מודעה בלוח" />';
else
echo 'הסתר מודעה מהלוח" />';
echo '
<input type="submit" name="deleteAd" value="מחק מודעה" class="deleteButton" />
</form>
and here is the script to forward to the processing php file and writing some results on the current page:
<script>
$(document).ready(function(){
$("#actionForm").validate({
debug: false,
rules: {
submitHandler: function(form) {
$.post('/tests/process.php', $("#actionForm").serialize(), function(data) {
$('#resDiv').html(data);
});
}
}});
});
</script>
the processing php only writes data to the database and prints a confirm message.
here is the link to it: http://codeviewer.org/view/code:29c4
I've inspected every single line of the code but still can't get why I see no message from the processing php...
any ideas?
thanks in advance for your help!
P.S. here is the full code of the initial php: http://codeviewer.org/view/code:29c3
I think your javascript snippet at the end of your code is wrong. The submit handler must not be in the rules: {} block.
Try the following:
<script>
$(document).ready(function() {
$("#actionForm").validate({
debug: false,
submitHandler: function(form) {
$.post('/tests/process.php', $("#actionForm").serialize(), function(data) {
$('#resDiv').html(data);
});
}
});
});
</script>