This is the java script code for ajax call. In this case code variable get a c program code and pass it to the compiler.php page.
function insert(){
var code = document.getElementById("file_cont").value;
var arr = new Array(code,"c");
alert(arr[0]);
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//window.location.assign("login.php");
alert (xmlhttp.responseText);
}
}
xmlhttp.open("POST","server_controlers/compiler.php?q="+JSON.stringify(arr),true);
xmlhttp.send();
}
Ajax call work well but the case is in php file. I'm decode the jason array to $arr variable. But if i echo like this echo $arr[0] it is empty. But if i not include the code to the array in the java script like this var arr = new Array("aaaa","c"); its works fine. Can some tell me what is the wrong when i send the array with code variable. This is the php file.
<?php
if(isset($_REQUEST["q"])){
$arr = $_REQUEST["q"];
$arr2 = json_decode($arr);
echo $arr2[0];
/*$file = fopen("../temp_files/c/mmm.c","w");
fwrite($file,"$arr[0]");
fclose($file);
shell_exec('gcc -ommm ../temp_files/c/mmm.c');
system('mmm', $retval);*/
}else{
}
?>
server_controlers/compiler.php?q="+JSON.stringify(arr)
Your data is not being made URL safe. You say that it contains c code, this means it might include (for instance) the & character which would break the query string format and cause the JSON to be invalid when extracted from it.
You need to run the data through encodeURIComponent before putting it into your URL.
server_controlers/compiler.php?q=" + encodeURIComponent(JSON.stringify(arr))
I think the problem in ur request type POST/GET. U shuffled 2 request types in 1. Also how i can see u try to send get request? but in parameters u use type POST.
All information what u need about GET request u can find here.
Also u can try change ur php code too. If u need to use POST
<?php
if($_POST){
print($_POST);
}
?>
After u can do all u need with data array.
Related
Specifically, I need to get data in html from a database. If there is a simple way to do that in JavaScript then just skip the next part ^^
I have successfully written the php code to retrieve the data from the database, which is something like this:
$host = (host)
$user = (user)
$db = (database)
$pw = (password)
$funct = $_GET["Function"];
switch ($funct) {
case "getName": {
$personid=$_GET["PersonID"];
$output = getName($host, $user, $pw, $db, $personid);
echo $output;
break;
}
}
Of course there are more values for $funct, but to keep things short I only wrote one and left out the function itself. I tested it by making a form with method="GET", and it correctly prints the name. So my actual question is how to pass the name onto a html document, where I want to list the names of certain people. I did research and found for example that I need to use "echo $output;", I had originally tried "return $output;" but that was not enough. My current js-code is something like this:
"use strict";
function getName(field_id, person_id) {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("name"+field_id).innerHTML=this.responseText;
}
};
request.open("GET", "people.php");
request.setRequestHeader("Function", "getName");
request.setRequestHeader("PersonID", person_id);
request.send();
}
I originally tried fetch(), because it was recommended by javascript.info, but I didn't find many examples, so I scratched that. If i change it to ".innerHTML=this.responseText+this.status;" it just prints "200" onto the name field. There are no error messages.
It probably looks like I'm making it too complicated, but the code is supposed to do more stuff than what I shared, I'm just keeping it simple for you to understand.
I hope you can help me!
$_GET won’t give you the request headers, it will give query string parameters. You want to change your request to request.open("GET", "people.php?Function=getName&PersonId=" + person_id).
I have made an application requesting data to a PHP and javascript receives the data and displays it.
At first I did it by getting the data separated by ',' and it works fine, but I want to do it with JSON and this is where I have the problem.
I receive the data and try to decode them but it gives me the following error:
Uncaught SyntaxError: Unexpected token <in JSON at position 0
At JSON.parse (<anonymous>)
At XMLHttpRequest.xmlhttp.onreadystatechange
In the received variable I have:
"<meta charset="utf-8"/>
↵ {"rastro":"entrada:inicio-inicio-comprobarPerfil-conectar-","mensaje":"si","usuario":"Invitado47","password":"","email":""} "
My code is:
PHP
$jsondata = array();
$jsondata["rastro"] = $rastro;
$jsondata["mensaje"] = $mensaje;
$jsondata["usuario"] = $usuario;
$jsondata["password"] = $password;
$jsondata["email"] = $email;
echo '' . json_encode($jsondata) . '';
javascript
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var contenidosRecibidos = JSON.parse(xmlhttp.responseText);
I have looked at google for many examples and it seems all very simple but there is no way it works.
Thank you for your help
I don't know if this is the best solution but this is what I use to use JSON in Javascript via PHP.
PHP:
<script>
var datavalue= <?php echo json_encode($answers) ?>;
</script>
The data is a JSON object. I also recommend to have a look at jQuery, which provides excellent ways to call PHP pages and have JSON as a result.
It looks like your PHP page is throwing some error/warning.
Try to print response like this.
echo json_encode($jsondata);
That might not be the cause for your proble. But I strongly suspect that your PHP page is throwing some warning.
And are you sure $password is not "Undefined" ?
Try
console.log(xmlhttp.responseText)
before parsing it. You'll get the warning/error.
Thank you. The problem was in the beginning of PHP, in the first line had:
<meta charset="utf-8"/>
I am using this code to obtain some data from a php file. The php file has very simple coding and I have checked that it is working efficiently. It looks like that the error is in my javascript code which is not sending the request at all. My ajax code is posted below:
var jax=new XMLHttpRequest();
jax.onreadystatechange = function() {
if (jax.readyState == 4 && jax.status == 200)
alert(jax.responseText);
}
jax.open("GET","http://marked.byethost12.com/response.php?req=1&rnd="+Math.random(),true);
jax.send();
And the code in php file is this:
<?php
$request=$_GET["req"];
if($request=="1") //requesting the initiation of protocol
echo 'alert("hello. the protocol has been initiated!")';
else
echo "alert! error in req variable. variable not present or value is not 1";
?>
I think the problem is that you're sending it as an async-call. If you do like this:
jax.open("GET","http://marked.byethost12.com/response.php?req=1&rnd="+Math.random(),false);
You will see a response if you try it out in the browser-console.
Edit: As mentioned in other comments, CORS is a different beast you'll have to handle as well.
I am writing simple AJAX functions to send comments to the server and save them in a mySQL database with php.
The following code seemed to work just fine for my purposes, basic but did his job, until i tried to put a hash symbol (#) in a comment.
Inserting this into the text "crashes" my functions, without saving the written text in the database and returning an empty div basically.
This is the ajax call:
function sendComment(n){
var xmlhttp = createAjax();
var text = document.getElementById("f"+n).value;
if (!validation(text))
return false;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState==4 && xmlhttp.status==200){
appendComment(n, xmlhttp.responseText);
}
}
...
url = "comments.php?news="+n+"&text="+text;
xmlhttp.open("GET", url, true);
xmlhttp.send();
...
}
Where createAjax simply creates the xmlhttp object for every browser as standard, validation is a function that checks for many symbols like <,>,=,(,),| with a regular expression.
this is the php part:
function insertComment($text, $news){
$conn = dbConnect();
$user = $_SESSION["user"];
$text = nl2br(htmlentities($text));
$date = date("Y-m-d H:i:s");
$sql = "INSERT INTO comments(user, news, date, text) VALUES ('".$user."','".$news."','".$date."', '".$text."')";
mysql_query($sql) or die ("Errore in inserimento: ".sql_error());
echo writeSingleComment($user, $date, $text);
mysql_close(conn);
}
It just connects, saves the comment and returns the html code with echo, so that the javascript function can print it.
This works with any text apparently, but I can't get it to work with an hash, am I missing something?
Sidenotes, I could simply add the symbol to the validation regular expr., but my point is to "print" it, not just excluding it. Thanks in advance!
Sidenote 2, the javascript attaches the comment to a static element.
url = "comments.php?news="+n+"&text="+text;
You aren't escaping any of the data you are putting into your URL.
Some characters have special meaning, e.g. & separates query parts and # starts the fragment identifier.
You need to run your input through encodeURIComponent() before adding it to the URL.
url = "comments.php?news=" + encodeURIComponent(n) + "&text=" + encodeURIComponent(text);
Many characters (such as #) are not SQL safe and require escaping
At the very least you need to use
var toSend = escape(mystring);
this will not protect from attacks but will get you down the road.
I have set up post xmlhttprequest and it work working great. I however would like to set up the responseText to receive multiple variable in an array, comma delimited or whatever.
This is how I am currently scooping up my return php echo command.
var return_data = hrequest.responseText;
Maybe something like this?
var update = new Array();
if(response.indexOf('|$|' != -1)) {
update = response.split('|$|');
alert(update[0]);
document.getElementById("button1").value=update[1];
document.getElementById("button2").value=update[2];
}
Would be easier to send data as JSON from php.
Send JSON from php:
echo json_encode( $array);
Parse to array from responseText:
var return_data_array = JSON.parse(hrequest.responseText);