Ajax, Javascript, Python - javascript

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?

Related

Disable a radio button after confirm

I tried to research and tried many options but still not working. After the user click the radio button and confirm it i need to disable the radio buttons
<script type="text/javascript">
function getVote(int) {
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (confirm("Your vote is for " + int)) {
xmlhttp.open("GET", "save.php?vote=" + int, true);
xmlhttp.send();
window.location.reload();
} else {
alert("Choose another candidate ");
}
}
function getPosition(String) {
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "vote.php?position=" + String, true);
xmlhttp.send();
}
</script>
and this is the radio button that the user will click
echo "<td><input type='radio' name='vote' value='$row[candidate_name]' onclick='getVote(this.value)' /></td>";
this is save.php when the user click the radio button
<?php
require('connection.php');
$vote = $_REQUEST['vote'];
$checkposition=mysql_query("SELECT candidate_position FROM voting_tbCandidates WHERE candidate_name='$vote'");
while ($row=mysql_fetch_array($checkposition)){
session_start();
if($row['candidate_position']=="PRESIDENT"){
$_SESSION['vote_president']=$row['candidate_position'];
}elseif($row['candidate_position']=="VICE"){
$_SESSION['vote_vice']=$row['candidate_position'];
}elseif($row['candidate_position']=="MUSE"){
$_SESSION['vote_muse']=$row['candidate_position'];
}elseif($row['candidate_position']=="SECRETARY"){
$_SESSION['vote_secretary']=$row['candidate_position'];
}elseif($row['candidate_position']=="ESCORT"){
$_SESSION['vote_escort']=$row['candidate_position'];
}elseif($row['candidate_position']=="AUDITOR"){
$_SESSION['vote_auditor']=$row['candidate_position'];
}
}
mysql_query("UPDATE voting_tbCandidates SET candidate_cvotes=candidate_cvotes+1 WHERE candidate_name='$vote'");
mysql_close($con);
?>
You are sending just the value back to the function. It would be easier to send the whole element to the function and pick out the parts that you need. For example:
Change
onclick='getVote(this.value)'
to
onclick='getVote(this)'
Change
function getVote(int)
to
function getVote(obj) {
var int = obj.value;
Before the xmlhttp.open("GET", "save.php?vote=" + int, true); add the line
obj.setAttribute('disabled','disabled'); // I think this would work
set disable property to true on confirm and false for else.
modified function should be look like this
function getVote(obj) {
var int = obj.value;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (confirm("Your vote is for " + int)) {
obj.disabled = true;
//xmlhttp.open("GET","save.php?vote="+int,true);
//xmlhttp.send();
// window.location.reload();
} else {
obj.disabled = false;
alert("Choose another candidate ");
}
}
and pass the object of input element during function call
<td>
<input type='radio' name='vote' value='45' onclick='getVote(this)'/>
</td>
here is working fiddle : https://jsfiddle.net6mcd5bq7/

JavaScript form submit to database using Ajax and Laravel route

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)

sending multiple data in ajax post method in jsp

function getXmlHttpRequestObject()
{
var xmlHttp = false;
if (window.XMLHttpRequest)
{
return new XMLHttpRequest(); //To support the browsers IE7+, Firefox, Chrome, Opera, Safari
}
else if(window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP"); // For the browsers IE6, IE5
}
else
{
alert("Error due to old verion of browser upgrade your browser");
}
}
var xmlhttp = new getXmlHttpRequestObject(); //xmlhttp holds the ajax object
function servletPost()
{
if(xmlhttp)
{
var comp_to = document.getElementById("comp_to").value;
var comp_subject = document.getElementById("comp_subject").value;
var comp_letter = document.getElementById("comp_letter").value;
var date_time = document.getElementById("date_time").value;
if(comp_to==""||comp_subject==""||comp_letter==""||date_time=="")
{
document.getElementById("redSignal").style.display='block';
document.getElementById("redSignal").innerHTML="All Fields are necessary";
}
else
{
xmlhttp.open("POST","complaintHandler",true);
xmlhttp.onreadystatechange = handleServletPost;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
var data_string="to="+comp_to+"&subject="+comp_subject+"&complaint="+comp_letter+"&date_time="+date_time;
xmlhttp.send(data_string);
}
}
}
function handleServletPost()
{
if (xmlhttp.readyState == 4)
{
if(xmlhttp.status == 200)
{
document.getElementById("greenSignal").style.display='block';
document.getElementById("greenSignal").innerHTML=xmlhttp.responseText;
}
else
{
document.getElementById("redSignal").style.display='block';
document.getElementById("redSignal").innerHTML="Error Code ="+xmlhttp.status;
}
}
}
I am getting the problem of error code 404
What could be the problem in this code? Please help me.
Error 404 itself says that your URL is wrong .
xmlhttp.open("POST","complaintHandler-wrong",true);
check this URL 1st .
ERROR 404 Says. The requested Http request is not present or wrong.
Please check your "complaintHandler" It might be complaintHandler.jsp , kind of...
Please go through this tutorial for your future use.

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 div can't access address bar variable

Can someone please advise me on how my Ajax div can get an address bar variable. The usual way just doesn't work.
My address bar currently looks like this:
http://localhost/social3/browse/?locationName=Cambridge
Obviously, the word I'm trying to access here is 'Cambridge'. Usually, I would use a little php and do this:
$searchResult = $_POST['locationName'];
echo $searchResult;
But because I'm in an Ajax div, I can't seem to get to the variable.
Do I need to add some JavaScript wizardry to my Ajax coding? (I have little knowledge of this)
My Ajax:
<script>
window.onload = function () {
var everyone = document.getElementById('everyone'),
searching = document.getElementById('searching'),
searchingSubmit = document.getElementById('searchingSubmit');
everyone.onclick = function() {
loadXMLDoc('indexEveryone');
everyone.className = 'filterOptionActive';
searching.className = 'filterOption';
}
searching.onclick = function() {
loadXMLDoc('indexSearching');
searching.className = 'filterOptionActive';
everyone.className = 'filterOption';
}
searchingSubmit.onclick = function() {
loadXMLDoc('indexSearchingSubmit');
}
function loadXMLDoc(pageName)
{
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("leftCont").innerHTML=xmlhttp.responseText;
}
}
function get_query(){
var url = location.href;
var qs = url.substring(url.indexOf('?') + 1).split('&');
for(var i = 0, result = {}; i < qs.length; i++){
qs[i] = qs[i].split('=');
result[qs[i][0]] = decodeURIComponent(qs[i][1]);
}
return result;
}
xmlhttp.open("GET","../browse/" + pageName + ".php?user=" + get_query()['user'],true);
xmlhttp.send();
}
}
</script>
<!-- ends ajax script -->
If your url contains the variable, you should use $_GET["key"] instead of $_POST
alternatively, you can use $_REQUEST["key"] to handle both cases.

Categories