JavaScript form submit to database using Ajax and Laravel route - javascript

I'm making a quiz website using Laravel, Javascript and Ajax and I made an add form function with JavaScript like this:
But I want to send the form data (to create a new quiz question) into my Laravel QuizController route using Ajax, after the focus on the form is lost or after an enter..
But I can't figure out how to do it.
My JavaScript/Ajax:
var limit = 1;
var count = 0;
var myButton = document.getElementById('myButton');
var container = document.getElementById('container');
function createQuestion() {
if(count < limit) {
var input = document.createElement("input");
input.type = 'text';
input.id = '';
input.setAttribute('class', 'form-control')
container.appendChild(input);
count++;
}
else {
alert ('Enter this question first before you can add another question!');
}
}
function storeQuestion() {
var xmlhttp;
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)
{
//
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
My Laravel.blade:
<div class="form-group">
<div id="container"></div>
</div>
{!! Form::button('Add Quiz', array('onclick' => 'createQuiz()', 'class' => 'btn btn-default', 'id' => 'myButton', 'value' => 'Add question')) !!}
My QuestionController:
public function store(Quiz $quiz)
{
$input = Input::all();
$input['quiz_id'] = $quiz->id;
Question::create($input);
return Redirect::route('quizzes.show', $quiz->slug)->with('message', 'Question created.');
}
I hope someone can help me because I'm pretty stuck up with this problem for some time..

To use AJAX instead of standard HTTP POST you should catch enter and blur events.
How to catch enter is explained in first answer to input type text and onKeyDown not working under IE but in test for enter you should run storeQuestion
to add blur add :
<input type="text" name="item_code" onkeydown="test(event)" onblur="storeQuestion()">
Your store function should not return a Redirect::route but some status code or JSON string. If you use laravel 4 http://laravel.com/api/4.1/Illuminate/Http/JsonResponse.html that would just say "OK" or true or error
You should modify storeQuestion to add the new answer/edit/delete buttons to the list also. ( // )
A simpler way would be to not use AJAX but just submit the form with javascript after focus is lost by attaching an onblur event handler to the textbox.

var req = new XMLHttpRequest();
queryString = "access_token=" + access_token + "&data=" + data;
req3.open('GET', '/path/of/laravel/route?' + queryString, true);
req3.send(queryString)

Related

Get HTML id with JQuery through AJAX

I'm stuck..I have made a system which gets all colleges from a specific subject, and I want javascript to select the college the user has selected when he clicks on one so the presence of that class can be shown, just a summary: the user selects a subject, an AJAX request gets all colleges from that subject and another AJAX request has to get that specific college and use it to display the data.
This specific function gets the data from the subjects and displays them in a div with the id 'colleges'
function showAanwezigheid(str) {
if (str == "") {
document.getElementById("colleges").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 (this.readyState == 4 && this.status == 200) {
document.getElementById("colleges").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","../controller/docentController.php?action=getColleges&vak="+str,true);
xmlhttp.send();
}
}
Here is the controller which calls the query and displays the result:
$vak = $_GET['vak'];
$colleges = $q->getColleges($vak);
echo "<select id='college'>";
echo "<option>Selecteer een college:</option>";
foreach($colleges as $college){
echo "<option value='".$college->getCollege()."'>College ".$college->getCollege()."</option>";
}
echo "</select>";
}
This is the id where the result is being displayed
<span id="colleges"></span>
And this function should select the 'select' tag with the id 'college' to get that value on change
$(document).ready(function(){
$('#vak').on('change', function() {
var vak = this.value;
alert(vak);
$('#college').on('change', function() {
var college = this.value;
alert(college);
});
});
});
I feel like there would be such an easy fix but I just can't seen to make it work...
Change jQuery code like below:-
$(document).on('change','#vak',function() {
var vak = $(this).val();
alert(vak);
});
$(document).on('change','#college',function() {
var college = $(this).val();
alert(college);
});
Note:- Make sure that jQuery library added before your script code. Otherwise you will get $ is undefined error
This is called Event Delegation
IF you want to get the value of the #college select on change then this would be simpler:
$(document).ready(function(){
$('#vak').on('change', function() {
var vak = $(this).val();
alert(vak);
});
$('#college').on('change', function() {
var college = $(this).val();
alert(college);
});
});
IF you noticed, The onchange of the #vak and the #college is separated

Ajax Javascript function not being called

First question on StackOverflow so I hope i get this right. I have a AJAX call to a JS function :
function addOptionText(str)
{
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("0").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","AddText.php?q="+str,true);
xmlhttp.send();
}
And Here is my HTML code :
<body>
<FORM NAME ="form6" onclick= "addOptionText(this.value)" >
Text Input:
<INPUT TYPE = "TEXT" VALUE placeholder ="Nume Field" NAME ="Text_Field">
<INPUT TYPE = "Submit" Name = "Edit" VALUE = "Add" >
</FORM>
<p id="0"> </p>
</body>
The php file only contains :
<html>
<body>
<?php
$name = ($_GET['q']);
echo "nume";
?>
</body>
</html>
But the function doesn't appear to be used as the paragraph doesn't change. New to php here and trying to understand how it works so I'm thinking something might've slipped me.
EDIT
I had more than one "submit" id's so that's why it didn't work. I changed the "submit" id from to and now all's working as intended.
Unfortunately, your code is all over the place.
<FORM NAME ="form6" onclick= "addOptionText(this.value)" > is wrong for a multitude of reasons.
First, we don't use onclick on the form itself but on the submit button. Secondly the value you put in the parameter doesn't in any way represent the value of the text box.
Since you want just to display the value of your textbox and not to navigate to a different page, modify your <form> tag, so that it doesn't have an action = "some page" attribute, because that way it will automatically redirect you to the page you specify and thus the AJAX request is rendered useless. Instead, modify your tag so that it looks like this:
<form name = "form6" onsubmit = "return false;">Provided that you specify your input/button type to submit: type= "submit", using the onsubmit event and setting it to return false will prevent the form from sending you over to a new page.
When using Vanilla JavaScript and not jQuery, I believe its more efficient to use IDs, so as to identify your HTML elements easier in JavaScript.
Your PHP code doesn't mean anything at all. Before doing anything else, you need to evaluate if, indeed, the q was sent over to the PHP file with the GET method. To do that, use in your php file:if (isset($_GET["q"])): // Your codeendif;
The line: echo "nume" you wrote will output "nume" regardless of what you have actually sent to your php file with the AJAX request.
In my opinion is pretty useless to still provide support for Internet Explorer 5 and 6. Not many people use it, unless for whatever reason they are mentally bound to it.
Analytically, how your files should be:
HTML:
<body>
<form name = "form6" onsubmit = "return false;">
Text Input:
<input type = "TEXT" placeholder ="Nume Field" id = "textfield" name = "Text_Field"/>
<input id = "submit" type= "submit" Name = "Edit" value= "Add"/>
</form>
<p id = "0"> </p>
<script src = "YOUR JAVASCRIPT FILE" type = "text/javascript"></script>
</body>
JavaScript:
var textfield = document.getElementById("textfield");
var submit = document.getElementById("submit");
submit.onclick = function() {
'use strict';
var xmlhttp;
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("0").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "AddText.php?q=" + textfield.value, true);
xmlhttp.send();
};
PHP:
<?php
if (isset($_GET["q"])):
echo ($_GET["q"]);
endif;
?>

HTML forms - need a js/php combo capability

I have two dropdown lists. Both are to be filled by PHP via a mysql query. My problem is I want the form to be responsive if these list selections change. For instance, I need to populate the second list via another query based upon the selection of the first list.
Problem is: I need "on_change" to POST the form data AND to trigger PHP instead of Javascript.
Is there a way to collect that selection in Javascript and then send it to PHP and then refill the form? Hope I'm making myself clear.
Thanks,
Dana
Use Javascript to detect a change of the list. When a change occurs, you can make an AJAX request using a PHP script to return a new list. Javascript can manipulate the new data set and replace the DOM with the new appropriate list.
<script type=\"text/javascript\">
function changeCountry(){
var e = document.getElementById(\"country_id\");
var country_id = e.options[e.selectedIndex].value;
if(country_id == 1){
// Display states
document.getElementById('display_province').style.display = \"none\";
document.getElementById('display_state').style.display = \"\";
document.getElementById('display_state').style.visibility = \"visible\";
}
else{
// Display Province
document.getElementById('display_state').style.display = \"none\";
document.getElementById('display_province').style.display = \"\";
document.getElementById('display_province').style.visibility = \"visible\";
// Remove current selection list
var select = document.getElementById('province_id');
for (var option in select){
select.remove(option);
}
// Get Provinces for country_id
var xmlhttp = new XMLHttpRequest();
// Include fix for IE6 and IE5
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) {
var xmlDoc = xmlhttp.responseXML;
// get each property
var x=xmlDoc.getElementsByTagName('province');
for (i=0;i<x.length;i++)
{
var e = document.getElementById('province_id');
var opt = document.createElement('option');
opt.value = x[i].getElementsByTagName('zoneid')[0].textContent;
opt.innerHTML = x[i].getElementsByTagName('zone')[0].textContent;
e.appendChild(opt);
}
}
}
var url = 'get_provinces.php?country_id='+country_id;
// var url = 'provinces.xml';
xmlhttp.open('GET',url,false);
xmlhttp.setRequestHeader(\"Content-type\", \"text/xml\");
xmlhttp.send();
}
}
function changeShippingCountry(){
var e = document.getElementById(\"shipto_country_id\");
var shipto_country_id = e.options[e.selectedIndex].value;
if(shipto_country_id == 1){
// Display states
document.getElementById('shipto_display_province').style.display = \"none\";
document.getElementById('shipto_display_state').style.display = \"\";
document.getElementById('shipto_display_state').style.visibility = \"visible\";
}
else{
// Display Province
document.getElementById('shipto_display_state').style.display = \"none\";
document.getElementById('shipto_display_province').style.display = \"\";
document.getElementById('shipto_display_province').style.visibility = \"visible\";
// Remove current selection list
var select = document.getElementById('shipto_province_id');
for (var option in select){
select.remove(option);
}
// Get Provinces for country_id
var xmlhttp = new XMLHttpRequest();
// Include fix for IE6 and IE5
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) {
var xmlDoc = xmlhttp.responseXML;
// get each property
var x=xmlDoc.getElementsByTagName('province');
for (i=0;i<x.length;i++)
{
var e = document.getElementById('shipto_province_id');
var opt = document.createElement('option');
opt.value = x[i].getElementsByTagName('zoneid')[0].textContent;
opt.innerHTML = x[i].getElementsByTagName('zone')[0].textContent;
e.appendChild(opt);
}
}
}
var url = 'get_provinces.php?country_id='+shipto_country_id;
// var url = 'provinces.xml';
xmlhttp.open('GET',url,false);
xmlhttp.setRequestHeader(\"Content-type\", \"text/xml\");
xmlhttp.send();
}
}
function addProvince(){
// Get input
var np = document.getElementById('new_province').value;
// Get country_id
var e = document.getElementById(\"country_id\");
var country_id = e.options[e.selectedIndex].value;
// Erase input
document.getElementById('new_province').value = \"\";
// Add to database
var xmlhttp = new XMLHttpRequest();
// Include fix for IE6 and IE5
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) {
var xmlDoc = xmlhttp.responseXML;
}
}
var url = 'add_provinces.php?province='+np+'&country_id='+country_id;
xmlhttp.open('GET',url,false);
xmlhttp.setRequestHeader(\"Content-type\", \"text/xml\");
xmlhttp.send();
changeCountry();
changeShippingCountry();
}
function addShippingProvince(){
// Get input
var np = document.getElementById('shipto_new_province').value;
// Get country_id
var e = document.getElementById(\"shipto_country_id\");
var country_id = e.options[e.selectedIndex].value;
// Erase input
document.getElementById('shipto_new_province').value = \"\";
// Add to database
var xmlhttp = new XMLHttpRequest();
// Include fix for IE6 and IE5
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) {
var xmlDoc = xmlhttp.responseXML;
}
}
var url = 'add_provinces.php?province='+np+'&country_id='+country_id;
xmlhttp.open('GET',url,false);
xmlhttp.setRequestHeader(\"Content-type\", \"text/xml\");
xmlhttp.send();
changeShippingCountry();
changeCountry();
}
function hideShipping(){
document.getElementById('shipping').style.display = \"none\";
document.getElementById('shipping').style.visibility = \"hidden\";
}
function displayShipping(){
document.getElementById('shipping').style.display = \"\";
document.getElementById('shipping').style.visibility = \"visible\";
}
You can make an ajax call to an endpoint you set up that runs some php code and returns some JSON that your javascript can then use to populate the second list. Your javascript would look something like:
$.ajax( "your-endpoint.php" )
.done(function(data) {
// use javascript to dynamically populate your list
var json = data;
//assuming data is a list you could iterate over it
$.each(data, function (k, v) {
//use this to populate your list
}
})
.fail(function() {
// show an error message on your form
});
Your PHP endpoint would have to return a JSON object so that your javascript can more easily use it.
Communcation betwen php and javascript is typically done by Ajax, which is very simple to use in jQuery. The basic syntax is something like this:
$.ajax({
type: "POST",
url: "yourFile.php",
data: "{data: " + yourData + "}", //yourData is javascript variable
success: function(result){
//do something with result from php file
}
});
Where variable yourData is what you want to send to php script and it would be accessible throught $_POST['data'].
Everyone answered that Ajax is the solution, and I agree, Ajax is more elegant, but Ajax is not the only solution. I post this answer only to show another way to do it : without Ajax.
The first code (combos.php) is the page with a combo that, when selected, calls PHP. The second code (combos_action.php) is the PHP that returns the values according to the option selected. To make this codes to work, create two text files with the given names, copy-paste the codes and run it from your browser with http://localhost/combos.php. If you change the filenames, change them in the code, also.
Here is how it works : the page shows a simple combo filled with the days of the week. When a day is selected the JavaScript's onchange event fires and the form is autosubmitted, PHP gets the selected day and stores some values in session, returns to the page that refreshes and fills the second combo with those values. Comments will help you to understand:
combos.php
<?php
session_start(); // NECESSARY TO RETRIEVE THE VALUE RETURNED FROM PHP.
?>
<html>
<head>
<title>By José Manuel Abarca Rodríguez</title>
<script type="text/javascript">
// AUTOSUBMIT FORM #1 WHEN ANY OPTION IN COMBO #1 IS SELECTED.
function combo1_selected () {
document.getElementById( "form1" ).submit();
}
</script>
</head>
<body>
<!-- THIS IS COMBO #1. -->
<form id="form1" method="post" action="combos_action.php">
Select a day
<br/>
<select name="combo1" onchange="combo1_selected()"> <!-- NOTICE THE EVENT! -->
<option>Monday</option>
<option>Tuesday</option>
<option>Wednesday</option>
</select>
</form>
<?php
// DISPLAY COMBO #2 ONLY IF COMBO #1 WAS SELECTED.
if ( isset( $_SESSION[ "combo2" ] ) )
{ echo "<br/>" .
"<br/>" .
"Options for <b>" . $_SESSION[ "combo1" ] . "</b>" .
"<br/>" .
"<select name='combo2'>";
// SEPARATE THE OPTIONS RETURNED FROM PHP.
$options = explode( ",",$_SESSION[ "combo2" ] );
// DISPLAY THE OPTIONS FOR THE COMBO.
for ( $i = 0; $i < count( $options ); $i++ )
echo "<option>" . $options[ $i ] . "</option>";
echo "</select>";
}
?>
</body>
</html>
combos_action.php
<?php
session_start();
$_SESSION[ "combo1" ] = $_POST[ "combo1" ]; // SELECTED OPTION.
if ( $_SESSION[ "combo1" ] == "Monday" )
$_SESSION[ "combo2" ] = "mon 1,mon 2,mon 3"; // RETURN THESE VALUES.
if ( $_SESSION[ "combo1" ] == "Tuesday" )
$_SESSION[ "combo2" ] = "tue 1,tue 2,tue 3"; // RETURN THESE VALUES.
if ( $_SESSION[ "combo1" ] == "Wednesday" )
$_SESSION[ "combo2" ] = "wed 1,wed 2,wed 3"; // RETURN THESE VALUES.
header( "Location: combos.php" ); // RETURN TO PAGE.
?>

javascript dynamic content not affected when ajax call

I am new to javascript, am using PHP variable for created link dynamically as given below
$addlink = '<button class="blueBtn btnSmall" id="current'.$product_id.'" onClick=addcart('.#$product_id.',"add")><span class="allitem"
<font color="#A2F3AB">Added</font></span></button>';
This my php variable created by dynamically like below.
Added
Added
Added
I want to change the content of all variable“ added” as“ add” by just one click,Am using ajax function for changing that text as given below..
function clearcart(msg) {
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('cartreturn').innerHTML = xmlhttp.responseText;
document.getElementsByClassName('allitem').innerHTML = "Add";
}
}
xmlhttp.open("GET", "/addcart.php?msg=" + msg, true);
xmlhttp.send();
}
But first link text only affected.. other is not affected how I can solve this problem
document.getElementsByClassName returns a NodeList. You have to iterate over all the elements:
var allItems = getElementsByClassName('allitem');
for (var i = 0; i < allItems.length; i++) {
allItems[i].innerHTML = 'Add';
}
See this question.
You can't do document.getElementsByClassName('allitem').innerHTML.
You can do document.getElementsByClassName('allitem')[0].innerHTML = "Add"
Do you have several elements with the class "allitem"? If you don't, then maybe you should use an id, instead of a class, and then call document.getElementById('allitem').innerHTML = "Add";

Ajax, Javascript, Python

From a python script located at /script.py, I want to see storeNum on the html page.
def testpost(storeNum):
storeNum = int(storeNum) + 1
return storeNum
Then on the html page I have JScript
function create_xml_http() {
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
var xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
alert("This page does not support Internet Explorer. Please open in another\\
browser.")
}
return xmlhttp;
}
function sendStoreNum() {
var storeValue = +document.getElementById('strNum').value;
if (storeValue == '') {
return;
}
var sendStoreNum.onreadystatechange = create_xml_http();
var url = 'home/jholstine/workspace/oreilly/sqltest.py/testpost'
if (storeValue >= 1) {
alert('made it to post');
sendStoreNum.open('POST', url, true);
} else {
alert('You have enter a text instead of a number!');
sendStoreNum.send();
storeValue.value = '';
return
}
}
I can't seem to get these two to talk. I just want to enter the number into a text box and hit enter. Then have it send back the store number plus 1. Can someone please help make these to talk?

Categories