JSON string acting funny on server end - php

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

Related

Onclick=\"alert('hi');\" works, but onclick=\"function_name();\" does't work, ajax with javascript and php

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

$.ajax()function with json data from javascript array to a php processing file

i trying to use json for the first time with $.ajax() i got the values of checkboxes and other needed data to a php file for processing and posting to mysqldb through an array for the data section of $.ajax() function but would get an empty array[] on my php file. When i try using javascript debugging tool from my browser i got the reprot
**Uncaught SyntaxError: Unexpected end of input jquery-1.9.0.min.js:1
st.extend.parseJSON jquery-1.9.0.min.js:1
(anonymous function) index.php?url=account/registration/:297
st.event.dispatch jquery-1.9.0.min.js:2
y.handle**
the array i produced looks like this at the console log
[checkbox1: "COM 101", semester: "1st Semester", mid: "7", checkbox2: "COM 112", checkbox3: "STA 111"…]
checkbox1: "COM 101"
checkbox2: "COM 112"
checkbox3: "STA 111"
checkbox4: "STA 112"
checkbox5: "MTH 111"
length: 0
mid: "7"
semester: "1st Semester"
on my php processing file i did print_r on the json data but got an Array[] as a result
this is my javascript code block "myDataArray is a global variable"
$('#mytable2').on('change',function(e){
var rel = e.target.getAttribute('rel');
console.log(e.target.value+ " "+ e.target.checked)
if(rel === globals.payment_target && e.target.checked===true){
myDataArray[e.target.getAttribute("name")]= e.target.value;
myDataArray["semester"] = $("#semester").val()
myDataArray["mid"] = $("#mid").val()
}
if(rel === globals.payment_target && e.target.checked ===false){
delete myDataArray[e.target.getAttribute("name")]
console.log(myDataArray)
}
});
$('#mytable2').on('click',function(e){
var rel = e.target.getAttribute('rel');
console.log(e.target.value+ " "+ e.target.getAttribute('name'))
if(rel === globals.payment_target && e.target.value =="Register"){
console.log(myDataArray)
var jsonstring = $.parseJSON(myDataArray);
var myglob =JSON.stringify(globals)
console.log(myglob)
$.ajax({url:'courseregistration.php', type:'POST',data:{data:jsonstring},success: function(result){
$('#putmehere').html("<h4 style='text-align:center'>"+result+"</h4>")
alert(result)
}
})
}
});
and this what the php file looks like
$data = json_decode($_POST['data']);
print_r($data);
i just can't figure out what the problem is. can someone please tell me what is wrong with the way i'm doing it or suggest a better way
Try to set data type property json
$.ajax({
url:'courseregistration.php',
type:'POST',data:{data:jsonstring},
datatype:"json",
success: function(result){
$('#putmehere').html("<h4 style='text-align:center'>"+result+"</h4>")
alert(result)
}
});
Also set content type in php script.
header('Content-Type: application/json');
The reason that your page is not working is the critical error (your first listing). You need to clear up this error before you can do anything else because your form is not being submitted as you want it to.
The reason for the error: maybe a corrupt file - download another copy of jQuery and try again.
i removed this --- $.parseJSON(myDataArray) --- and the error did not come again i used JSON.stringify(myDataArray) instead. also i declared myDataArray as an object instead of as an array and things went fine, it solved the Uncaught SyntaxError: issue
Initially, i declared myDataArray as an array
var myDataArray = new array();
but when i changed myDataArray to Object
var myDataArray = new Object;
i effect it as below and things went fine
$('#mytable2').on('click',function(e){
var rel = e.target.getAttribute('rel');
console.log(e.target.value+ " "+ e.target.getAttribute('name'))
if(rel === globals.payment_target && e.target.value =="Register"){
console.log(myDataArray)
console.log(globals)
var jsonstring = JSON.stringify(myDataArray);
console.log(myglob)
$.ajax({url:'courseregistration.php',dataType:"json", type:'POST',data:{data:jsonstring},success: function(result){
$('#putmehere').html("<h4 style='text-align:center'>"+result+"</h4>")
alert(result)
}
})
}
});

accessing local var value from JS function in PHP

After searching for internet and even here for 5 hours, i am still stuck at getting value of a local variable in a function and sending it to PHP.
I have tried different syntaxes but none of them seems to be working. This code below, takes an input field from PHP and assign some value to it (having problem send this value back to PHP)
$(document).ready(function() {
//select all the a tag with name equal to modal
$('form[name=modal]').click(function(e) {
//Cancel the link behavior
e.preventDefault();
//Dont go until value is not 7
console.log('i am Now waiting for input');
var s = $('#serial').val();
console.log('searching for ' + s);
while(s.length != 7) return;
//When code value reaches 7
var code = $('#serial').val();
console.log('Value is reached ' + s);
});
});
In PHP
echo "<script>document.write(code);</script>";
Uncaught ReferenceError: code is not defined
please help
You should do somthing like this in javascript when $('#serial') is your input field.
$.ajax({'url':'your_php_file_url', 'type':'post', 'data':{'str':$('#serial').val()}}).done(function(data){
console.log(data.code);
});
And in php
$output = Array('code' => 'not set');
if (isset($_POST['str']))
{
//do your search and assigne value to output
$output['code'] = 'some value';
}
echo json_encode($output);
In short - you send your search string via ajax to php and make your searches. Then you echo it out as json, then ajax will read it as an object and you can use those values you want.
ok, i have almost tested every possible solution but all in vain... so i am off and try to use some normal method rather than javascript. Thanks for all your answers guys.

write javascript array to file

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

Issue with PHP + Ajax + Sql

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?

Categories