I'm sure it is just a simple issue, I have looked in the forums but couldn't find an example that was specific to my issue.
Basically I am displaying a table of hrefs, which each have an onclick() call to an ajax method, using a 'get' and a url.
function createRequestObject(){
var req;
if(window.XMLHttpRequest){
//For Firefox, Safari, Opera
req = new XMLHttpRequest();
}
else if(window.ActiveXObject){
//For IE 5+
req = new ActiveXObject("Microsoft.XMLHTTP");
}
else{
//Error for an old browser
alert("Your browser is not IE 5 or higher, or Firefox or Safari or Opera");
}
return req;
}
//Make the XMLHttpRequest Object
var http = createRequestObject();
function sendRequest(method, url){
if(method == "get" || method == "GET"){
http.open(method,url,true);
http.onreadystatechange = handleResponse;
http.send(null);
}
}
function handleResponse(){
if(http.readyState == 4 && http.status == 200){
var response = http.responseText;
if(response){
document.getElementById("DIVNAME").innerHTML = response;
}
}
}
The call for an href looks like:
echo '<td><a href="#" onClick="sendRequest(\'get\', \''.$toPass.'\')"/>'.$variable.'</a></td>';
The $toPass variable is page.php?variable1='.$variable1.'&variable2='.$variable2.'&variable3=blah&action='.$option.'
When I pass a variable 1 for example : 'TP111010114' it works fine, the _REQUEST['variable1']; grabs the variable and pushes it the through my sql request.
if the variable contains a # for example : 'Blah #2' the only piece of data that gets through is
Variable 1 = 'Blah ' with the remaining variables being unassigned.
From what it looks like it is not getting anything after the #.
I tried encoding the url in php, then unescaping it in my ajax.js where you call window.open('get', unescape(url), true); but I had the same result, it worked with any variable that didn't contain #. When I tried to encode it using urlencode() and not decoding it in my ajax.js, the request was not going through.
The encoded request looks like:
page.php%3Fvariable1%3DTP111010114%26variable2%3D64%26variable3%3Dnew%26Action%3DOthers
if it is not encoded it looks like:
page.php?variable1=TP111010114&variable2=64&variable3=new&Action=Others
I used firebug to monitor the .js variables as they go through and it looks as though when I encode it that it should grab the proper variable, but it still only grabs before the # in the variable
http://www.randomsite.ca/page.php?variable1=WF225+Amendment+#2&variable2=543&variable3=new&Action=Others
Yet this request on the php side still gets $variable = $_REQUEST['variable1']
$variable = 'WF225 Amendment ', and the other variables are unnassigned.
It must be something to do with the way something is handling the #, but I do not see what I am missing here, if anyone could help it would be much appreciated.
I have renamed information for privacy purposes
You need to urlencode the values you're putting into the URL, not the whole URL including variable names. You want to encode the "blah #2" but not the "&variable1=" part. Ex:
$toPass = 'page.php?variable1=' . urlencode($variable1) . '&variable2=' . urlencode($variable2) ...etc
You won't need any decoding on the HTML/JS end.
I believe that it may be parsing anything after the # as a named anchor which will likely disregard the variables after this point... have you tried using a method that doesn't rely on the # character? Or even try using POST as the AJAX method?
Related
I have two files:
inventory.php which has some javascript functions, one called (items) which looks like:
function items(page,cat,order,column)
{
alert('hiiiiii');//testing msg
var xhr = new getNewXmlHttpObj();
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4)
{
//alert(xhr.responseText);
document.getElementById('items').innerHTML=xhr.responseText;
}
}
var URL="ajax/inventory_items.php";
xhr.open("POST",URL,true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
var info="page="+page+"&cat="+cat+"&order="+order+"&column="+column+"&dummy=" + new Date().getTime();
xhr.send(info);
}
and the other file inventory_items.php which returns an HTML code to be displayed in the items div.
in inventory_items I have a link for the next page like this:
echo "Next";
the problem is with onclick, it doesn't call the (items) function at all, while changing to onclick=\"alert('something');\" works!
I am wondering whats the problem, I had this same code on windows (before win8) and it was working perfectly, but now I am using windows 8, does it make any difference?
how can I make the onclick work?
please help
fixed it!
the problem is that I had to include the non-number variable in single quotation marks, as follows:
Next
I am almost pulling my hair in frustration having tried to sort the issue I'm having.
I'm trying to use javascript to send some data to a PHP server while making use of JSON.
From what I experience, once the string hits the PHP server and I use the json_decode PHP command to decode the string back to its json format, it fails. It fails as I cannot get the size of the associative array json_decode is meant to return.
Funny enough, if I rather save the string to my database to a column of blob type, and then later try to repeat the process of using json_decode and making use of the associative array it returns, I get positive results.
Kindly see a little bit of the code involved.
Javascript Code
var products = {
product: [],
companyId: ""
};
products.companyId = nameofCompany;
for(var c=0; c<count; c++)
{
var product = {
productItems: []
};
productTitle=document.getElementById('productTitle' + c).innerHTML;
product.productItems.push({ "productTitle" : productTitle});
products.product.push({ "product" : product});
}
var JSONObject = new Object;
JSONObject = products;
JSONstring = JSON.stringify(JSONObject);
addNewProduct(JSONstring, 'addNewProduct')
//make ajax calls to PHP server here. I have shorted it to show that I am passing the string
function addNewProduct(inputStr, fieldStr)
{
inputValue = encodeURIComponent(inputValue);
fieldID = encodeURIComponent(fieldID);
cache.push("inputStr=" + inputStr + "&fieldStr=" + fieldStr);
if ((xmlHttp.readyState == 4 || xmlHttp.readyState == 0) && cache.length > 0)
{
xmlHttp.open("POST", phpServerAddress, true);
}
}
PHP Code
the below code will not work as it returns a value of 0 for the sizeof() command. However if I save the
$_POST['inputStr'] to a database column of blob type and then try to read and do this same code, it works
perfectly well
if(isset($_POST['inputStr']))
{
$jsonStrArr= (json_decode($_POST['inputStr'], true));
die sizeof($jsonStrArr);
}
Thanks a lot
Your code is incomplete, I assume it's because its quite large and might be spread over several files. As noted before:encodeURIComponent(inputValue) should be inputStr.
Here is a working php page, maybe you can use it to add your code and trace what goes wrong.
<?php
if(isset($_POST["object"])){
var_dump($_POST);
var_dump($_GET);
var_dump($_POST["object"]);
var_dump(json_decode($_POST["object"]));
}
?>
<!DOCTYPE html>
<html>
<head>
<script>
var myObj={value1:"value1",value2:"value2"};
var someOtherVal="hello there";
var postString="object=" + escape(JSON.stringify(myObj))
+"&someOtherval="+escape(someOtherVal);
var xhr = new XMLHttpRequest();
xhr.open("POST", "index.php" ,true);
xhr.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
xhr.onreadystatechange=function(){
if(this.readyState != 4){
return;
}
if (this.status === 200 || this.status == 304) {
document.getElementById("output")
.innerHTML=this.responseText;
}
};
xhr.send(postString);
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>
All,
Thanks for your response. However I was able to finally get the issue resolved. Resolved it by writing the JSON.stringify value to a file where I noticed the value had escape characters in it. Using stripslashes on the PHP server simply helped out. All the same thanks
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
pass php variable to javascript
I want to compare the click count(s) clicked by the users with the data saved in database.
I am not sure how to proceed to pass the value of the HTML "clicks" to compare with "counts" in PHP.
<html>
<script type="text/javascript">
var count = 0;
function countClicks()
{
count = count + 1;
document.getElementById("clicks").innerHTML = count;
}
</script>
<?php
if(empty($counts)){
?>
<script type="text/javascript">
alert("Count is empty!!");
</script>
<?php
} else {
$data = mysql_query("SELECT clicks FROM customerdetails WHERE customer_username='$username'");
$info = mysql_fetch_array($data);
//compare $data with the clicks
echo 'same!';
}
?>
<body>
Count Clicks
<input type="button" onclick=countClicks() value="Click"/>
<p id="clicks">0</p>
</body>
</html>
You are using PHP and Javascript in the wrong way. PHP is a serverside language. which means it runs before the page even loaded on the browser.
You will have to create a javascript click counter and put its values into a hidden formfield. Then use a submit button to send the information to the server (PHP). Then let PHP do the checks and selections from the database and return an answer.
Another solution is to use javascript AJAX, but I do recommend first trying the above.
The best way to proceed would be to make an Asynchronous JavaScript and XML call (AJAX). PHP is a server-side language, which is executed before the HTML (thus, before Javascript) is built and shown to the browser.
Therefor, the only way for Javascript to exchange variables and data with PHP is to make an AJAX call (you could always reload the page with a form submit or with session variables and cookies, but this isn't the best way to go if action is repeated too often.
IN AJAX, you can make another PHP page that will check both values and return whatever you want. The response can be stored in a Javascript variable, or even in JSON.
I suggest you to read more about AJAX and also get to know what is PHP how to use it.
Edit: After reading your comment, I decided to put a simple example down here.
Javascript (in your HTML page)
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
/*Here you should do what you want.
xmlhttp.responseText is the content of your PHP answer! */
var result = xmlhttp.responseText;
//I am parsing a JSON response, which is a specific, universal language
//To exchange data without losing formatting or anything else.
result = JSON.parse(result);
/* The we use the name of our PHP array key as a property
Here it is "response" (see PHP json_encode line) */
alert(result.response);
}
}
/* Change this URL for the PHP filename. we use the GET method to send data. */
/* You should always use the POST method when sending sensitive data */
xmlhttp.open("GET","getUserClicks.php?clicks="+count+"&username="+username,true);
xmlhttp.send();
PHP (here it is the file named getUserClicks.php )
<?php
if(!isset($_GET['username']) || !isset($_GET['clicks']))
die("Error");
$username = $_GET['username'];
$jsClicks = $_GET['clicks'];
$phpClicks = null;
#I am using the mysqli class to execute the query since mysql is deprecated in PHP5.
$data = mysqli_query("SELECT clicks FROM customerdetails WHERE customer_username='$username'");
while($row = mysqli_fetch_array($data))
{
$phpClicks = $row['clicks'];
}
#If your "IF" only contains one line, you don't need brackets.
#Otherwise they are needed.
if($phpClicks == null)
die("Could not get the number of clicks of the desired username");
#This is the string PHP will send to Javascript.
$response = "Same number of clicks!";
#If phpClicks is different and has the same type as jsClicks...
if($phpClicks !== $jsClicks)
{
$response = "Number of clicks changed!";
if($jsClicks > $phpClicks)
{
#Updates the number of clicks the user has done.
$mysqli_result = mysqli_query("UPDATE customerdetails SET clicks=$jsClicks WHERE customer_username='$username';");
}
}
echo json_encode(array('response'=>$response));
?>
Be sure to make some research if you see functions or methods you have no idea what they do (eg.: isset).
i have loaded a file into an array using ajax and after splitting it i need to save it to the file again.This all happens onClick of a button.
function updatetags(){
var alreadyexistingtags;
var responsetext;
var r2 = new XMLHttpRequest();
r2.open('GET', 'tagsupdated.txt', true);
r2.send(null);
r2.onreadystatechange = function() {
if (r2.readyState == 4 && r2.status==200) {
responsetext=r2.responseText;
alreadyexistingtags=responsetext.split(' ');
}
}
}
i understand that javascripts are not server side and that's why i cannot do what i want,but i'm sure there must be a way to write alreadyexistingtags[ ] to tagsupdated.txt.Any help?Perhaps i should somehow pass the array to PHP?And if so how is that possible given that PHP gets executed when the page loads,when i need to wait for the button to be pressed?
You're going to have to use AJAX or some other method to send the data back to your server, which can then write the file out.
To do this, just create a new script on your server, say writearray.php, which accepts the Javascript array as input. Then use AJAX to send a request to that file with your array.
The PHP file would look something like so (this is a highly simplified example):
<?php
file_put_contents("where_you_want_the_file.txt", $_POST['array']);
?>
It looks like you're just storing your Javascript array as a space separated list, so the Javascript would look something like this:
var str = your_array.join('%20'); // URL encoded spaces separating array entries
var params = "array=" + str;
var http = new XMLHttpRequest();
http.open("POST", "your_script.php", true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
// Do something on success?
}
}
http.send(params);
The way this works, is you're sending a POST with a field named array, which holds the textual representation of your Javascript array. The PHP code checks $_POST['array'] to get this value, then writes it to your file.
Note that if you want to do anything more complicated, you should look into using JSON. And also as always be very careful with what you do with user data.
For send data you must doing another ajax query but in .send method you have to pass a string with data
Example:
var r3 = new XMLHttpRequest();
r3.open('POST', 'writeTextWithoutTags.php', true);
var data_string='text='+alreadyexistingtags+'&etcParams='+etc_you_params;
r3.onreadystatechange = function()
{
if (r3.readyState == 4 && r3.status==200)
{
alert(r3.responseText);//write result
}
}
r3.send(data_string);
Before sent alreadyexistingtags variable you must implode array to string with separator or better to JSON string.
But in writeTextWithoutTags.php ypu must check data because javascript execute ib user brouser and you can not be sure that the data is sent from yavastsript not undergone processing intruder!
P.S. If you can access to PHP I dont understang I do not understand why you are here JS - all this actions you can douing in PHP and not to drive data from the server to the browser and back
I am using json to read records. It works perfectly fine if I use it inside the javascript like this
var events=[{eventId:"1", event_name:"wedding"},{eventId:"2", event_name:"interview"}]
then loop it to read records
for(var events_count=0;events_count<events.length;events_count++)
{
//read records and works perfectly fine
}
but when I am doing the same using ajax, it is not working. I have even put the text
{eventId:"1", event_name:"wedding"},{eventId:"2", event_name:"interview"}
in the ajax called(ajax-get-events.php) page, It doesn't go inside the loop
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//got data in same format as above in xmlhttp.responseText and used eval to parse it
events = eval('(' + xmlhttp.responseText + ')');
//I have tried to alert(events) and it shows [object object]
for(var events_count=0;events_count<events.length;events_count++)
{
//loop doesn't work at all
}
}
}
xmlhttp.open("GET","ajax-get-events.php",true);
xmlhttp.send();
Please tell me what I am missing.
Thanks
This is not parsed as a JSON array, but as one object (the second one):
{eventId:"1", event_name:"wedding"},{eventId:"2", event_name:"interview"}
But this should be parsed (read eval'd) as a correct array:
[{"eventId":"1", "event_name":"wedding"},{"eventId":"2", "event_name":"interview"}]
Since you're using PHP, use json_encode to generate your JSON output, it'll be correct JSON.