JSON parse doesn't work if i have request to database - javascript

I have json parse error, if I request to database. My php code is:
if($result->num_rows){
header('Content-Type: application/json');
echo json_encode(array("msg" => "close"));
$query = "DELETE FROM users WHERE num = '$num' AND password = '$pw'";
$result = $connection->query($query);
}else {
$myArr = array("msg" => "Неверный пароль!");
echo json_encode($myArr);
exit();
}
and Ajax request code is:
function ajaxLoad(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
I tried commenting db request exactly this area
$query = "DELETE FROM users WHERE num = '$num' AND password = '$pw'";
$result = $connection->query($query);
, then my code worked well, but I want to make a request. DB request also working correctly, It deletes the row. I want to say that if i use delete request responseText doesn't work, but it works when i comment the delete request.

It is likely that your database query is failing, there are two parts to fixing this:
You need to fix the error, the first step is to see what the error actually is, you can do this by looking at your logs, or the actual output that is being returned by your AJAX request.
You can do this by viewing it in your browser by just going to the URL that the AJAX request is being made to, or using Dev Tools to view the response (described here: Request Monitoring in Chrome).
Also, you should wrap anything which depends on something external (like a database, or API, or any user data) in a try/catch block, so that you can handle any unexpected errors, something like this:
try {
$result = $connection->query($query);
}
catch(Exception $e) {
Log::Error($e->getMessage();
}
Your database error should not be output to screen (or as part of the response in this case).
Turning off displaying errors is done using ini_set('display_errors', 1);, or by actually changing the php.ini, more details can be found here:
Turn off warnings and errors on php/mysql

Related

PHP parse Ajax-request sent from Internet Explorer

I'm working on a real-time timetable for a scool. Now when i'm testing it i'm getting an Error only in internet explorer. I use ie v.11 and charset UTF-8
When i send the data of the current student to a php-script there are some characters like ä,ö,ü which get parse to a ?. But only in InternetExplorer.
if i sent a URL like this: http://adopraesenz.ipwin.ch/data/students.php?q=getWirth Nalia;3:Kürzel;0;0;4;0;0;0;
and want to receive them in the php like this
$q = $_REQUEST["q"];
echo $q;
i get this output: getWirth Nalia;3:K?rzel;0;0;4;0;0;0;
I'm sending data like this:
function getData(str) {
var requestURL = "http://adopraesenz.ipwin.ch/data/students.php?q=" +str;
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if(this.readyState === 4 && this.status === 200){
loadJson(request);
}
};
request.open("GET", requestURL, true);
request.send();
}
for more code or information please ask.
In PHP you should always use urlencode and urldecode if you want to send data over a GET request. First encode your parameters, and after receiving decode them again. Most webservers will do the decoding for you, so you only have to call the encode code most of the time.
Also check that your form is using the same charset in html and http-header (utf-8 prefered)
Examples from official php documentation
encode
<?php
echo '<a href="mycgi?foo=', urlencode($userinput), '">';
decode (webserver will do this for you most of the time)
<?php
$query = "my=apples&are=green+and+red";
foreach (explode('&', $query) as $chunk) {
$param = explode("=", $chunk);
if ($param) {
printf("Value for parameter \"%s\" is \"%s\"<br/>\n", urldecode($param[0]), urldecode($param[1]));
}
}
An easier solution would be to use a post request instead of get, this is the prefered way for sending json data.

deleting a row from db using node, mysql, express and pure js

I am creating a simple app using node, express, mysql.
I am trying to create a route with which I can delete a row from my db, I wrote a pure javascript xhr.
when I test it I keep getting the following error message
POST http://localhost:3000/article/22 404 (Not Found)
this is what I have:
main.js
function handleDeleteClick(e, userId) {
e.preventDefault(); // Prevent default behaviour of this event (eg: submitting the form
// Perform the AJAX request to delete this user
var target = e.target;
var id = target.getAttribute('data-id');
var page = '/article/' + id;
var parameters = 'delete=true';
var xmlhttp = new XMLHttpRequest();
if (confirm('Are you sure you want to delete this?') == true) {
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// Request completed
}
}
xmlhttp.open("POST", page, true);
xmlhttp.send(parameters);
}
}
and the route app.js
app.delete('/article/:id', function(req, res) {
con.query(`DELETE FROM posts WHERE posts.id = ${req.params.id}`,
function(err, result, fields) {
if (err) {
console.log(err);
} else {
console.log("deleted Record: " + result.affectedRows);
res.redirect('/')
}
});
});
what am I missing?
help is very much appreciated!
thanks.
change POST to DELETE in your main.js-file:
xmlhttp.open("DELETE", page, true);
You are getting this 404 NOT FOUND error because route POST /article/:id does not exist (it's DELETE /article/:id).
Note: Your DELETE-query is vulnerable for SQL-injection attacks escaping-query-values
Escape query values:
con.query('DELETE FROM posts WHERE posts.id = ?', [req.params.id]);
Note: Actually, correct http status for this case is 405 METHOD NOT ALLOWED, but express by default doesn't distinguish those cases
app.delete expects to recieve a DELETE request.
xmlhttp.open("POST", page, true); is sending a POST request.
Change the second argument to "DELETE" to make a DELETE request.
you have a delete route in your server, so if you want to send a request to that route, you should pass "DELETE" parameter to xmlhttp.
so simply change
xmlhttp.open("POST", page, true);
to
xmlhttp.open("DELETE", page, true);
also, this answer may help you understand using XMLHttpRequest better
Do not insert params directly into your database query
As others said, you are vulnerable to SQLInjection attacks. you should evaluate params first instead of just inserting it directly into your SQL query

Inserting value from Javascript to mysql if possible through php

I'm currently developing a intranet application for my company. Within my application i would like to fetch some variables with javascript and send them to a MySql database through php.
I know that javascript is a client-side and php is server-side so I'm not sure if it's even possible to transfer the variables through.
Goal is to get the current users computer name and store it in a SQL database whenever they are opening the intranet site.
<?php
<script type="javascript">
var network = new ActiveXObject('WScript.network');
<?php $pcName = "<script>document.write(network.computername)</script>";
</script>
?>
This part works perfectly. The computername is stored in the php variable $pcName and it shows fine on the intranet site when I try to echo the variable.
$sql = "INSERT INTO t1 (pcName) VALUES ('".$pcName."')";
But when I insert it into my sql table the value is "<script>document.write(network.computername)</script>".
Am I missing something? Or is it as I assumed that the variable is available on the clint, and the client only.
You will probably have to create and call an "API" of some sort. For example, you could have something like this on the client:
<script type="javascript">
var network = new ActiveXObject('WScript.network');
var pcName = network.computername;
fetch('storeComputer.php', {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
pcName: pcName
})
});
</script>
And then on PHP side:
// storeComputer.php
$json = json_decode(file_get_contents('php://input'));
$pcName = $json['pcName'];
// do what you want with $pcName..
There are many ways, but i use jquery inside javascript to send the parameter to php. Its works for me very well
try this
$('.add_item').click(function(){
var responsecontainer=$('#responsecontainer').val();
var ProductName=$('#ProductTable').val();
$.ajax({
url:"sample.php"
, method:"POST"
, data: {
ProductName: ProductName,
}
, success: function(result){
// do some thing here
}
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
}
use can use some other method too.
Yes, it's possible.
Javascript can launch any URL with parameters, notably including JSON encoded parameters; the URL can launch a CGI script; the CGI script can catch the JSON and interact with the MySQl; and then return the result to javascript, either asynchronously or synchronously. Here's an asynch URL launch:
// this is asynchronous - result comes back to callback later, while this returns immediately
// -----------------------------------------------------------------------=======------------
function callAjax(url, callback)
{
var xmlhttp;
// compatible with IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
callback(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
.
Here's a callback:
function cb_myCallback(theStuff)
{
// process theStuff here. If it's JSON data, you can unpack it trivially in Javascript,
// as I will describe later. For this example, it's just text. You're going to get
// back "hello, Ben"
console.log(theStuff);
}
.
So here's how I might use that to call a script that can access the database:
function pyRequest(upd_data,upd_callback)
{
var cd_url;
cd_url = '/cgi-bin/myPython.py?myData=' + encodeURIComponent(upd_data);
callAjax(cd_url,upd_callback);
}
pyRequest("Ben",cb_myCallback);
.
So here’s what happens. pyRequest() builds a URL that can call the Python (or whatever you like to use) script. callAjax() actually does the calling. This all returns immediately to the calling code. Later, when the script has completed whatever its task is, the callback, in the example cb_myCallback(), is sent whatever the script emitted.
Synchronous Approach
There may be times when you won’t want to use an asynchronous callback, because you can’t proceed until you have the data you asked for. In such cases, you need to use a synchronous request, which will not return (with the actual response) until the response has been received from the script. Note that in this function, I embed the URL to demonstrate a little variety in possible structuring of these types of usages:
// this is synchronous - result returns only when called script provides it
// ------------------------------------------------------------------------
function syncCallAjax(spdq_myData)
{
var remote = '__Unset__';
var request = new XMLHttpRequest();
var remote_url;
remote_url = '/cgi-bin/myPython.py?myData=' + encodeURIComponent(spdq_myData);
request.open('GET', remote_url, false); // false makes the request synchronous
request.send(null);
if (request.status === 200)
{
remote = request.responseText;
}
return(remote);
}

Initiate a Post request from a form with paylod in the Body request

I have the following problem. I have a webservice, which accepts a post request with some json data in the request body and which also returns Json data.
Now I want to build a user friendly HTML page to test this service. I have a form to fill in data, when the user clicks the button, the JSON should be build from the form data and POSTed to my webservice, the response should be displayed to the user. How do I achieve that?
jQuery is your friend, the have a look at ajax part...there a bunch of function that forge a request and grab directly the data from your form.
http://api.jquery.com/jquery.ajax/
This is one example doing this, but it requires a MySQL database and PHP support by your provider.
jQuery
$('#form').on('submit', function(e) {
e.preventDefault();
var data = $(this).serialize();
$.POST('path_to_php_file.php', data, function(response) {
$('#container').append(response);
});
}
PHP
<?php
$db = new PDO('mysql:host=localhost;dbname=DATABASENAME;charset=utf8', USERNAME, PASSWORD);
//the post variables equal the name attribute on your input element in html: <input name="THIS">
$text = $_POST['text'];
$name = $_POST['name'];
if(isset($text) && isset($name)) {
$stmt = $db->prepare("INSERT INTO table_name (text, name) VALUES (?, ?)");
$stmt->execute(array($text, $name));
echo "Successfully saved.";
} else echo "There was an error.";
$db = null;
Another option, if you just want to test your webservice, is to use postman, a friendly chrome extension for testing web APIs.
Otherwise, you really don't even need jQuery. A synchronous post is easy enough to write:
var button = document.getElementById("submit");
button.onclick = function() {
var xhr = new XMLHttpRequest();
xhr.open("POST", "yourwebservice.com/your-web-service", false);
xhr.send("{'json_string':['goes'],['here']}");
alert(xhr.response);
}

XHR in Chrome Extension with CI

I'm sending a POST from a chrome extension content script to a server I control. I setup the permissions in the manifest ok. Here is my XHR code. (I want to avoid jQuery for this). Its sending an empty responseText
var xhr = new XMLHttpRequest();
xhr.open("POST",'http://mysite.com/make',true);
xhr.onreadystatechange=function() {
if (xhr.readyState == 4) {
var res = JSON.parse(xhr.responseText);
console.log(res);
}
}
xhr.send({'textbox':data[0].user,'from':'extension'});
data[0].user is an object I got directly from the Twitter API
in my CI controller I have
$user = $this->input->get_post('textbox', TRUE);
$from = $this->input->get_post('from', TRUE);
$fullURL = 'http://www.google.com'; //example of a URL from code.
$json = $this->output->set_content_type('application/json');
$json->set_output(json_encode(array('URL' => $fullURL)));
The response text is empty
a jquery call on the other hand works fine
$.post("http://mysite.com/make", { 'textbox': data[0].user, 'from':'jquery' },
function(data) {
console.log(data);
});
Reason is simple, JQuery post method can accept JSON and then convert it to string and send to the server.
What you are trying to do is to directly send JSON here :
xhr.send({'textbox':data[0].user,'from':'extension'}) // Incorrect way
send method should either accept NULL or a string which is generally made up of QueryString Parameters like.
xhr.send("textbox="+ data[0].user + "&from=extension"); // Correct way
This will ensure that your data goes to the appropriate URL with textbox and from as post request parameters.
and queryString will be generated like textbox=username1234&from=extension in the packet's body unlike one goes in Get with the headers along side the URL.
jQuery's post method makes it simpler for you to format data you send using JSON and then internally it converts that to a queryString to send parameters.
You can't directly send Javascript object like that with an XHR object!
Also checkout this example:
http://beradrian.wordpress.com/2007/07/19/passing-post-parameters-with-ajax/

Categories