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.
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 :)
<script>
function postComment() {
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("commentHint").innerHTML = xmlhttp.responseText;
}
var comment = document.getElementById("comment").value;
var id = document.getElementById("postID").value;
xmlhttp.open("POST", "commentpost.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("comment=" + comment + "&postID=" + id);
}
}
</script>
<form>
<div id="comment">
<textarea name="comment" id="comment" rows="4" cols="125" style="max-width: 950px; max-height: 140px;" placeholder="<?php echo $_SESSION["name"] ?>, Write Your Comment Here" class="form-control"></textarea><br>
<div id="commentHint"></div>
<input type="submit" onclick="postComment()" value="Submit Comment" class="btn btn-success btn-sm ">
<input type="hidden" id="postID" name="postID" value="<?php echo $post_id ?>">
</div>
</form>
I have no idea why my AJAX POST request isn't working...
Here's the POST vars in my corresponding PHP FILE:
$comment = $_POST["comment"];
$postID = $_POST["postID"];
When ever I click the submit comment button it refreshes the page first and bring me back to the home page. It does not fire the php script either.. I'm new to AJAX can someone please tell me what's wrong
Your xmlhttp.send(...) call is within the onreadystatechange handler, for the handler method to get called you need to send the request so the ajax method is never executed.
The code that is responsible to send the request should be outside of the handler method.
function postComment() {
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("commentHint").innerHTML = xmlhttp.responseText;
}
}//need to close onreadystatechange here
var comment = document.getElementById("comment").value;
var id = document.getElementById("postID").value;
xmlhttp.open("POST", "commentpost.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("comment=" + comment + "&postID=" + id);
}
Note: If you use proper code indentation this kind of issues can be easily avoided.
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
I have data on a website which looks like this
[{"id":213877,"pic":"https://graph.facebook.com/ariel.barack/picture?type=square","url":"https://angel.co/ariel-barack","name":"Ariel Barack","type":"User"},{"id":109396,"pic":"https://d1qb2nb5cznatu.cloudfront.net/users/109396-medium_jpg?1405528556","url":"https://angel.co/mattbarackman","name":"Matt Barackman","type":"User"},{"id":881384,"pic":null,"url":"https://angel.co/austin-barack","name":"Austin Barack","type":"User"},{"id":245752,"pic":null,"url":"https://angel.co/drgoddess","name":"Dr. Goddess","type":"User"}]
I have a html file with javascript code as follows:
function httpGet(url) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", url, false );
xmlHttp.send( null );
var data = xmlHttp.responseText;
data = (JSON.parse(data));
I need to access the "name" attribute from the URL database and form a string concat of all the name attributes. Could you please help me out what to be done next?
Below is my test data
var data = '{"name": "mkyong","age": 30,"address": {"streetAddress": "88 8nd Street","city": "New York"},"phoneNumber": [{"type": "home","number": "111 111-1111"},{"type": "fax","number": "222 222-2222"}]}';
var json = JSON.parse(data);
alert(json["name"]); //mkyong
alert(json.name);
For Example if you want to acces the name you can access as like above.
To concatenate the vales do like below
var Output = json.map(function(result) {
return result.name;
}).join('');
alert(Output);
Have a look on it https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
var result = data.map(function(user) {
return user.name;
}).join('');
<html>
<head>
<script type="text/javascript">
function fun(){
var str='[{"id":213877,"pic":"https://graph.facebook.com/ariel.barack/picture?type=square","url":"https://angel.co/ariel-barack","name":"Ariel Barack","type":"User"},{"id":109396,"pic":"https://d1qb2nb5cznatu.cloudfront.net/users/109396-medium_jpg?1405528556","url":"https://angel.co/mattbarackman","name":"Matt Barackman","type":"User"},{"id":881384,"pic":null,"url":"https://angel.co/austin-barack","name":"Austin Barack","type":"User"},{"id":245752,"pic":null,"url":"https://angel.co/drgoddess","name":"Dr. Goddess","type":"User"}]';
var obj=eval(str);
var names='';
for(var item in obj){
names+=obj[item].name;
}
alert(names);
}
</script>
</head>
<body>
<input type="button" onclick="fun()" value="click me"/>
</body>
</html>
I got what you mean.It is the Ajax problem.If you really use the code that you provided,it should not work.Here is the Ajax code to get response from a certain url:
var ajaxRequest;
//create ajax object
function createAjaxRequest() {
var xmlhttp = null;
if (window.XMLHttpRequest) {// code for all new browsers
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {// code for IE5 and IE6
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
//send request and identify callbak handler
function send(url) {
ajaxRequest = createAjaxRequest();
ajaxRequest.onreadystatechange = callback;
ajaxRequest.open("POST", url, true);
ajaxRequest.send(null);
}
// the callback handler
function callback() {
if (ajaxRequest.readyState == 4) {// 4 = "loaded"
if (ajaxRequest.status == 200) {// 200 = OK
var data = ajaxRequest.responseText;
}
else {
alert("Problem retrieving data");
}
}
}
We are using http://jscolor.com (JavaScript Color picker) without any problem normally. But when we create the input element by AJAX, it don't work correctly and jscolor.js can not detect class (color) of the input, while the input show correctly. What we should do?
The HTML code is:
<html>
<head>
<script src='/js/jscloro.js'></script>
<script>
function showHint(str)
{
if (str.length==0)
{
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","gethint.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
FORM
<div id="txtHint"></div>
</body>
</html>
Our PHP response to ajax is:echo "<input class=\"color\" type=\"text\" value=\"66ff00\">";
I think, when you create new DOM element after documentload, you should bind the event's after where you create that's element.
UPDATED PART OF ANSWER
See this html and script:
<div id="container"></div>
$(document).ready(function () {
// if you add the event for element that currenlty not exist on
// page, and later may be created, the even cannot fired
$('#elem').click(function () {
alert('You are clicked on input!');
});
$.ajax({
url: 'somePage.aspx',
type: 'POST',
contentType: 'application;json/ charset=utf-8',
dataType: 'json',
data: {},
success: function (msg) {
// if you create your own element here
$('#container').append(function () {
return $('<span>')
.text('This Is New Element')
.attr('id', '#elem');
});
}
});
});
But the correct way is to add event after where DOM element is created, as you see below:
$(document).ready(function () {
$.ajax({
url: 'somePage.aspx',
type: 'POST',
contentType: 'application;json/ charset=utf-8',
dataType: 'json',
data: {},
success: function (msg) {
// if you create your own element here
$('#container').append(function () {
return $('<span>')
.text('This Is New Element')
.attr('id', '#elem')
.click(function () { // you should bind your events here
alert('You are clicked on input!');
});
});
}
});
});
UPDATED PART 2
you should initialize the new jscolor instance, for example use this code
new jscolor.color($('.color'), {});
after you created your own element.
UPDATED PART 3
<html>
<head>
<script src='/js/jscloro.js'></script>
<script>
function showHint(str) {
if (str.length == 0) {
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;
/* YOU SHOULD INITIALIZE THE NEW JSCOLOR INSTANCE HERE */
var myPicker = new jscolor.color(document.getElementById('myField1'), {})
myPicker.fromString('99FF33') //
/**/
}
}
xmlhttp.open("GET", "gethint.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
FORM
<div id="txtHint"></div>
</body>
</html>
Please mark it as answer if it helped you.