Get raw text from textarea with javascript and send it to PHP - php

I have a textarea where I put some C++ code, then I get that code with javascript and send it to a PHP script via AJAX to be processed. The problem is that the code gets corrupted in the way.
Here is my code:
function showResult()
{
var code = document.getElementById('code').value;
var input = document.getElementById('input').value;
if (code != '') {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('result').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'ideone.php?code=' + code + '&input=' + input, true);
xmlhttp.send();
}
}
PHP:
<?php
echo 'Code: '.$_GET['code']; // Empty string
?>

You need to quote your query string:
xmlhttp.open('GET', 'ideone.php?code=' + encodeURIComponent(code) + '&input=' + encodeURIComponent(input), true);

Related

Storing ajax output into variable

I have to check weather invoice number is duplicate or not for that i am using following ajax.
function check_duplicate_invoice(num){
var isDuplicate ;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","check_duplicate_invoice.php?in="+num, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
isDuplicate =xmlhttp.responseText.trim() // reponceText will be 0 or 1
}
}
alert(isDuplicate); //result undefined
if(isDuplicate== 1){
alert("Invoice Number Already Exist");
}
}
I am not able to store ajax output into isDuplicate variable. Please help.
That's because ajax calls are asynchronous. You are looking at the variable before the request has had a time to complete. Try this:
function check_duplicate_invoice(num){
var isDuplicate ;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","check_duplicate_invoice.php?in="+num, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
isDuplicate =xmlhttp.responseText.trim() // reponceText will be 0 or 1
alert(isDuplicate); //result undefined
if(isDuplicate== 1){
alert("Invoice Number Already Exist");
}
}
}
}

Getting value from file called by ajax request using json

On button click I submit the form and post some data to data.php.
Form to be submitted is:
<form action="data.php" method="POST" onsubmit="showUser(this, event)">
index.php
function showUser(form, e) {
//alert(myid);
e.preventDefault();
e.returnValue=false;
var xmlhttp;
//Get value for sent, text1, text2, text3
console.log(sent);
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(e) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
xmlhttp.responseText.resultOne; // Is this correct? Should be here? I dont know correct
xmlhttp.responseText.resultTwo;
document.getElementById("myFirstDiv").innerHTML=xmlhttp.responseText.resultOne;
document.getElementById("mySecondDiv").innerHTML=xmlhttp.responseText.resultTwo;
}
}
xmlhttp.open(form.method, form.action, true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
deURIComponent(text3);
xmlhttp.send('sent=' + sent + '&text1=' + text1 + '&text2=' + text2 + '&text3=' + text3);
}
data.php
<?php
ob_start();
echo "1:blah\n";
echo "</br>";
echo "shonice";
echo "1:blahDFDFD\n";
$div1 = ob_get_clean();
ob_start();
echo "2:blah";
echo "</br>";
echo "2:DFDFDFblah\n";
$div2 = ob_get_clean();
$resultArray = array("resultOne" => $div1,"resultTwo" => $div2);
echo json_encode($resultArray);
?>
How can I fetch json value from `data.php` into `myFirstdiv` aand `mysecondDiv`?
What's wrong with code I have created.
It show undefined value in div as a result.
lets assume that there is a result from the data.php file and it is json encoded..
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var div1=document.getElementById("myFirstDiv");
var div2=document.getElementById("mySecondDiv");
var data=JSON.parse(xmlhttp.responseText);
//alert data to see what u get..
div1.innerHTML=data['resultOne'];
div2.innerHTML=data['resultTwo'];
}
hoping this helps..

PHP: Calculate textbox value via Ajax

I'm trying to calculate text box value via ajax, on event onkeyup :
index.php
<html>
<head>
<script type="text/javascript">
function calc() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('MicrosoftXMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('myDiv').innerHTML = xmlhttp.responseText;
}
}
var text = document.getElementById('txtField').value;
var target = "calc.php";
var parameter = "txtValue=" + text;
xmlhttp.open('POST', target, true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(parameter);
}
</script>
</head>
<body>
Price: <input type="text" id="txtField" onkeyup="calc();">
<div id="myDiv"></div>
</body>
</html>
calc.php
if ($_POST['txtValue'] && !empty($_POST['txtValue'] )) {
echo $_POST['txtValue'] * 4;
}
But won't show the result. Please tell me what am i missing here ?
Try to change your calc.php like:
if (isset($_POST['txtValue']) && !empty($_POST['txtValue'] )) {
echo $_POST['txtValue'] * 4;
}
use the following to see if you are getting correct response:
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
document.getElementById('myDiv').innerHTML = xmlhttp.responseText;
}
ok hre is your problem:
use:
if (($_POST['txtValue'] != '') && !empty($_POST['txtValue'] ))
instead of:
if ($_POST['txtValue'] && !empty($_POST['txtValue'] ))
cuase $_POST['txtValue'] is not a boolean and can't be used in if condition

why error with if (xmlHttp.readyState == 4)

I earlier asked a question about a xmlHttp.send() code that wasn't working. I thought I had fixed all of it, but now I've got another problem.
In the handleServerResponse() function, the code errors out in the if (xmlHttp.readyState == 4) and if (xmlHttp.readyState == 200). Why is it doing that? An example php code is under the JavaScript.
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.ActiveXObject){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlHttp = false;
}
}else{
try{
xmlHttp = new XMLHttpRequest();
}catch(e){
xmlHttp = false;
}
}
if(!xmlHttp){
alert("cant create that object hos");
}else{
return xmlHttp;
}
}
function newuser() {
if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) {
name = encodeURIComponent(document.getElementById("name").value);
queryString = "name=" + name;
xmlHttp.open("GET", "code/php/core.php?" + queryString, true);
xmlHttp.onreadystatechange = handleServerRespons;
xmlHttp.send();
}else{
setTimeout('newuser()', 1000)
}
}
function handleServerRespons(){
if (xmlHttp.readyState == 4){
if (xmlHttp.readyState == 200){
alert('1234545');
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement=xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
alert(message);
}
}
}
php code:
$name = $_GET['name'];
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
echo $name;
echo '</response>';
instead of using a variable (xmlHttp) you must use this in an onreadystatechange event callback
so your function will be:
function handleServerRespons() {
if ( this.readyState === 4 && this.status === 200 ) { // and also use "status" here not "readyState"
xmlResponse = this.responseXML;
xmlDocumentElement=xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
alert( message );
}
}
or wrap your code with (function(){...})(); like below
(function() {
// all your code goes here, so you can use that 'xmlHttp' instead of 'this'
})();
xmlHttp.readyState can't be 200. you should use xmlHttp.status.
xmlHttp.readyState has status of the XMLHttpRequest The XMLHttpRequest Object
xmlHttp.status will be available when xmlHttp.readyState is 3 or 4. When available xmlHttp.status should represent the HTTP status code.

Changing include direction with javascript

I'm trying to change an include path with JavaScript. It need's to go from this
<?php include 'sections/welcome.php'; ?>
to this
<?php include 'sections/new_visitor.php'; ?>
to this
<?php include 'sections/nda.php'; ?>
and so on... do anybody know how to code this in JavaScript?
you can't change how PHP is coded via javascript. You can send variables to php via javascript and then PHP responds to those variables... it looks like you have a registration of sorts. If you're using standard HTTP requests, you could use javascript to append a $_GET variable to the action link. For Instance:
$('#form').attr('action', $('#form').attr('action') + '?page=welcome');
Then, upon clicking the link, PHP will have access to $_GET['page'], so in php you could:
switch($_GET['page'])) {
case 'welcome':
include 'section/welcome.html';
break;
case 'nda':
include 'section/nda.html';
break;
}
Look at the if(message ===1) statement below:) sorry for being such a noob :P
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.ActiveXObject){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlHttp = false;
}
}else{
try{
xmlHttp = new XMLHttpRequest();
}catch(e){
xmlHttp = false;
}
}
if(!xmlHttp){
alert("cat create that object hos");
}
function newuser(){
if(xmlHttp.readyState ===0 || xmlHttp.readyState ===4){
name = encodeURIComponent(document.getElementById('name').value);
company = encodeURIComponent(document.getElementById('company').value);
nationalities = encodeURIComponent(document.getElementById('nationality').value);
phonenumber = encodeURIComponent(document.getElementById('phonenumber').value);
queryString = "?name=" + name + "&?company=" + company + "&?nationalities=" + nationalities + "&?phonenumber=" + phonenumber + "&?URL= newuser";
xmlHttp.open("GET", "/php/database.php?" + queryString, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}else{
setTimeout('newuser()', 1000);
}
}
function handleServwerResponse(){
if(xmlHttp.readyState ===4){
if(xmlHttp.status === 200){
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
if(message === 1){
//I want to call a function here, so i can change the include path
}else{
document.getElementBy("underInput").innerHTML = 'User already exist klick to sign in here <p style="color:blue" onclick=""></p>';
}
}
}
}
}

Categories