I'm searching for the best solution to display information which I store in PHP variable (which I get from a MySQL DB).
I was thinking to use jQuery. My questions:
With the input field I receive the number of the Member.
I store a new variable called $imgMember with the img name.
Questions:
I want to display this image each time a user enters a number at <div class="boxImageMember"> (which I already validated through PHP and made a variable ($imgMember) of it.
How should I access it? Do I need to store those variable with AJAX? Internal/external jQuery? Or do I need to think otherwise? Im stuck in my head.
Im totally stuck with the way I how to process this.
HTML:
<div id="header">
<div class="header-content">
<img src="img/logo-dqmih.png" width="60px">
</div>
</div>
<div class="container">
<div class="boxImageMember">HERE I WANT TO DISPLAY A USER IMAGE</div>
<div class="boxInformationMember"></div>
<form action="" method="post">
<input type="text" id="MemberNumberEntry" name="staffNumber">
<button type="submit" name="action">
</form>
</div>
jQuery:
$(document).ready(function() {
$("#MemberNumberEntry").focus();
$(document).on('submit',function(event, test){
event.preventDefault(); // Don't refresh the page
var MemberNumberEntry = $("#MemberNumberEntry").val();
console.log(MemberNumberEntry);
$(".boxImageMember" ).css("background-image", "url(../images/persons/NIT.jpg)"); // Change image (Not dynamic yet)
$(".boxInformationMember" ).text("Hi Test, welcome!");
// Reset value form entry
$('#memberNumberEntry').val('');
});
});
Your jQuery script would do something like this
$(document).ready(function() {
$("#MemberNumberEntry").focus();
$(document).on('submit',function(event, test){
event.preventDefault(); // Don't refresh the page
var MemberNumberEntry = $("#MemberNumberEntry").val();
//console.log(MemberNumberEntry);
$.ajax({
url: '/your-php-script.php',
method: 'POST',
data: {
MemberNumberEntry: MemberNumberEntry
},
success: function(response){
//If call goes well, you use the image here.
}
});
$(".boxImageMember" ).css("background-image", "url(../images/persons/NIT.jpg)"); // Change image (Not dynamic yet)
$(".boxInformationMember" ).text("Hi Test, welcome!");
// Reset value form entry
$('#memberNumberEntry').val('');
});
});
You're basically sending an HTTP POST request to your PHP script that will accept the image ID like a normal post request, using $_REQUEST or $_POST.
There are tonnes of options to configure with jQuery, you can look at the docs here. For more information on working with images in PHP and AJAX, this answer is useful.
Related
For what is probably a pretty easy thing to do, I am not sure I have implemented it correctly,
I am trying to send 2 local storage variables that are created using javascript, I understand that this data generated at the client-side and that it needs to be sent server-side, and after trying to get my head around AJAX, I found this https://www.quora.com/Is-it-possible-to-get-localstorage-key-value-into-a-php-variable-If-so-how-can-we-do-it, that pointed me in the right direction.
After looking at a few other tutorials I think I have written the correct code, but after trying it the script doesn't seem to be functioning correctly.
The radio button form functions correctly and will submit data to firebase firestore with no issues, but that is not viable for the rest of the app, so I decided to use mysql database instead.
The problem that occurs, from the console, is that when I click the submit button that is revealed on performing the form action is
Uncaught ReferenceError: firebase is not defined
at HTMLFormElement.<anonymous> (auditConfirm.js:1)
but as far as I can tell I'm not referencing auditConfirm.js in either of the 2 files I am using.
I don't think I have coded it correctly and am quite stumped on where to go from here, If someone could please tell me where I have gone wrong that would be great.
These are the local storage variables created, veneuPercentage & auditPercentage
// output results on page
// local storage has to go at the end as this is the final value of each item.
venueResult.querySelector('span').textContent = `${venuePercentage}%`;
venueResult.classList.remove('hide');
auditResult.querySelector('span').textContent = `${auditPercentage}%`;
auditResult.classList.remove('hide');
formConfirm.classList.remove('hide');
this is the PHP file I have written, auditConfirm.php, that should then access these variables from javascript and send them to the database using a JQuery post method, that allows for a sql query to add them to the database.
<?php
if(isset($_POST["confirmResult"])){
$venueScore = $_POST['jsVenuePercentage'];
$auditScore = $_POST['jsAuditPercentage'];
include('static/connection.php');
$auditQuery = "INSERT INTO bar 13 (venueScore, auditScore, submissionDate) VALUES ('$auditScore', '$auditScore', CURRANT_TIMESTAMP)";
if( !mysqli_query($connection, $auditQuery)){
echo "Error: ". $auditQuery."<br>". mysqli_error($connection);
}
?>
<script>
var localVenuePercentage = localStorage.getItem("venuePercentage");
var localAuditPercentage = localStorage.getItem("auditPercentage");
$("confirmResult").click(function(){
$.post("auditConfirm.php",{jsVenuePercentage: localVenuePercentage});
$.post("auditConfirm.php",{jsAuditPercentage: localAuditPercentage});
});
</script>
but again, I'm not sure if I have implemented it correctly.
finally this is the section of the form that I have assigned the above script too.
<div class="container blue-grey-text text-lighten-1">
<form class="submitResults-form hide brown lighten-5 p-b-10">
<div class="row">
<div class="col s3"></div>
<div class="col s6 center-align">
<button class="btn brand waves-effect waves-light red lighten-1" type="post" name="confirmResult" id="confirmResult">Confirm result<i class="material-icons right">send</i></button>
</div>
<div class="col s3"></div>
</div>
</form>
When using Ajax I recommend trying the non-shorthand:
$.ajax({
type: "POST",
url: 'auditConfirm.php',
data: {
jsAuditPercentage: localAuditPercentage,
jsVenuePercentage: localVenuePercentage,
}
});
This solution works on my end.
I would like to do a web site using Aptana IDE and xampp, and it has a few pages. Index page is where all users which does not log in the system and home is where all users which does log in the system must visit. I am very new to develop web site. Because of that I am changing a lot of and vital things during the development. An here my problem is began.
I have created log and sign pages separately using HTML5, CSS, Javascript, JQuery and Php. To achieve more quality service, decided to use also Ajax. These pages works correctly, log page can control validation with jquery
$('#login-form').validate({
//validation rules, messages and submitHandler(ajax code) goes here});
and with using ajax, it can communicate with php file and mysql database so can check whether the user is exist or not.
$.ajax({
type: 'POST',
url: 'log.php',
data: strAjax, //username and password
success: function(data) { //data is echoing from php file either as true or false
if(data) {
window.location.href = "home.php";
}
else {
//some error messages
}
}
});
Sign systems works like it and correctly. But I do not like the design of these pages because of emptiness. So in index file when user click log in button, the log file is showing inside a div with jquery load function.
$(".jumbotron").load("login.html").hide().fadeIn(1500).delay(5000);
Same thing for sign system as well. For good looking, I am satisfied but...
The whole system messed up. (I want to cry) I have to think before start to coding web site, very bad I know but this is my first complete web site. How can achieve a system working properly in this way? I have searched some pages on the internet and they said that the ajax can not work across the pages or something like that. I am also new to stack overflow too, so some important thing will be forgotten. I can edit if you want more information.
Thank You and Regards...
EDIT 1:
<div class="jumbotron">
<div class="container">
<h1>//sometext</h1>
<p>//some text</p>
</div>
</div>
Firstly this is showing on the screen. And when the user press login button, jquery load function running which is above. And loads login.html which works properly by itself.
<form id="login-form" class="text-left">
<div class="form-group">
<label for="lg_username" class="sr-only">Username</label>
<input type="text" class="form-control" id="lg_username" name="username" placeholder="username"
data-container="body" data-toggle="popover" data-placement="left" data-content=""
value="">
</div>
<div class="form-group">
<label for="lg_password" class="sr-only">Password</label>
<input type="password" class="form-control" id="lg_password" name="password" placeholder="password"
data-container="body" data-toggle="popover" data-placement="left" data-content="">
</div>
<div class="form-group login-group-checkbox">
<input type="checkbox" id="lg_remember" name="lg_remember">
<label for="lg_remember">remember</label>
</div>
<button type="submit" class="login-button">Submit</button>
</form>
The jquery validation works right. My rules are valid. If the inputs are ok upon my rules, it send me to home.php. I think ajax code can not work.
submitHandler: function() {
var username = $('#lg_username').val();
var password = $('#lg_password').val();
var checkbox = $('#lg_remember').is(":checked");
var strAjax = "username=" + username + "&password=" + password + "&checkbox=" + checkbox;
$.ajax({
type: 'POST',
url: 'logDeneme.php',
data: strAjax,
cache: false,
success: function(data) {
if(data) {
window.location.href = "home.php";
}
else {
//error message. but when this code run, always send to home page.
}
}
});
return false;
}
This parts all works. It does not works inside index.php. My question is why and how to handle this!
Problem 1
Your form is submitting via a GET request because the JS is not getting called (see #2 below) and the HTML is likely declared like this:
<form action='log.php'>
[...]
</form>
You must specify method='post' to submit POST data.
Problem 2
Unless you're using a jQuery plugin there is no .validate event for forms. You want to use .submit.
Finally, make sure all your javascript is in $(document).ready(function() { ... }); or it won't execute at the right time. Look in the Firefox/Chrome developer console, it's a lifesaver for debugging.
I am currently making a webpage where I want the user to view different database results depending on which result they pick. The results will either be picked through a button, or by a query typed in by hand into a textarea.
I have the connection to the database and everything set up in an external PHP script which I am currently linking in to my site using "require".
Within this PHP script I have a "query" variable.
I would like for this variable to be dependent on whatever value is entered by the user.
I suppose this should be doable using some sort of $query = $POST['entry'] and some kind of Ajax call in a javascript? I just don't know how this whole thing should be fitted together.
If we assume that my menu and container looks something like this, where getData.php is where the $query variable is and what returns the database data.
<div id="menu">
<textarea class="queryText" name="queryText" placeholder="Enter the query..."></textarea>
<input class="menuButt" type="button" value="Submit" onclick="JavaScript:ChangeDivVal();"/>
</div>
<div id="container">
<?php
require 'getData.php';
?>
</div>
Here is a picture if that helps my explanation of what I want to do.
I'm very grateful for any help I could possibly get!
//Ambrose
There are neat and simple mechanisms to pass the input of your textarea (the query string) to php and return the database output back to javascript. From there you then can easily attach it to any dom node you wish.
I personally do stuff with jQuery since its so handy. You might wanna use the load function for your simple purpose:
$( document ).ready(function() {
$('#querySubmitButton').click(function (evt)
{
evt.preventDefault(); // stops the submit taking place
var myQuery = $('#queryText').val(); // get the query value
// load data received from php script into the dom container
$('#container').load('getData.php', { query:myQuery, anotherVar:null });
});
});
The load function simply loads everything the desired script outputs into the given domnode. You can add as many parameters as you want in the second argument and could even use a callback to perform some more js after loading.
For details see http://api.jquery.com/load/.
Oh and by the way I changed your html to this:
<div id="menu">
<textarea id="queryText" name="queryText" placeholder="Enter the query..."></textarea>
<input id="querySubmitButton" type="button" value="Submit"/>
</div>
<div id="container"></div>
In your getData.php (which I assume produces plain html) you can then use php's $_POST var to get the query.
$query = $_POST['query'];
This is really frustrating I would appreciate some help with this. I have a div, called comments and a form inside of that div. What I want to do is post a form to the current page and have it load inside of the div without reloading the entire thing. Here is my current code:
<div id="comments">
<form action="#" method="post" onsubmit="return false;" >
<input type="hidden" name="txtname" value="test">
<textarea id="wysiwyg" name="wysiwyg" rows="5" cols="50"></textarea>
<input type="submit" name="post" id="post" value="Submit">
</form>
<script type="text/javascript">
EDIT: Read edit below for current code
</script>
</div>
When I submit, the alert fires, but the page does not load. It works fine if I make the event as follows:
$("#comments").load("comments.asp");
It's not liking the posting of data. I have used .load before but never to post data. I got the above code from these very same forums.
I'm honestly not sure of the purpose of 'name' and 'tel' - do I refer to those variables or the form variable names when processing the code? This is in ASP classic.
What's wrong with the above code, how can I get it to send data from the forum via POST? Thanks!
EDIT:
I am now using the following code:
$("#post").submit(function(event){
var $form = $(this),
$inputs = $form.find("input, select, button, textarea"),
serializedData = $form.serialize();
$inputs.attr("disabled", "disabled");
$.ajax({
url: "/comments.asp",
type: "post",
data: serializedData,
success: function(response, textStatus, jqXHR){
console.log("comment posted");
},
error: function(jqXHR, textStatus, errorThrown){
console.log(
textStatus, errorThrown
);
},
complete: function(){
// enable the inputs
$inputs.removeAttr("disabled");
}
});
event.preventDefault();
});
And now it's using properly getting the form handled...however it goes to comments.asp. How can I make all the action happen in a certain div (comments div?)
It seems to me you are blending a bunch of different techniques in a way that is not entirely coherent.
$.post is a shortened version of $.ajax (see here).
$.load takes a url and sticks it into a <div> or other DOM Element (see here).
If I understand it correctly (and I may not!), you're not really wanting to load the form, but put values into the form fields. $.load is an odd way to do this. (It may work, but I do it another way.)
If you're using $(#...).submit, you can also leave out a whole bunch of stuff in your form. The following should work fine.
<form id="form_id">
...
<input type="submit" value="Submit">
</form>
My method is: (1) have a hardcoded HTML form (or build it by AJAX), (2) get the values from the DB (or wherever) using $.post (or $.ajax), (3) stick the values into the form using .val() (or equivalent - whatever is right for the input type) and the DOM id of that input, and then (4) use .submit (in a manner similar to yours). You will need to add preventDefault as the others have suggested.
You're also muddying the waters using #post as the DOM id. You really want to give the form itself the ID, and then use $(#form_id).submit(... I can't test it now, but having the submit on the input field may cause some grief. The official example attaches the .submit to the form id.
I'm also not sure the <div> with id 'comments' really does much. I have a container id like your 'comments', but that's because I build forms by AJAX and stick them into the container. If you don't need to do that, the id 'comments' is unnecessary to the whole procedure.
Your text box element dont have an id with value txtname. But in your script you are trying to access using # (which is supposed be with an id context). So add an id element to your input box.
<input type="hidden" name="txtname" id="txtname" value="test">
And as expascarello said, You need to stop the default behaviour of the submit button . Other wise it will do the normal form posting so you wont be able to feel the ajax effect.
Use preventDefault
$(function(){
$("#post").click(function(e) {
e.preventDefault()
alert("clicked");
$("#comments").load("comments.asp", {
'name': $("#wysiwyg").val(),
'tel': $("#txtname").val()
});
});
});
You are not cancelling the clicking of the button so the form is submitting and resetting the page.
$("#post").click(function(evt) {
evt.preventDefault();
...
jQuery event.preventDefault()
The load() method does a get and not a post.
let me start by saying it may look simple but im finding it extremely difficult.
ive made a search script that uses PHP and to fetch a result would look like this
search.php?term=alice&submit=Submit
Standard stuff.. problem is, i use an SPI with AJAX and PHP so my results would have to load dynamically into a div, whilst still keeping the hash value, as not to lose the page the user had visited previous to searching.
jQuery.history.js is the plugin i use for back button support, which requires links to be like such:
Home Page
this would load 'home.html' into a div named pageContent. as far as i know theres no way to call php files unless you develop a little hack, which i have,
here is my JavaScript/jQuery for my search form:
<script language="JavaScript">
$(document).ready(function() {
// bind form using ajaxForm
$('#search1').ajaxForm({
// target identifies the element(s) to update with the server response
target: '#pageContent',
// success identifies the function to invoke when the server response
success: function() {
$('#pageContent');
var hash = '#search.php?term='+($('#query').val()+'&submit=Submit').replace(/ /g, '+');
var stripped = hash.replace(/(<([^>]+)>)/ig,"");
update(window.location.hash = stripped);
}
});
});
</script>
Heres the form:
<form id="search1" action="search.php" method="post">
<input id="query" type="text" name="term" />
<input type="submit" name="submit" value="Submit" />
</form>
My problem is this:
ive tried this.form.reset(); this: Resetting a multi-stage form with jQuery , yet none of this works. please help me if you know a way of doing this..
$('#query').val(DefaultValue);
with this u can set your value to whatever you want, like blank: '';