preg_replace and json_decode - Ajax handler - php - php

I have problem with array in PHP.
I've got that code in my Ajax handler PHP page:
if(isset($_GET['dataa']))
{
$dataa = $_GET['dataa'];
$dataa = preg_replace('/\\\"(.*?)\\\"/', '"$1"', $dataa);
$dataa = json_decode($dataa);
echo $dataa[0];
echo $dataa[1];
}
I tried to send data array in JavaScript to the Ajax handler but it's not working so I want to to pass param in the URL.
When I try to put this URL:
...AjaxHandler.php?dataa=["test1","test2"]
I get this: test1test2 and that's ok.
But I don't really understand why I need to use preg_replace and json_decode.
I tried to delete the preg_replace but then it didn't show me anything.
I tried to delete the json_decode too but then I get only [/ on the screen.
I need to send multiple data so I do that with array.
Why I have to use preg_replace?
Is it common to use preg_replace like that? All time when I send data array?

Related

convert query String to json in php

I send a QueryString formatted text like bellow to a php Script via Ajax:
title=hello&custLength=200&custWidth=300
And I want to convert this text to a JSON Object by this result in PHP:
{
"title" : "hello",
"custLength" : 200,
"custWidth" : 300
}
How can i do that. Does anyone have a solution?
Edit :
In fact i have three element in a form by title , custLength and custWidth names and i tried to send these elements via serialize() jquery method as one parameter to PHP script.
this code is for Send data to php:
customizingOptions = $('#title,#custLength,#custWidth').serialize();
$.post('cardOperations',{action:'add','p_id':p_id,'quantity':quantity,'customizingOptions':customizingOptions},function(data){
if (data.success){
goBackBtn('show');
updateTopCard('new');
}
},'json');
in PHP script i used json_encode() for convert only customizingOptions parameter to a json.
But the result was not what I expected and result was a simple Text like this:
"title=hello&custLength=200&custWidth=300"
I realize this is old, but I've found the most concise and effective solution to be the following (assuming you can't just encode the $_GET global):
parse_str('title=hello&custLength=200&custWidth=300', $parsed);
echo json_encode($parsed);
Should work for any PHP version >= 5.2.0 (when json_encode() was introduced).
$check = "title=hello&custLength=200&custWidth=300";
$keywords = preg_split("/[\s,=,&]+/", $check);
$arr=array();
for($i=0;$i<sizeof($keywords);$i++)
{
$arr[$keywords[$i]] = $keywords[++$i];
}
$obj =(object)$arr;
echo json_encode($obj);
Try This code You Get Your Desired Result
The easiest way how to achiev JSON object from $_GET string is really simple:
json_encode($_GET)
this will produce the following json output:
{"title":"hello","custLength":"200","custWidth":"300"}
Or you can use some parse function as first (for example - save all variables into array) and then you can send the parsed output into json_encode() function.
Without specifying detailed requirements, there are many solutions.

How to format js object to php array?

So I found some answers on how to do this, but none of them actually worked, i.e. json_decode(). This is what I did:
I created js object/array
Then I passed it to php file via Ext.Ajax.Request as JSON.stringify(js object)
Now in my php I see the result of that string as follows: ["James;","George;"]
I want to get it as an php array like (James, George). Any easy way to do this or I have to remove unnecessary parts manually?
OK, I was looking at this problem for a while and finally got the answer.
Inside php, I needed to add json_decode(stripslashes($scenarios)), where $scenarios = ["James;","George;"].
Code: ($scenarios is sent from js file via Ajax using JSON.stringify(js object))
<?php
$scenarios = empty($_GET['scenarios']) ? false : $_GET['scenarios'];
// more code for validation
$arr = json_decode(stripslashes($scenarios));
?>
Now $arr will become regular php array.
Use html_entity_decode function

save url in MySql databse via PHP getting failed

I have a array of URL which I am saving in database after iteration on PHP side.
I am sending the array with Ajax and saving it with PHP.
Data send via Ajax
linksString=http://localhost/phpmyadmin/index.php?db=testdb&token=42d0dde57469a9aa4b6a2f7e0741,
http://localhost/phpmyadmin/index.php?db=testdb&token=98604a9aa4b6a2f7e0741,
http://localhost/phpmyadmin/index.php?db=testdb&token=9864dde57469a9aa4b6a2f7e0741,
http://localhost/phpmyadmin/index.php?db=testdb&token=986042d0dde57469a9aa4b6a2f7e0741,
http://localhost/phpmyadmin/index.php?db=testdb&token=986042d0dde57469a9a23&q=save
Not getting all values in $linksPieces , Getting only one value
But I am not getting this all string in PHP side; only getting first sub string which is before first comma(,).
I.E
http://localhost/phpmyadmin/index.php?db=testdb&token=42d0dde57469a9aa4b6a2f7e0741
PHP
$linksPieces = array();
$links = $_POST['linksString'];
$linksPieces = explode(",", $links);
foreach($linksPieces as $link)
{
//operation
}
I need to get all the string in array on PHP side.
If I am sending these type of url which have not any = then working fine.
http://in.yahoo.com/
http://www.hotmail.com/
http://www.google.com/
http://www.blah.com/
http://www.blah1.com/
You can try using encodeURIComponent() in Javascript before sending this string and using urldecode() in PHP before using this string.

Passing PHP-generated JSON via semantic markup

In another question, it was pointed out that using semantic markup can be a really clean way to pass data to an onclick function, along the lines of the code below.
I have a second question relating to passing JSON and having the receiving function recognize it as such. I have a PHP generated JSON value of [{"authed":"2012-03-04 17:24:24"},{"authed":"2012-03-04 11:44:38"}] that I need to pass to a function. echoing that straight into the <a> tag won't work, so I am using urlencode() to get:
click
Unfortunately, when I alert this out from popup(), I via the following code:
function popup(t) {
var auth = t.getAttribute('data-auth');
alert(decodeURI(auth));
}
I get
[{"authed"%3A"2012-03-04+17%3A24%3A24"}%2C{"authed"%3A"2012-03-04+11%3A44%3A38%22"}]
which JSON.parse() is unable to handle. Any suggestions on decoding/passing JSON using this pattern?
You need to use htmlspecialchars() to escape for html--like you should be doing for everything you echo out in html. (You are doing that right? To prevent generating invalid html?) Don't use urlencode(), which is for encoding parts of a url path or query parameter.
<?php
$data = array(array('authed'=>'2012-03-04 17:24:24'), array('authed'=>'2012-03-04 11:44:38'));
$jsondata = json_encode($data);
?>
<a data-auth="<?php echo htmlspecialchars($jsondata, ENT_COMPAT, 'UTF-8')?>" onclick="popup(this)">click</a>

Passing get parameter from javascript to php destroys formatting

I format text with javascript asigning + to every emtpy space like this
var ft = text.replace(/ /g,"+");
Then I pass ft to a php script via jquery ajax as an get argument.
But
print $_GET['text'];
gives me the text with empty spaces instead +.
Any ideas?
You should get familiar with the concept of URL encoding.
PHP's urldecode function will run against all $_GET variables by default, so if you want to see raw input, use rawurldecode:
$encoded = array_map('rawurldecode', $_GET);
echo $encoded['text']; //blah+blah
Also, it's a good idea to use JSON to pass data from javascript to PHP.

Categories