AJAX call to PHP not returning value - javascript

I have 3 files linked together index.php functions.js and compute.php
index.php has a div that calls a function in functions.js: compute() that sends an AJAX request to do something in compute.php
index.php:
<form id = "input_form">
<textarea name = "row" id = "inputform" placeholder="Input row here"></textarea>
<input type = "submit" value = "Enter" onclick="compute(inputform.value);">
</form>
<div id = "output_container">
<p id = "output"></p>
</div>
When the button is pressed, compute() is called passing in whatever was in the textarea as data.
function compute(row){
var xhttp;
if(window.XMLHttpRequest){
xhttp = new XMLHttpRequest();
}
else{
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4) {
output.innerHTML = xhttp.responseText;
}
};
xhttp.open("GET","compute.php?row="+row,true);
xhttp.send(null);
}
This passes the value into a php script which simply is suppose to output what was in the textarea into #output
<?php
$str = $_GET['row'];
echo $str;
?>
When I test my program by clicking the button, nothing happens indicating something went wrong. I tried to pinpoint the problem by adding a window.alert('something'); after the check if(xhttp.readyState == 4) but a popup box never appears, making it seem like the issue is between functions and compute.
I tested out phpinfo(); and it looks like php is working properly on my server as well

Problem: Form is getting submitted without making ajax call, because your code contains type='submit'
Solution: Change type to button:
<input type = "button" value = "Enter" onclick="compute(inputform.value);">
Also update code to fetch the output properly:
if (xhttp.readyState == 4) {
document.getElementById("output").innerHTML = xhttp.responseText;
}

Related

Ajax To PHP converter get value from ajax

i need help, here my code :
<html>
<head>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "getstok.php?secretkey=123&sku=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<p><b>Masukkan kode barang / SKU:</b></p>
<form>
Kode Barang: <input type="text" onkeyup="showHint(this.value)">
</form>
<div id="txtHint"></span>
</body>
</html>
What I need is:
I want to hide this "secretkey=123" so visitor cannot see my secret key
when call "xmlhttp.send();" return the value and I want to convert it to php like example
$getxmlhttp = xmlhttp.send();
when I type something it will be call function, but when I press enter that refresh, how to disable the enter or what the best suggestion for me.
this is my site sample:
http://stok.tk
for example type "YI 067"
1 : You can't. The browser (and so the visitor) can always know wich page is called with wich URL and parameters
2 : You can't do it like that. You need to get the value of your request into getstok.php with the super global variables $_GET['your var']
3 : It's reloading the page because it's sending your form. By default it send it to the same page. Just remove your <form>

How to check if a session is empty using javascript inside php

Also, how do i unset the session through javascript?
I have made this code with PHP:
if(isset($_SESSION) && !empty($_SESSION)) {
unset($_SESSION['Plan1']);
unset($_SESSION['excel_array']);
$_POST['excel_name']['Main'] = "Main".date("y_m_d_Hi");
$_POST['excel_array']['Main']['Plan1'] = array();
}
else{
$_SESSION['excel_name']['Main'] = "Main".date("y_m_d_Hi");
$_SESSION['excel_array']['Main']['Plan1'] = array();
}
So here i check if there is a session. If there is, i unset it and send the $_POST data instead. however, if there isn't one, i create it.
The problem is, i might want to call this on a button click. How would i make a code with the same functionality, but using a javascript function?
Put your php in a file on its own, called set_session.php for example:
<?php
session_start();
unset($_SESSION['Plan1']);
echo 'unset';
?>
Call it in javascript:
<script>
function unset() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").innerHTML = this.responseText;
}
};
xhttp.open("GET", "set_session.php", true);
xhttp.send();
}
</script>
<button type="button" onclick="unset()">Unset</button>
<div id="result"></div>

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;
?>

JSP Chat - How I can parse the value from HTML to JSP page?

I have to make a chat with JSP, AJAX and Java and I have a problem: when I try to use my variable to store value of a input text, this variable is null.
If I add 'action' property to the form, the variable 'textParam' will have the value of the input text, but, if I do that I have to redirect with action to a page and I don't what that.
I need to process something bigger in the JSP page and then to reload in the HTML page (which is a JSP page) (the reload part is not on actual probem).
How I can make to populate 'textParam' with the input text value when I press the button?
PS: I need to make it with pure javascript, not with some libraries :)
The JSP which have to process is:
String textParam = request.getParameter("chatMessage");
System.out.println("textParam = " + textParam);
My form it look like that:
<form id="frmmain" name="frmmain" onsubmit="return blockSubmit();">
<input type="text" id="chatMessage" name="chatMessage" style="width: 447px;" />
<input type="button" name="btn_send_chat" id="btn_send_chat" value="Send" onclick="sendChatText();" />
</form>
The .js file it's this:
var request = getXmlHttpRequestObject();
var response = getXmlHttpRequestObject();
var lastMessage = 0;
var mTimer;
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function sendChatText() {
if(document.getElementById('chatMessage').value == '') {
alert("You have not entered a message");
return;
}
if (request.readyState == 4 || request.readyState == 0) {
request.open("POST", 'getChat2.jsp?chat=1&last=' + lastMessage, true);
request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
request.onreadystatechange = handleSendChat;
var param = 'message=' + document.getElementById('chatMessage').value;
param += '&chat=1';
request.send(param);
document.getElementById('chatMessage').value = '';
}
}
function handleSendChat() {
clearInterval(mTimer);
getChatText();
}
function blockSubmit() {
sendChatText();
return false;
}
The problem is here:
String textParam = request.getParameter("chatMessage");
I was trying to get 'chatMessage' parameter, which it was only the name of the input. The solve is to get 'message' param which it was defined and requested in js:
String textParam = request.getParameter("message");

Javascript code for handling Form behaviour

Here's how the situation looks :
I have a couple simple forms
<form action='settings.php' method='post'>
<input type='hidden' name='setting' value='value1'>
<input type='submit' value='Value1'>
</form>
Other small forms close to it have value2, value3, ... for the specific setting1, etc.
Now, I have all these forms placed on the settings.php subpage, but I'd also like to have copies of one or two of them on the index.php subpage (for ease of access, as they are in certain situations rather frequently used).
Thing is I do not want those forms based on the index.php to redirect me in any way to settings.php, just post the hidden value to alter settings and that's all.
How can I do this with JS ?
Cheers
Yes, you could use an ajax call to send a request to the settings.php file. You'd probably want that PHP code to return something that the JavaScript can use to know if the request was successful or not (for example, using JSON instead of HTML).
Here is an ajax getData function.
function getData(dataSource, targetDiv){
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new
ActiveXObject("Microsoft.XMLHTTP");
}
if(XMLHttpRequestObject) {
var obj = document.getElementById(targetDiv);
XMLHttpRequestObject.open("GET", "settings.php?form="+dataSource+"&t="+new Date().getTime());
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
use this function to send the form to your setting.php file which should return confirmation message to index.php(inside targetDiv).
Parameters of the function
1) dataSource - is the variable value that you send to settings.php
2) targetDiv - is the div on index php that with display the response from settings.php
Hope it makes sense.

Categories