Combining this piece of Javascript with another part? - php

Since I am a complete n00b in every aspect when it comes down to JS, JQuery and PHP, I will be needing some help.
Probably it's really simple for someone with basic knowledge of JS, but it ain't that simple for me.
I have the following part in my index.php:
<form method="get" id="searchform" action="http://wwwapps.ups.com/WebTracking/track?HTMLVersion=5.0&loc=nl_NL&Requester=UPSHome&WBPM_lid=homepage%2Fct1.html_pnl_trk" target="_blank" >
<input type="text" value="" name="trackNums" id="ups" />
<input type="hidden" name="track.x" value="Traceren">
<input type="hidden" name="loc" value="nl_NL">
<input type="image" src="afbeeldingen/search_btn.png" id="searchsubmit" />
</form>
In the .js file I have this:
$(document).ready(function() {
$("#ups").attr("value", "UPS Trackingscode...");
var text = "UPS Trackingscode...";
$("#ups").focus(function() {
$(this).addClass("active");
if($(this).attr("value") == text) $(this).attr("value", "");
});
$("#ups").blur(function() {
$(this).removeClass("active");
if($(this).attr("value") == "") $(this).attr("value", text);
});
});
I added this (at the top of) the .js file:
function removeSpaces(string) {
return string.split(' ').join('');
}
But when I add this part to the index.php (form-section) it doesn't work:
<input type="text" onblur="this.value=removeSpaces(this.value);">
I guess I have to incorporate it to the current JS as well, but I have no clue how to do this or what to change / add.
What I am trying to achieve here, is that whenever I paste a trackingcode into the text field, it should automatically remove the spaces (if there are any, because a bad copy/paste action).
It's not for any special website, but just for my personal use, so I can track packages more easily from my own starting page.
I hope I explained it correctly. Probably it takes less than a minute for someone with basic JS skills, but for me it's very difficult. :(

The function itself is working well. It's solely a scoping issue. You have two options:
1) You move your function outside the $(document).ready(function() { }) part
2) You remove the onblur="this.value=removeSpaces(this.value);" from your element, discard your function and write an according event-handler
// identifier or class needed to target the element, i use id="target"
$("#target").on("focusout",function(){
this.value = this.value.replace(/\s*/g,"");
});
The second way (using event handlers) is considered the cleaner and better way. But valid are both.
Sidenotes:
to remove spaces from your string, it's better to use the replace method with an according regular expression /\s*/g (replace zero or more whitespaces \s* in your entire string (globally g) ).
Instead of $(this).attr("value") use $(this).val().

Related

how to enable the submit button in real time depending on text validation?

I have a HTML form in list.php that submits the data from text box ("item" in below code) to check.php. This check.php validates the text entered to be not empty or white spaces only. After validation, it redirects to list.php for the entered text to be displayed. list.php is below. I want the "add" button to be enabled only when valid text is entered in the text box. I would like this feature to be done with php and probably not with javascript.
I can use "disabled=\"disabled\" in the form, but this does not work in real-time disabling depending on validation.
<form action="check.php" method="post">
<input name="item" type="text" size="25" autofocus="autofocus" />
<input type="submit" value="Add" id="add" />
</form>
You say:
I would like this feature to be done with php and probably not with javascript.
Unfortunately, if you want "real-time" then you're gonna need JavaScript. You'll need it to make AJAX calls to your PHP code to check for validation.
So either A) you don't validate in "real-time" at all, or B) You use JavaScript in one shape or another.
Let's say you opt for B), to use JavaScript, and presuming ALL you need to do is check for an empty string or whitespace, then you can do all of this client-side in JavaScript and not require a server call at all, also making it truly "real-time".
And so, here is my solution, using JavaScript (jQuery) without relying on server calls. This may not be suitable for your current implementation, but just in case it is, this might be helpful.
JSFiddle:
http://jsfiddle.net/VKfrw/1/
JavaScript:
function hasWhiteSpaceOrEmpty(s)
{
return s == "" || s.indexOf(' ') >= 0;
}
function validateInput()
{
var inputVal = $("#myInput").val();
if(hasWhiteSpaceOrEmpty(inputVal))
{
//This has whitespace or is empty, disable the button
$("#add").attr("disabled", "disabled");
}
else
{
//not empty or whitespace
$("#add").removeAttr("disabled");
}
}
$(document).ready(function() {
$("#myInput").keyup(validateInput);
});
HTML:
<!-- give this guy an ID -->
<input id="myInput" name="item" type="text" size="25" autofocus="autofocus" />
This implementation uses jQuery.
As mentioned, if you want this done in real time some javascript will be needed.
However I think this problem is actually more suited to javascript in general. PHP validation can be useful if you need to cross reference for data with data in your database.
eg. In a sign up form, checking a user is not already registered with the entered email address.
But in your case, depending on what you mean by "valid text" it is probably easier and better to use javascript.
There are some great jQuery plugins which make javascript validation really simple.
http://docs.jquery.com/Plugins/Validation/validate

JavaScript: formname.submit(); not working

I have the following form:
<form id="vintro-upload-form" action="{url}?nexturl={nextUrl}" method="post" enctype="multipart/form-data" >
<input name="file" type="file"/>
<input name="token" type="hidden" value=""/>
<input value="Upload Video File" type="button" name="submit" onClick="checkFile()" class="button" />
</form>
and the following javascript:
<script>
function checkFile(){
var fileVal = document.forms["vintro-upload-form"].elements['file'].value;
//RegEx for valid file name and extensions.
if(fileVal != ""){vintro-upload-form.submit();}
else {alert('Please select the Video file.');}
}
</script>
What works? The fileVal assignment is good. Submit isn't working, when I checked the debugger, it is saying: "vintro is undefined."
What have I tried?
The following examples and code:
http://www.w3schools.com/jsref/met_form_submit.asp
http://www.javascript-coder.com/javascript-form/javascript-form-submit.phtml
document.vintro-upload-form.submit();
document.forms["vintro-upload-form"].submit();
document.getElementById("vintro-upload-form").submit();
changed the dashes/hyphens to underscores
All to no success. There is some jQuery (in another .js file) going on with this form as well, and it functions properly with the hyphenated name.
Why is the submit call not working?
EDIT:
I have tried using document.getElementById('vintro-upload-form').submit(); as suggested in the answers to this question, however, this is still failing. My (Firefox) debugger is saying that it is not a function. Chrome's debugger explained a little bit more: "Uncaught TypeError: Property 'submit' of object # is not a function" (I'm going to Google this in the meantime.)
Since I have less than 100 reputation:
Ok, so it turns out, I was asking the wrong question.
Here's the answer I found:
Submitting Form Via Javascript, form defined in external PHP file
Check the accepted answer as well.
This JavaScript:
document.forms["vintro-upload-form"].elements['file'].value
is looking for the NAME attribute of the form tag:
document.forms[{form_name}].elements[{field_name}].value
You just have an ID. Copy the value of the ID to a NAME and you're done.
However, document.getElementById() is the preferred, modern way of doing this with plain JavaScript.
HOWEVER: You can't have a submit / button named "submit".
When you do and you call the JavaScript submit() function, you get a conflict.
You simply need:document.getElementById('nameofform').submit() is easier to find elements by its id than for the name.
Other way is to get elements by name, you can do it with document.getElementsByName('nameofform')...But that returns an array so you need to iterate that array to find which of those forms is needed to be uploaded. So, I think you should use the id.
The name of your form contains characters that cannot be used in a JavaScript identifier (dashes). Use document.getElementById('vintro-upload-form').submit(); instead.

Javascript Variables to PHP Script

I could see that this question was being asked a lot of times and I did extensive research on what methods could be used to transfer a couple of Javascript variables to a PHP script.
Post data in a form as hidden values
Post to URL, i.e. '/txt.php?h=' + var
Use a cookie
I'm trying write a piece of code that will let you download what you've written in Wrrrite.com - I'm the developer of this website. (I also did a client-side approach of putting the variables into the URI and setting a header to download stuff)
None of this is working. Either there's a character that's causing an error, or there are html elements.
Is there something I can code to guarantee a 1:1 transfer of the work/variables?
Datatype: HTML + various different Characters "!§!' etc.
Output: .txt File, perferably a 1:1 translation of what was being written on the form
You should maybe use a Base64 encoding of your data, before sending it. Have a look at MDN for the JavaScript part and here for the PHP decoding. This should prevent special characters from breaking your code.
Hope it helps
//PHP
if(isset($_REQUST['submit']))
{
$download=$_REQUEST['download'];
// from database get value of all the downloadable items
// and check if the input is in that array then to the suitable thing.
}
//HTML
<form method="post" action=''>
Type :<input type="text" id="txtField" name="txtField" />
<input type="hidden" name='download' />
<input type="submit" name="submit" onclick="return onSubmit() " />
</form>
//Javascript
<script type="text/javascript">
function onSubmit()
{
if(document.getElementById("txtField").value != '')
{
document.getElementById("download").value=document.getElementById("txtField").value;
return true;
}
else
{
alert("Please enter item to download");
return false;
}
}
Here's the Cookie Approach, which doesn't work http://pastebin.com/SKNtxLi5
That just slaps values together without any consideration for the data format used in cookies.
Quirks Mode has a decent guide to cookies with JS if you want to fix that.
However… the point of cookies is that the data persists. It isn't a sensible transform for one shot messages.

how to Pass Parameters to php page without having to load it

how can i pass parameters from an html page(map.html) to a php(createxml.php) without having to open the php page? Im incorporating googlemaps in html page(map.html) so i want the users to enter data on a form on the html page which will be sent to php(createxml.php) which in turn will connect to mySQL DB and create an xml format of the response the html page uses this xml output to create positions on the map since it contains longitude and latitude.
I have used the following code in the heading of the php page(createxml), but it shows the contents of php file for a brief moment redirecting me to map.html
Thanks for your time, i can post all the code if needed.
<meta http-equiv="refresh" content="0;url=http://localhost/map.html/">
It's quite simple with AJAX, using jQuery you don't have to know much about it :)
So simply import the latest jQuery Library.
Then you have your form:
<form id="my_form">
<input type="text" name="param1" />
<input type="text" name="param2" />
<input type="hidden" name="action" value="do_stuff" />
<input type="submit" value="Submit" />
</form>
and somewhere beneath that, you just paste this tiny javascript-function, which handles the submit of the form:
<script>
$('#my_form').submit(function(){
var post_params = $('#my_form').serialize();
$('#waiting').show();
$.post('the_page_you_are_on.php', post_params, function(data) {
$('#waiting').hide();
return false;
})
});
</script>
(The element (div, p...) with the id "waiting" could e.g. contain one of those fancy ajax loading images, but is not neccessary! :) If you want one to be shown, find one via google, set it as the background image of the #waiting-element and set its display to none (CSS)).
The function itself just calls the page you're on and then you've got the form variables in your post-array, so the top of your page could look something like this:
<?php
if(isset($_POST['action'])) {
switch($_POST['action']) {
case 'do_stuff' :
$param1 = $_POST['param1'];
$param2 = $_POST['param2'];
//do some DB-stuff etc.
break;
}
}
?>
I hope that helps!
It's a terrible idea, but because you don't want to use AJAX you could put the PHP in a frame and reload just that portion. Again, awful idea, but the closest you're going to get without using AJAX.
On a useful note though, AJAX is literally just one function in javascript. It's not hard at all to learn.
If you are just trying to pass parameters to a PHP page from the web browser, there are other ways to do it beyond 'Ajax'. Take a look at this page and view the source code (be sure to view the source of the included javascript file: http://hazlo.co/showlist.php?s=chrome&i=4e289d078b0f76b750000627&n=TODO
It uses an extremely basic method of changing the src of an image element, but passes information to the web server (PHP page) in the querystring of the image request. In this example I actually care about the results, which are represented as an image, but it sounds like you are just trying to pass data to the server, so you can return a 1 pixel image if you like. BTW, don't be fooled by the URL that is being used, a server rule is telling apache to process a specific PHP file when check it,GIF is requested.
You should play with it and use firebug or chrome's built in debugger to watch the requests that are being sent to the server.
You can't get any results from a PHP-script if you don't request it and process the output. If you dont't want to leave the current page, you have to use AJAX!
"but it shows the contents of php file for a brief moment" The reason is, that your browser first needs to load the entire page, then start the META-redirect. You don't need a redirect to load data from the server, but if you really want to, you should HTTP-headers for redirect.
Ok guys after hours of headache i finally found the solution! Basically i called my xmlproduce.php from inside my map.html, lemme explain so maybe will help others:
maps.html contained a googlmap API Javascript function which called my createxml.php called second.php
GDownloadUrl("second.php", function(data) )
what i did was i tweaked this call to second.php by adding some parameters in the URL like:
GDownloadUrl("second.php?strt="+ysdate+"/"+msdate+"/"+dsdate+"&end="+yedate+" /"+medate+"/"+dedate+"&id="+ide, function(data)
which is sending the parameters needed by second.php, so after that i made a small html form which called the script of googlemap api on the same file(map.html) to pass the parameters from the form to the GDownloadUrl i mentioned above, the code of the form is :
form method="get" action="">
IMEI: <input type="text" id="id" name="id" size="25" /> <br />
Start Date: <input type="text" id="ysdate" name="ysdate" size="4" value="2000" /> <input type="text" id="msdate" name="ysdate" size="1" /> <input type="text" id="dsdate" name="dsdate" size="1" /> <br/>
End Date: <input type="text" id="yedate" name="yedate" size="4" /> <input type="text" id="medate" name="ysdate" size="1" /> <input type="text" id="dedate" name="dedate" size="1" /> <br/>
<input type="button" value="submit" onClick="load()" />
</form>
afterwards i put extra constraints on the form for the values allowed.
Thanks everybody for the help, and you can always ask if somebody needs some clarification.

Remove text from fields on input

How do I make the text disappear like the way some fields work here on stackoverflow once I start putting in text? I tried out the different 'on'-actions in HTML but that didn't really do what I wanted.
Thanks.
You can do it with onfocus/onblur events. For example:
<input type="text" value="search" onfocus="if(this.value=='search')this.value=''"/>
If you click on this input field, the default text "search" will disappear. The onfocus event handler checks if this input field has the value of "search" and if so then clears it, in other cases (user has already typed something in) leaves everything as is.
Presumably you mean "Labels which appear inside the input".
If you want to do this in a sane, accessible, semantic way — use a <label>, if JS is available then position it under the element, and onfocus/onblur change classes around based on the value of the element.
I knocked up a simple example at http://dorward.me.uk/tmp/label-work/example.html using jQuery (all the source that isn't part of the jQuery library is embedded in the HTML of that document for easy reading).
jQuery would make this easy work;
http://www.jsfiddle.net/TshDN/
If you are using HTML 5 you could use the placeholder attribute.
http://dev.w3.org/html5/spec/Overview.html#the-placeholder-attribute
use the onFocus() in javascript
<input type="text" onfocus="if(this.value == 'value') { this.value = ''; }" value="value" />

Categories