So I would like to submit the form using Javascript, and with the form I would like to send also one Javascript array.
So far I have this which is not working (I don't get the modified URL and I get the one specified in the action property of the form):
<script>
function submit_form() {
var unique_id_to_delete = [];
if (confirm('Remove records ID: ' + unique_id_to_delete.toString() + '?')) {
document.getElementById("submit_form").submit(function(event) {
event.preventDefault();
var url = 'submit.php?id_delete='+unique_id_to_delete.toString();
window.location.href = url;
});
} else {
alert('Ok, next time!');
}
}
</script>
Form:
<form id="submit_form" method="post" action="submit.php" enctype="multipart/form-data">
<input type="button" onclick="submit_form();" value="Submit"/>
</form>
Form submit using javascript
function submit_form()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//response after success
//xmlhttp.responseText
}
}
xmlhttp.open("GET","YOUR URL WITH PARAMS",true);
xmlhttp.send();
}
Heh.. ok I tried this which I think is not what you thought..
<script>
function submit_form() {
var unique_id_to_delete = [];
if (confirm('Remove records ID: ' + unique_id_to_delete.toString() + '?')) {
var data1 = JSON.stringify(unique_id_to_delete);
$.ajax({ type: "POST", data: {value1:data1}, url: "submit.php", success: function() {
} });
} else {
alert('Ok, next time!');
}
}
</script>
script:
function submit_form() {
var unique_id_to_delete = [];
if (confirm('Remove records ID: ' + unique_id_to_delete.toString() + '?')) {
var url = 'submit.php?id_delete='+unique_id_to_delete.toString();
alert(url);
window.location.href = url;
} else {
alert('Ok, next time!');
}
}
Form:
<form id="submit_form" method="post" enctype="multipart/form-data">
<input type="button" onclick="submit_form();" value="Submit"/>
</form>
Your form will never but submitted as your are simply redirecting the window location, thus creating a GET rather then a POST as intended.
You could do:
function submit_form() {
var unique_id_to_delete = [1,2,3,4,5,6];
if (confirm('Remove records ID: ' + unique_id_to_delete.toString() + '?')) {
$.ajax({
url: "submit.php",
type: "POST",
data: unique_id_to_delete,
});
} else {
alert('Ok, next time!');
}
}
And not need a form:
<input type="button" onclick="submit_form();" value="Submit"/>
I haven't used PHP in a while, but at the other end you need to use json_decode
Related
I wanna make ajax calls in symfony2. I already done with ajax with flat php and i have no idea how to set up in this symfony framework.
<html>
<head>
<script>
function showBook(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
function showAuthor(str){
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getAuthor.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form action="">
Book name: <input type="text" id="txt1" onkeyup="showBook(this.value)">
<br><br>
Author name:<input type="text" id="txt1" onkeyup="showAuthor(this.value)">
</form>
<br>
<div id="txtHint"><b>book info will be listed here...</b></div>
</body>
</html>
Where should i pass this request?? to controller??
how to set routes??
is there any way to use flat php instead of controller??
You would pass the request to a controller action exposed using a route:
http://symfony.com/doc/current/book/routing.html
Then in your html code, if you are using twig and including javascript in a script tag, you can do
xmlhttp.open("GET","{{ path("route_name", {"parameter_name":"parameter_value"}) }}");
If you want to access the route in an attached .js file, you can use FOSJsRoutingBundle to generate the route url
If you are in a form, you can do something like :
$(document).submit(function () {
var url = $('form').attr('action');
var data = $('form').serialize();
$.post(url, data, function (data) {
window.location.href = data.redirect;
})
.fail(function () {
$('form').replaceWith(data.form);
});
});
You just need to send the correct url :
$(document).on('click', 'a', function () {
var url = window.location.href;
$.get(url, function (data) {
$('.container').replaceWith(data);
});
});
It is also possible to use a routing generate, simply add:
"friendsofsymfony/jsrouting-bundle": "dev-master" to your composer.json.
AppKernel.php :
new FOS\JsRoutingBundle\FOSJsRoutingBundle()
Then config it in your routing.yml :
fos_js_routing:
resource: "#FOSJsRoutingBundle/Resources/config/routing/routing.xml"
And finally use "expose" arg in your routing :
#Route("/{table}/index", name="beta.index", options={"expose"=true})
I use annotation routing
In your JS :
var url = Routing.generate('beta.index', { 'table': 'foo' });
Hope it'll help you :)
I have an ajax call. This script is working fine when I put it in one file with the form that will be loaded with the script.
$(document).ready(function () {
$("#uploadbutton").click(function () {
var referenceNumber = document.getElementById('referenceNumber').value;
$.ajax({
type: "POST",
url: "selectReferenceOrder.php",
data: 'referenceNumber='+referenceNumber,
cache: false,
//data: $('form').serialize(),
success:function(html)
{
document.getElementById('outputReference').innerHTML = html;
alert('referenceNumber');
}
});
});
});
However, when I try to put it in an external file, it doesn't give me anything.
The script of this ajax is functioned as the script that will post the form into the php file.
Reference: <input type="text" id="referenceNumber" />
<input type="button" id="uploadbutton" value="SEARCH"/>
I have tried many ways of doing this, but it still doesn't work:
<input type="submit" value="SEARCH" onclick="collectActed()" />
function collectActed () {
var referenceNumber = document.getElementById('referenceNumber').value;
$.ajax({
type: "POST",
url: "selectReferenceOrder.php",
data: 'referenceNumber='+referenceNumber,
cache: false,
success:function(html) {
document.getElementById('outputReference').innerHTML = html;
}
});
}
Please, help.
Following code works well:
<html>
<head>
<title>Ajax Search</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
function searchFor(suchbegriff) {
var xmlHttp = null;
// Mozilla, Opera, Safari sowie Internet Explorer 7
if (typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
if (!xmlHttp) {
// Internet Explorer 6 und älter
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xmlHttp = null;
}
}
}
// If object has been created
if (xmlHttp) {
var url = "search.php";
var params = "search=" + search;
xmlHttp.open("POST", url, true);
//Headerinformatio for POST request
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
// Zurückgeliefertes Ergebnis wird in den DIV "ergebnis" geschrieben
document.getElementById("result").innerHTML = xmlHttp.responseText;
}
};
xmlHttp.send(params);
}
}
</script>
<script>
$(document).ready(function(){
$("input").click(function(){
$("div").load("search.php");
});
});
</script>
</head>
<body>
<input type="text" onkeyup="searchFor(this.value);"/>
<div id="search"></div>
</body>
</html>
I have following form and javascript which is not activated on submit. I can not understand where is the problem so that the javascript is not fired by pressing the button. The script is included in the html of course and the path is correct.
var req;
function addProductToCart(){
var url = "/addToCart";
var productReference = document.getElementById("selectedProductRef");
var size = document.getElementById("selectedProductSize");
req = initRequest();
req.open("POST", url, true);
//req.onreadystatechange = callback;
req.send("selectedProductRef="+productReference.value+"&selectedProductSize="+size.value);
}
function callback(){
if (req.readyState == 4) {
if (req.status == 200) {
parseMessages(req.responseText);
}
}
}
function initRequest(){
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
req = new XMLHttpRequest();
}
else if (window.ActiveXObject){
// code for IE6, IE5
req = new ActiveXObject("Microsoft.XMLHTTP");
}
}
<form name="addToShoppingBag" id="addToShoppingBag" >
<input type="hidden"
form="addToShoppingBag"
id="selectedProductRef"
name="selectedProductRef"
value="${selectedCart.productReference}">
<input type="button"
form="addToShoppingBag"
name="addToCart"
id="addToCart"
onclick="addProductToCart()"
class="css-button primary"
value="ADD TO SHOPPING BAG">
</form>
Here's a nice blog post on why to move away from using inline javascript.
You might want to consider using jQuery as a way to facilitate going to a more event-driven scripting approach. It also makes async requests pretty straight-forward with its $.ajax() method.
Here's your addProductToCart() in jQuery format:
$('body').on('click', '#addToCart', ({
var url = "/addToCart";
$.ajax({
type: "POST",
url: url,
data: '{selectedProductRef: "'+ $('#selectedProductRef').val() + '", selectedProductSize:"' + $('#selectedProductSize').val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json"
});
});
var req;
function addProductToCart(){
var url = "/addToCart";
var productReference = document.getElementById("selectedProductRef");
productReferenceValue =productReference ;
var size = document.getElementById("selectedProductSize");
sizeValue=size .value;
rm = initRequest();
rm.open("POST", url, true);
//req.onreadystatechange = callback;
rm.send("selectedProductRef="+productReferenceValue +"&selectedProductSize="+size.sizeValue);
}
function callback(){
if (req.readyState == 4) {
if (req.status == 200) {
parseMessages(req.responseText);
}
}
}
function initRequest(){
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
else if (window.ActiveXObject){
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
<!-- language: lang-html -->
<form name="addToShoppingBag" id="addToShoppingBag" >
<input type="hidden"
form="addToShoppingBag"
id="selectedProductRef"
name="selectedProductRef"
value="${selectedCart.productReference}">
<input type="button"
form="addToShoppingBag"
name="addToCart"
id="addToCart"
onclick="addProductToCart()"
class="css-button primary"
value="ADD TO SHOPPING BAG">
</form>
<!-- end snippet -->
A little change in your code instead of req = initRequest(); just call initRequest()
var size = document.getElementById("selectedProductSize");
initRequest();
req.open("POST", url, true);
initRequest() does not return any value.
i have an input text , and i want when i click in a button it takes that value and pass it in a parameter in a url , this is my code so far :
<div id="landmark-1" data-landmark-id="1">
<form name ="data">
<label>enter your name :</label>
<input type= "text" placeholder="ID" name="ID" value="" style="width:206px;" />
<input type="submit" value="Suivant" onclick="showUser(this.form)" >
</form>
</div>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
and this is my javascript code :
<script>
function showUser(frm)
{
var str = frm.ID.value;
if (str==""){
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://localhost/filename/page.php?q="+str,true);
xmlhttp.send();
}
</script>
but when i enter a name, it just add : ?ID=name in the url of the current page ! it doesn't send the parameter in the url i want ..
Change your code from: onclick="showUser(this.form)" to onclick="return showUser(this.form)"
and
if (str==""){
document.getElementById("txtHint").innerHTML="";
return;
}
to
if (str==""){
document.getElementById("txtHint").innerHTML="";
return false;
}
Your form is being submitted even if there is no ID entered. The return false prevents the form submission.
Here is a revised AJAX call. It is a bit more complicated than the w3schools example but it is more functional and complete. First the AJAX routine:
function AJAX( url, processFunction ) {
var XHR;
try{
// Opera 8.0+, Firefox, Safari/Chrome
XHR = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
XHR = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
XHR = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser doesn't support AJAX!");
return false;
}
}
}
if( XHR.onreadystatechange ) {
if( XHR.readyState == 4 ) {
if( XHR.status == 200 ) {
//--- we've got the data so process it
processFunction( XHR.responseText );
}
if( XHR.status != "OK" ) {
alert( 'Error : '+XHR.responseText);
}
}
}
//--- open
XHR.open( 'GET', url ); // --- url is from the function call
//--- send
XHR.send();
}
Now the function that will handle the returned data. In this case you simply want to display the text:
function processMyData( data ) {
document.getElementById("txtHint").innerHTML= data;
}
Now for the modified showUser function
function showUser(frm) {
var str = frm.ID.value;
if (str==""){
document.getElementById("txtHint").innerHTML="";
return false;
} else {
AJAX( "http://localhost/filename/page.php?q="+str, 'processMyData' )
}
}
If there is an error in you php file it should show up in the alert box.
If your code still isn't returning anything and there is no error the only other thing that I can think of is that you are not echo/print-ing your data for the AJAX routine to retrieve your text.
i am trying to auto submit form when the input reaches 7 characters. i have tried few java script codes, but it is spoiling my script functioning.
can any one please help me in this.....
<script type="text/javascript">
var url = "GetCustomerData.php?id="; // The server-side script
function handleHttpResponse() {
if (http.readyState == 4) {
if(http.status==200) {
var results=http.responseText;
document.getElementById('divCustomerInfo').innerHTML = results;
}
}
}
function requestCustomerInfo() {
var sId = document.getElementById("txtCustomerId").value;
http.open("GET", url + escape(sId), true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
function getHTTPObject() {
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject){
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (!xmlhttp){
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
}
return xmlhttp;
}
var http = getHTTPObject(); // We create the HTTP Object
</script>
<form id="form_home">
<p>Enter customer ID number to retrieve information:</p>
<p>Customer ID: <input type="text" maxlength="7" id="txtCustomerId" value="" /></p>
<p><input type="submit" value="Submit" onclick="requestCustomerInfo()" /></p>
</form>
<div id="divCustomerInfo"></div>
Here is the code that will submit the form when the text box reaches 7 chars:
document.getElementById('txtCustomerId').addEventListener('keyup', function(e) {
if(this.value.length === 7) {
document.getElementById('form_home').submit();
}
});
Here is a demo of it working:
http://jsfiddle.net/TuVN2/1/
Looking at your markup, I guess you want to run requestCustomerInfo() and not submit. If you submit the response will never be handled. To do this you would move the function call into the keyup handler:
document.getElementById('txtCustomerId').addEventListener('keyup', function(e) {
if(this.value.length === 7) {
requestCustomerInfo();
}
});
I would also not recommend hand rolling your ajax handler. Consider using a library like jQuery.