PHP parse Ajax-request sent from Internet Explorer - javascript

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.

Related

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

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

Send JSON file from jQuery to PHP without AJAX

So, I'm new to javascript/jquery, but I have played around long enough with PHP. I know how to get data from an input with PHP, which is really easy, but when trying to do the same with jQuery, how to do it just flies over my head.
Right now I have this script:
<script type="text/javascript">
function onSubmit( form ){
var data = JSON.stringify( $(form).serializeArray() );
console.log( data );
}
</script>
And this form:
<form onsubmit='return onSubmit(this)'>
<input type="date"/><br/>
<input type="date"/><br/>
<input type="submit" name=""/>
</form>
I see it logs the .json file just fine ([{"name":"from","value":"1994-01-01"},{"name":"to","value":"1994-02-02"}]) . My guess is it's pretty much sending the .json to the .php file, and then doing a $_POST, but I don't know how to proceed from here or do it. I don't know if ajax IS necessary or not, and if not, how to do it without it (everything I found around here is using ajax).
You can send form data as text string in standard URL-encoded notation or as JSON like string with jQuery.serialize().
<form id="set-date-form">
<input name="from" type="date"/><br/>
<input name="to" type="date"/><br/>
<input type="submit" id="set-date"/>
</form>
with jQuery
<script>
$('#set-date').on('click', function (e) {
e.preventDefault();
var data = $('#set-date-form').serialize();
$.post('somephpfile.php', data, function (response) {
// response is the data echoed from php
var result = JSON.parse(response) // assuming that php echoed ['success' => true/false];
if (result.success == true) {
alert("the values were sent to db successfully");
}else {
alert("the values were not sent to db successfully");
}
})
})
</script>
Then in your PHP file
<?php
$from = $_POST['from'];
$to = $_POST['to'];
// here you can update the database with this values
// after updating db or insert
// check if the query was successful
// if query was successful [echo json_encode(['success' => true]);] this value will be sent to javascript as a response
// if query was not successful [echo json_encode(['success' => false]);] this value will be sent to javascript as a response
PHP is treated Server-side.
If you want to send data to "PHP" you need to request the server (either via Ajax if you don't want to change your current page or calling a new URL with the data).
I know how to get data from an input with PHP
That's a pretty wrong statement as PHP can't get data from input since it's server side.
The browser send data to PHP calling the server.
Instead , define a route to post your input data in your php file and then through the form you can simply method='POST' rather than using ajax to send your data.
You could also use an XML HTTP Request.
Here is an example.
var http = new XMLHttpRequest();
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type ", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
This is taken from an answer here.
Send POST data using XMLHttpRequest

POST request alerts that it was successful, but data is not sent

I have a JavaScript code that is supposed to send some data to a php file on the server. The JavaScript code gives an alert that the post was successful, but no data is on the php file. No errors show up in the console. What is the problem here?
Here is the code:
var data = "It works";
var url = "data.php";
var http = new XMLHttpRequest();
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert("It worked");
}
}
http.send(data);
Here is the site for the code:
http://mikeyrichards.freeiz.com/run.html
EDIT: A clarification, I only want the data to show up like a text file on the PHP. For some reason, my server cannot open text files, so I have to use PHP
You need to send data in key value format something like this
var data = "lorem=ipsum&name=test";
Try changing to:
var data = 'data=It+works';
Then you can access it in the PHP script as $_POST['data'].
Don't forget to encode the space as + or %20. If you're generating the data dynamically, use encodeURIComponent to encode it properly:
var data = 'data=' + encodeURIComponent(value);

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/

HTTP file download with Javascript

Is there any way (in Javascript) to download a remote website (i.e. like with Curl), read it into a string variable and further process it?
You can only download a file from the same domain, as per the Same Origin Policy. You can download content from the same domain though, using the XMLHTTPRequest object:
var xhReq = createXMLHttpRequest();
xhReq.open("GET", "page.html", true);
xhReq.onreadystatechange = onResponse;
xhReq.send(null);
...
function onResponse() {
if (xhReq.readyState != 4) { return; }
var serverResponse = xhReq.responseText;
...
}
There are ways to circumvent the policy, some of them listed in the same Wikipedia page. But it's a hack at best and illegal at worst.
Sure- The url must be from the same domain, unless the url has a cross domain policy or you create a server side proxy script.
The following code is an example of an ajax call to any domain through a proxy PHP script:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","http://localhost/proxy.php?url=http://google.com", true);
xmlhttp.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
// ensure we have a response...
if (xmlhttp.responseText) {
var html = xmlhttp.responseText;
// do your processing here...
}
}
};
xmlhttp.send();
You then would make your proxy.php script connect to the given url via Curl (or whatever url library your sever side language has) and then simply echo the content from your domain...
<?php
// proxy.php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$_GET["url"]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$result=curl_exec ($ch);
curl_close ($ch);
echo $result;
?>
hope that all makes sense.
You can use the Yahoo Query Language to query any page on the web.
For example, if you want the full source of the Google homepage, you could use:
select * from html where url="http://google.com" and xpath='/html' limit 1
You'd have to use their JSON callback and reserialize the returned object, but you'd be able to get a full view of the page.
Mostly you won't be allowed. Javascript will prevent you doing this for security reasons. However, you can request json data from other domains using jQuery. Here is an example from the jquery docs that gets some cat pictures from flickr...
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",
function(data){
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
if ( i == 4 ) return false;
});
});
You can find this code in the jQuery Docs. As you can see, this makes a request, gets the data back and updates some image tags in the DOM with the cat pictures...

Categories