Ajax Request Not Firing. Why? - javascript

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.

Related

Simple AJAX function to set SESSION variable

I'm building a webpage in php, and want to change a $_SESSION variable from true to false on the click of a button.
I understand that php runs serverside, and as such I need to use AJAX to change that variable.
What I'd really like is a code to call an AJAX function (called methods in AJAX?) from a form button, the AJAX script then changes the SESSION variable. I'd really like to avoid page reload.
So, the form should look something like this:
<form action=ajaxMethod() method="get">
<input type="submit" value="X" id="close">
</form>
And this is the php version of what I want the AJAX script to do:
function ajaxMethod() {
$_SESSION["variable"] = false;
}
However, I'm such a noob when it comes to JS, and especially AJAX, that I am unsure how to create that AJAX method.
As simple as possible... If simple is possible...
Any help?
Also: The page I'm building is propeitary and belongs to the company I'm working for, and as such I'm not at liberty to divulge the actual code, but the examples above feels like they describe what I'd like to accomplish. If needed, I'll explain further.
I'd love to avoid using JQuery, if at all possible.
Avoiding Jquery for your need/requirement is not possible since you don't want the page to reload, Ajax is best way for it (And Ajax is more simpler with JQuery).
I have used Ajax request in many of my php webApps to change _SESSION variables.
HTML:-
<!-- Include Jquery library #Important -->
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<form>
<input type="button" value="X" id="close" onclick="changeSession();">
</form>
Script:- {JQuery and Javascript both}
function changeSession(){
$.post("session.php",{ name : "session", value : "false"},
function(data, status){
if(status == "success") console.log("successfully changed session variable");
else console.log("some error occurred");});
}
//Javascript
function changeSession(){
var value="false";
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
alert(xmlHttp.responseText);
}
}
xmlHttp.open("post", "session.php");
xmlHttp.send(value);//Don't know how to send multiple data with this sorry, so sending only 1
}
PHP file :- {session.php in my case}
<?php
if(isset($_POST['name'])){
//I think we have received Ajax request
if($_POST['value'] == "false") //Just to ensure the value to be changed should be false
//Now let us change session variable
$_SESSION['variable'] = "false";
}?>
Points to remember:-
You can make only 1 request to page at a time using Ajax.
The request can be either POST or GET at any time.
The variables you send from $.post() have to be properly handled at server side script {in my case session.php}.
You can also echo out text/html/json from php file as output of Ajax request.
Working Example here
Note:-
The code in working example may vary as I am trying to show how actually it works, however you can find the code in my Github, and for further queries comment below.
Edit:-
Added JavaScript code for Ajax request as you want to avoid JQuery. But didn't make a working example for it since I don't really prefer Ajax using JavaScript.

Getting data in JavaScript from php

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).

PHP script does not accept GET/POST data from a client having AngularJS scripts

I have my client app sending a json object to server which is in php.
Client side code:
var jacc = JSON.stringify(acc);console.log(acc);
$http.post($rootScope.url+'signup.php',jacc)
.then(function(response){console.log(response.data);});
which works perfectly fine.
But at server side
$acc = $_POST["jacc"];
$code = $_POST["code"];//received later
if($acc){
echo 1;//this thing never echoed.
}
elseif ($code && matchCode($code)){
if(addAcc($acc))
echo 1;
}
else echo 0 ." failed";
die();
The output at the console will be always "0 failed". Tried changing the post request to httpbin.org/post which works well. so the problem is with my php script. Also tried a var_dump($_POST) which also returns null value.
Your JavaScript code should be something like :
var params = { jacc : JSON.stringify(acc) };
// or var params = acc; if acc is already an object with the "jacc" property
$http.post($rootScope.url+'signup.php', params)
.then(function(response){
console.log(response.data);
});
Your error is that you try to post a "string" when you need to post an object with key:value.
tiltem saved my day.. thanks to dievardump for help.. Finally i got the issue and able to fix it. When using JSON content-type the $_POST array will not populate. All i had to do to fix it was
$rest_json = file_get_contents("php://input");
$_POST = json_decode($rest_json, true);

Javascript, PHP, and SQL Security - Basic validation of information received.

I have been developing a social network. I have noticed some security issues where the user can change the variables in javascript/jquery to other user_id's, text content, and other information that has been loaded into the scripts. And this is all done via the inspect tool or other software that can edit the languages. They can even rewrite the functions.
I load data onto the page via php and sql after sending the url_id to a php function.
I have javascript and jquery scripts that in return use this data to perform ajax, post, and get requests and to perform functions.
How can I stop the user from changing these variables before they are sent off to the server? For example when a user makes a post they can change the id to make it someone else's post, or when they click delete an image they can delete someone else's and it gets more complicated. This is a huge concern.
These scripts are included in the php pages or in php scripts that are loaded via ajax.
How can I stop this? Can you give me an easy explanation? I have been searching for months on how to stop this. I still don't understand how to stop the user from doing so. If there is another way could to do this? Can you provide me with true 100% examples? What are the other options I have?
Here are some snippets of my code
<? if (login_check($mysqli) == true) : ?>
<script>
$.post("auto/online.php?q=<? echo $id ?>");
function o() {
setTimeout(function() {
$.post("auto/online.php?q=<? echo $id ?>");
o();
}, 6e4);
}
</script>
<? endif; ?>
<?php echo '<div class="post-btn" onclick="ajaxPost(postenter.value,\''.$name.'\',\''.$id.'\');" title="Post">Post</div>'; ?>
function ajaxPost(content,name,id) {
var ip = '<?php echo $ip ?>';
content = content.replace(/<br\s*\/?>/mg,"\n");
var postArray = [content, id, ip];
postArray = JSON.stringify(postArray);
alert(postArray);
if (content.length == 0) {
alert('Oops it looks like your post is empty.');
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("postenter").innerHTML = "";
var html = xmlhttp.responseText;
alert(html);
$(html).hide().insertAfter("#wrapper").fadeIn(500);
document.getElementById("postenter").value = "";
}
}
xmlhttp.open("POST", "auto/post.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send('data=' + postArray);
}
}
<? if ($id == $user) : ?>
<div class="modalSetPro" onclick="setProImage(<? echo $picID; ?>,<? echo $uid; ?>)">Set Profile</div>
<div class="modalSetBac" onclick="setProCover(<? echo $picID; ?>,<? echo $uid; ?>)">Set Background</div>
<div class="modalDelImg" onclick="delItemPre(<? echo $picID; ?>, 1, <? echo $uid; ?>)">Delete</div>
<? endif; ?>
function delItemPre(itemID, type, user) {
var modArr = [itemID, type, user];
modArr = JSON.stringify(modArr);
$("#LoadMe").load('modals/del_modal.php?p=' + modArr);
}
How can I stop the user from changing these variables before they are sent off to the server? For example when a user makes a post they can change the id to make it someone else's post, or when they click delete an image they can delete someone else's and it gets more complicated. This is a huge concern.
You can't.
Your server side code should evaluate the user's privileges and decide whether or not they can do the action. JavaScript validation is more for the user experience - guiding and preventing mistakes.
You are not able to prevent this, which is why server-side validation is required.
Here is a stackoverflow discussing it: Why do we need both client side and server side validation?
There is some good information here:
http://www.w3schools.com/php/php_form_validation.asp
Basically, you want to put your validations in the PHP page that you are posting your ajax to.
Store and check all insecure data on server side, not client. This way user can't change it.
First of all when you are working on client side you have no control how user interact with you jquery or javascript code. So thumb rule is that never expose sensitive data in html or java script.
More over If you are curious about security you have not required to load User id in hidden field or any other client side code(html). In you case like when user is replying to any post you have to crosscheck at server side whether current logged in user is authorized to perform this task or not. also cross check whether this post is relate to current logged in user.
I have no knowledge about php but in asp.net we can create a session at server side and when user post data get the User id from session not from html content posted by user.

Call different PHP functions from javascript

I realize that calling database from JavaScript file is not a good way. So I have two files:
client.js
server.php
server.php has multiple functions.
Depending upon a condition, I want to call different functions of server.php.
I know how to call server.php, but how do I call different functions in that file?
My current code looks like this:
function getphp () {
//document.write("test");
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// data is received. Do whatever.
}
}
xmlhttp.open("GET","server.php?",true);
xmlhttp.send();
};
What I want to do is something like (just pseudo-code. I need actual syntax):
xmlhttp.open("GET","server.php?functionA?params",true);
Well based on that premise you could devise something like this:
On a sample request like this:
xmlhttp.open("GET","server.php?action=save",true);
Then in PHP:
if(isset($_GET['action'])) {
$action = $_GET['action'];
switch($action) {
case 'save':
saveSomething();
break;
case 'get':
getSomething();
break;
default:
// i do not know what that request is, throw an exception, can also be
break;
}
}
Just do something like this, i hope this will work
xmlhttp.open("GET","server.php?function=functioName&paramsA=val1&param2=val2",true);
You will most likely need to create the mechanism yourself.
Say the URL will look like server.php?function=foo&param=value1&param=value2
On the server side you will now have to check whether a function with such a name exists, and if it does, call it with these parameters. Useful links on how to do it are http://php.net/manual/en/function.function-exists.php and http://php.net/manual/en/functions.variable-functions.php
Otherwise, if you don't want to have it like this, you can always go with if/switch and simply check that if $_GET["function"] is something, then call something etc.
You can use jQuery too. Much less code than pure js. I know pure js is faster but jQuery is simpler. In jQuery you can use the $.ajax() to send your request. It takes a json structured array like this:
$.ajax({
url: "example.php",
type: "POST",
data: some_var,
success: do_stuff_if_no_error_occurs(),
error: do_stuff_when_error_occurs()
});
Here's a dynamic way to solve this issue:
xmlhttp.open("GET","server.php?action=save",true);
PHP Code:
<?php
$action = isset($_GET['action']) ? $_GET['action'] : '';
if(!empty($action)){
// Check if it's a function
if(function_exists($action)){
// Get all the other $_GET parameters
$params = array();
if(isset($_GET) && sizeof($_GET) > 1){
foreach($_GET as $key => $value){
if($key != 'action'){
$params[] = $value;
}
}
}
call_user_func($action, $params);
}
}
?>
Keep in mind that you should send the parameters in the same order of function arguments.
Let's say:
xmlhttp.open("GET","server.php?action=save&username=test&password=mypass&product_id=12",true);
<?php
function save($username, $password, $product_id){
...
}
?>
You can't write the API Call that way:
xmlhttp.open("GET","server.php?action=save&password=mypass&username=test&product_id=12",true);
Keep in mind that it's really bad to send "function namespaces" along with the parameters to a back-end. You're exposing your back-end and without proper security measures, your website will be vulnerable against SQL Injection, dictionary attack, brute force attack (because you're not checking a hash or something), and it'll be accessible by almost anyone (you're using GET using of POST and anyone can do a dictionary attack to try to access several functions ... there's no privileges check) etc.
My recommendation is that you should use a stable PHP Framework like Yii Framework, or anything else.
Also avoid using GET when you're sending data to the back-end. Use POST instead.

Categories