Append user data to url before sending request in PHP - javascript

What would be the easiest way to append form data to a json url prior to sending the request? I know next to nothing about php but Im trying either way
The PHP I have so far, I need to replace the ZIP before.json with the content im getting from $_GET['zip']
<?php
$zip = $_GET['zip'];
$zip_data = file_get_contents($zip);
$weather_data = file_get_contents("http://api.wunderground.com/api/myapi/conditions/q/ZIP.json");
echo $weather_data;
?>

In PHP if you just put the variable name inside a string that is quoted with double quotes, it puts the value into the string:
$weather_data = file_get_contents(".../q/$zip.json");
You can also put curly brackets around it to make it cleaner to read:
$weather_data = file_get_contents(".../q/{$zip}.json");
Or you can close the string, use the dot operator to concatenate, and reopen the string:
$weather_data = file_get_contents(".../q/" . $zip . ".json");

Replace
"http://api.wunderground.com/api/myapi/conditions/q/ZIP.json"
With
sprintf("http://api.wunderground.com/api/myapi/conditions/q/%s.json", $_GET['zip'])
(or whatever variable you want to take it's place)
More on string formatting with sprintf

Related

Problem with strings using slash (/) in PHP

I have some id (primary keys from database) with the next format: 2019/34. I show this code in a table where i can see it normally. The problem comes when i try to send this variable in PHP to a javascript method. As im using a slash in the id, when i send the php variable as parameter of the javascript method, it makes the count. It divides 2019 and 34 when i want to send the parameter 2019/34.
I have tried to parse the actual php string variable to string before send it through the parameter.
I have tried to send the parameter using quotes but it makes the count too.
I have even tried to separate the id (2019 and 34), send them to the javascript method using two parameters and making again the complete string in the method. But when i use the explode method (explode("/",$id)), it makes the count again.
echo "<td><a href='javascript:newConcepto(".$id.")'></a></td>"
Expected object sended: "2019/34".
Actual object sended: "59.3823529" (The division of 2019 and 34).
When you don't put the variable in quotes (from a JavaScript perspective), it assumes that you're doing math - as 2019 / 34 is a mathematical equation. Wrap it in quotes, and it becomes a string instead! To avoid collision with the href attribute, use doublequotes there - and to avoid conflict with the PHP double quotes, escape them.
echo "<td></td>";
PHP variables are parsed within double quotes, so you don't need to concatenate the value either, you can do it all inline. There's nothing wrong with doing it either though, by doing newConcepto('".$id."').
Try this
echo "<td><a href='javascript:newConcepto('".$id."')'></a></td>"

json_encode() gives special charactors like '\n'..how can i replace them in PHP?

I encoded an array using json_encode() function and it gave me a string like this..
"[{"details":"power - 2000w \nac-220-240v \/ 50-60hz\n369 degree cordless base\n","model_id":"MC-EK3428 \/ MC-EK3328"}]"
as you can see it contains special characters like "\n"..I want these special characters to be replaced with "" because in javascript I am using the JSON.parse(); function to convert this string to an object..
but it gives me an error
syntaxerror : missing ) after argument list
I think this is because of the special characters in the string..how can I escape these?
Edit
php :
$view->jsonencoded_array = json_encode($array);
javascript :
var products = JSON.parse('<?php echo $jsonencoded_array; ?>');//this line gives me the error
update :
found out that the error is given in this :
'<?php echo $jsonencoded_array; ?>'
The problem here is that \n (and various other combinations) have special meaning inside a JavaScript string, and you are dumping your JSON into a JavaScript string without doing any conversion of those characters.
Since JSON is heavily inspired by JavaScript literal syntax, you can use json_encode to convert a PHP string into a JavaScript string.
There are some gotchas, the main one being that </script> can appear in a JSON text without causing any problems, but having that in the middle of your JavaScript <script> element is going to cause the HTML parser to cut off your JavaScript in the middle of the string … but PHP's default encoding rules will generate <\/script> which solves that problem.
So:
<?php
$json_array = json_encode($array);
$javascript_string = $json_encode($json_array);
?>
var products = JSON.parse(<?php echo $javascript_string; ?>);
That said. A JSON array is also a JavaScript array, so you can skip that step entirely.
<?php
$json_array = json_encode($array);
?>
var products = <?php echo $json_array; ?>;
There must something that you are missing or there is some other reason for your issue while parsing in JavaScript; because json_encode handles \n and other special characters such " \ etc. very well and escape them properly without any explicit work.
I would suggest you to check the JSON produced and you are supplying to JavaScript and see if there is something missing in between.
Note: You can do a str_replace but it is not advised. Better stick to json_encodesince its s standard function and it works well.
Edit:
You should be echoing $view->jsonencoded_array not just $jsonencoded_array, no need to parse already JSON object.
php :
$view->jsonencoded_array = json_encode($array);
javascript :
var products = <?php echo $view->jsonencoded_array; ?>;
json_encode() twice helped me to solve this issue..
$view->jsonencoded = json_encode(json_encode($array));

document.getElementById call to inner html works with $_POST and $_GET variables but not with ordinary php variables

I'm quite baffled. I can put in variables from a $_GET or $_POST array into the innerHTML of an element, but I can't put in the text from an ordinary php variable. Here's my code:
$msg = "We don't recognize that password. Please try again.";
echo "<script>document.getElementById('alert').innerHTML='".$msg."';</script>";
//echo "<script>document.getElementById('alert').innerHTML='".$_POST['email']."';</script>";
The commented out line works great, but the one using $msg doesn't. I've also tried this without success, so substituting in plain old text doesn't work either.
echo "<script>document.getElementById('alert').innerHTML='hello';</script>";
Any ideas about what else I could try? I want to print something other than a $_POST or $_GET variable to the screen.
Thanks.
Use json_encode() when converting a PHP value to Javascript. It will ensure that the value is quoted and escaped properly. It also allows you to transfer more arrays to JS (JSON is a subset of Javascript literal notation for objects and arrays).
echo "<script>document.getElementById('alert').innerHTML=".json_encode($msg).";</script>";
Since this quotes the value, you don't need to include quotes in the JS part of the assignment.
It's the message, it contains a single quote that breaks it
$msg = "We don't ...."
// ^ here
you end up with
document.getElementById('alert').innerHTML= 'We don't ...';
Either escape it, remove it or replace it !

Escape an already encoded json string

at the moment i have to work with some json strings where the quotes are not correctly escaped. The strings looks like this
{ "foo" : "hello my name is "michael"" }
Is there any realistic chance in JS/PHP to escape the quotes in the value without doing it manually so i can parse the string?
You haven't provided us much to work with, but it looks like you're generating the json something like this way:
$userInput = $_GET['userInput'];
$json = '{ "foo" : "' . $userInput . '" }';
This is pretty bad. Here's the appropriate way to generate the json safely:
$outputData = array(
"foo" => $_GET['userInput']
);
$json = json_encode($outputData);
See the reference here: http://php.net/manual/en/function.json-encode.php
As to your original question, Is there any realistic chance in JS/PHP to escape the quotes? No. Suppose the "actual value" of the string is a series of paragraphs containing quote marks, you know, like a continuation of a quotation, where each paragraph starts with a ". No, that is not able to be fixed.
You need to fix the source of your json. If you are getting that json string from some third-party service, you need to tell them that the strings they are sending you is not valid json.

escaping single quotes for ajax calls

I have a php page which is called via AJAX. and basically it fetches some value from my database and echos back at table with inputs etc. The problem is when the string it fetches contains quotation marks(actually only single quotes seem to be effected). So on the php page there's something like this:
$value = htmlentities($DB_result->cloumn);
echo'<input type = "button" onClick = "$(\'#something\').val(\''.$value.'\');" />'
so if $value = "hello", no problems but if: $value = 'hello', the page which I'm making the AJAX call from throws up some such error: Syntax Error: unexpected identifier.
so I guess the quotations in $value have not been escaped, which I thought it would with the htmlentities. any Ideas how to solve this much appreciated. Thank you.
The problem is that $value contains single quotes, which interfere with the correct parsing of javascript. from the manual entry for html entities:
all characters which have HTML character entity equivalents are translated into these entities.
this means that your single quotes are not escaped, they are only translated in a way browsers will better understand. You need to use addslashes():
$value = htmlentities(addslashes($DB_result->cloumn));
"'hello'" will become "\'hello\'" which in the browser will look like:
<input type = "button" onClick = "$('#something').val('\'hello\'');" />
which will attribute the string 'hello' (with the single quotes) to the value attribute of $('#something')
Try:
$value = htmlentities($DB_result->cloumn, ENT_QUOTES, "utf-8");
Passing ENT_QUOTES through as a flag will convert both double and single quotes.

Categories

Resources