is my code victim of same origin policy? - php

Here is my code. You have to kindly look does it suffer from 'same origin policy' in this shape. The domain for HTML is (http://127.0.0.1/jqload.html) & php file (http://127.0.0.1/conn_sql.php). This is json format : [{"options":"smart_exp"},{"options":"user_int"},{"options":"blahblah"}]
I actually want to append json data that I receive in HTYML with user input & I am suffering in that. If I use eval for parsing, it works fine to point its put here. But if I use JSON.parse to parse, the whole code stops working & this error message is issued '"IMPORTANT: Remove this line from json2.js before deployment". I put my code for some other question on stackoverflow forum & I was told that my code suffer from 'same origin policy' that causes the problems in appending JSON data. So can you kindly see does my code suffer from this policy? Though I have doubts it suffers from that policy as I learn that it restricts if files reside on different domains, here both files reside next to each other.
Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html><head></head>
<body>
<form name="index">
<p><input type = "text" id = "txt" name = "txt"></input>
<p><input type = "button" id = "send" name = "send" value = "send" onClick=
"ADDLISTITEM"></input>
<p><select name="user_spec" id="user_spec" />
</form>
<script>
function ADDLISTITEM()
{
alert (json.length); // working
alert json.options[1]; // do not show any value, message just for testing
json.options[json.length+1] = 'newOption'; //not working; HELP HERE
jsonString = JSON.stringify(json);//working fine for current data
alert(jsonString);
//here I have to implement send this stringify(json) back to server,HELP
//HERE
}
</script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var json;
$(document).ready(function() {
jQuery .getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
json = jsonData;
$.each(jsonData, function (i, j) {
document.index.user_spec.options[i] = new Option(j.options);
});
});
});
</script>
</body>
</html>

You're on the right track, but here: $.each(jsonData, function (i, j) { ... } you are actually looping through each character of the jsonData string, and not the json object. Just change jsonData to json inside the $.each(), and it should work fine (regardless of whether you're using eval or JSON.parse, but I recommend the latter).
Edited: Since you are using jQuery.getJSON(), you don't need to use eval or JSON.parse - jQuery does it for you. So inside your callback function, just set json = jsonData .
<script>
var json;
$(document).ready(function() {
jQuery .getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
json = jsonData;
$.each(json, function (i, j) {
document.index.user_spec.options[i] = new Option(j.options);
});
});
});
</script>

Related

Ajax is driving me nuts. Why is Jquery post method failing in this specific case?

Ok, so ajax seems to be misbehaving. In other words i'm doing something wrong. I have a simple angular js app. The html looks like this:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="../scripts/form_controllers.js"></script>
</head>
<body ng-app="EditDocApp">
<div ng-controller="EventDetector">
<input ng-model="event">
<button ng-click = "SelectEvent()">Click</button>
</div>
</body>
</html>
form_controllers.js contains a call to the Jquery post method in the EventHandle angular service. This is invoked in the calling of EventHandle.ajaxRequest() in the $scope.SelectEvent method in the EventDetector controller. This is form_controllers.js:
var editDocApp = angular.module("EditDocApp", []);
editDocApp.controller("EventDetector", eventDetector)
.factory("HandleEvents", handleEvents);
function handleEvents() {
var pass_back = {
ajaxLastReturn: "one",
ajaxRequest: function() {
$.post("http://localhost/TrailGuide/Website/Interface/webDataModelBuild/Documentation/scripts/test1.php", {}, function(response) { alert(response); })
.fail(function() { alert("nah"); });
}
}
return pass_back;
}
function eventDetector($scope, HandleEvents) {
$scope.event = "";
$scope.SelectEvent = function() {
$scope.event = "select";
HandleEvents.ajaxRequest();
};
}
The $.post method is failing every time i execute it by calling $scope.SelectEvent() from the button in the view (an alert box with "nah" pops up). I've tested the address passed to $.post by copying and pasting to the browser address box and it runs fine. I've tried the $.post method with and without data, no dice. I've tried jquery.ajax, still no dice. The php file, test1.php, is as follows:
<?php
echo "I am here!";
?>
Can somebody please point out what i am missing here? Is there some setting in php.ini that could be effecting this? Btw, this is my very first post on stack overflow so go easy on me! I'll get the hang of it. Thanks a bunch!

Generate json with url built from form

I'm trying to create a form that is capable of generating multiple urls, depending on the input by the user. The created url has a json extension. A php file is used to get the contents of that url. This php file has to have the same contents as the inputted url has. This php file is used as input for a javascript/jquery file.
In this file I'm trying to convert the json code to an html table. This is done by an http_request. The table has to be outputted in a div on the html page. However my code doesn't work due to errors I can't find. I've already looked at simular questions at stackoverflow and google, but could find the fix that made my code working.
I'm applying this code to spotify lists. This is the code I already have:
html:
<script type="text/javascript" src="spotify.js"></script>
<form id="spotifyform" action="spotifylist.php" method="post">
<select id="country" name="country">
<option value="GB">UK</option>
<option value="US">USA</option>
</select>
<select id="interval" name="interval">
<option value="daily">Daglijst</option>
<option value="weekly">Weeklijst</option>
</select>
<select id="chart" name="chart">
<option value="most_streamed">Meest gestreamd</option>
<option value="most_viral">Meest gedeeld</option>
</select>
<input type="submit" name="formSubmit" value="Submit"/>
</form>
<div id="spotifylist"></div>
spotify.js:
function loadJSON()
{
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.open("GET", "spotifylist.php", true);
http_request.send();
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 )
{
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.artist_name and jsonObj.track_name.
HTML = "<table id='chart'> <thead><tr id='row2'><th id='dw'></th><th id='song'>Artiest</th><th id='song'>Titel</th></tr></thead><tbody>";
var x=jsonObj.tracks;
for (i=0;i<x.length;i++)
{
HTML += "<tr id='row1'><td id='dw'>";
HTML += i+1;
HTML += "</td><td id='song'>";
HTML += x[i].artist_name;
HTML += "</td><td id='song'>";
HTML += x[i].track_name;
HTML += "</td></tr>";
}
HTML += "</tbody></table>";
document.getElementById("spotifylist").innerHTML = HTML;
}
}
}
$("#spotifyform").submit(function(){
loadJSON();
return false;
});
spotifylist.php
<?php
if($_POST['formSubmit'] == "Submit")
{
$chart = $_POST['chart'];
$country = $_POST['country'];
$interval = $_POST['interval'];
}
$data_file="http://charts.spotify.com/api/tracks/".$chart."/".$country."/".$interval."/latest";
$url = file_get_contents ($data_file);
echo $url;
?>
What currently goes wrong is that the php file is loaded when I press the submit button. This file contains the right json information. However this json isn't converted to a html table.
I would really appreciate it, if anybody could help me fix this problem
If you want the spotifylist div to load in the data when you press submit, you have to prevent the page from redirecting.
Make the form action:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'])?>
And if possible, your input values (if you have any within the form tags):
"<?php echo $_POST['value']?>"
If you can, place your HTML code within a PHP file which executes everything from spotifylist.php.
There are a couple of problems in my guess.
You send your Form to the spotifylist.php which grabs an file and sends something back to the html. Probably JSON but where did you handle that data?
Maybe some Javascript which does something with that "string" that your php sends back?
And your loadJSON sends (whenever) a GET Request to the same php but without parameters or something.
So your php run into an error because there obviously no POST variables set, so your variables inside your if condition will never set ergo your data which comes back again?!? with errors
You should first get clear which technique you want to use.
It seems to me as you would take a little of both.
There are multiple ways to get information from an external server:
httprequest - not recommend, because of bad user experience.
file_get_contents - usually easy, but in this case it requires a lot of data handling. Php works server-side and javascript works client-side. It requires a lot more work to let these two work together.
$.ajax - in this case the best solution, because it doesn't require any php and $.ajax is able to directly parse the json data. Because the data is requested from an external site, you have to change the datatype to jsonp and perform a callback function.
It is very easy to transfer the data from the form to javascript:
// Automatically call this function when the page loads.
window.onload = function loadJSON()
{
// The HTML input of the form that is the input of this javascript document
var country2 = document.getElementById("country");
var chart2 = document.getElementById("chart");
var interval2 = document.getElementById("interval");
Build the url with the selected parameters on submit:
// Call the function when the form is submitted
$("#spotifyform").submit(function(e)
{
e.preventDefault(); // to prevent the page from reloading
// Save the choice of the <select> country in a variable named country2
var country = country2.options[country2.selectedIndex].value;
var chart = chart2.options[chart2.selectedIndex].value;
var interval = interval2.options[interval2.selectedIndex].value;
var url = "http://charts.spotify.com/api/tracks/" + chart + "/" + country + "/" + interval + "/latest"; // build url
Then get the right data and parse it directly with the json native parser.
// Get the data from the site and save this into the variable 'json'
$.ajax
({
'url': url + '?callback=?', // ?callback=? lets the server generate a function name, the call can be handled in the success parameter
'dataType': 'jsonp', // Cross site request via jsonp
'error': function(xhr, status, error){ alert(error.message); },
'success': jsonParser // call function
}); // $.ajax
}); // $("#spotifyform").submit(function(e)
} // window.onload = function loadJSON()
Then do with the data whatever you want. You don't need to do an httprequest and you don't have to parse the data anymore.
function jsonParser(json)
{
HTML = "<table id='chart'> <thead><tr id='row2'><th id='dw'></th><th id='song'>Artiest</th><th id='song'>Titel</th></tr></thead><tbody>";
var x=json.tracks;
for (i=0;i<x.length;i++)
{
HTML += "<tr id='row1'><td id='dw'>";
HTML += i+1;
HTML += "</td><td id='song'>";
HTML += x[i].artist_name;
HTML += "</td><td id='song'>";
HTML += x[i].track_name;
HTML += "</td></tr>";
}
HTML += "</tbody></table>";
document.getElementById("spotifylist").innerHTML = HTML;
} // function jsonParser(json)

Ajax/ Jquery in Zend framework

I’m using Zend framework (php) and I’m trying to submit a from using ajax/jquery.
Here’s the .phtml:
<form id="find">
<input type="text" name="name">
<input type="submit" id="submit" value="Submit">
</form>
Here’s the ajax/jquery part:
$(document).ready(function() {
$("#submit").click(function(){
$.ajax({
type:'POST',
url: "<?php echo SITE_URL;?>Training/test",
data:$('#find').val(),
success: function(response) {
alert (response);
}
});
});
});
Here, “Training” is the controller and “test” is the action inside the controller. The action has just 1 line of code which is echo “hello”. After the user types a number in the box and clicks on “submit”, the control has to go to the controller thus displaying “hello” on success. However, nothing happens when I click on it. Please help me. Thanks in advance.
You didn't name parametr in Ajax call
data:$('#find').val(),
change it to
data:{'param': $('#find').val()},
About Zend it doesn't matter if it's zend or not. You can handle request just providing proper URL. You can access param value in Zend via $this->getParam('param') method.
Also you don't prevent default submit action. Change your function to:
$("#submit").click(function(ev){
ev.preventDefault();
or use in the end of function return false;
I did not test your jQuery. But note you need the instruction event.preventDefault to ensure you haven't the normal form submit action.
The main problem is at your zend Controller because you need a
special response. I suppose you have a controller to perform the request logics. I'll name it AjaxController and I'll name the action ajaxrecuestAction to illustrate how to send a proper response.
<?php
// Filename: yourProject/module/ModuleName/src/Controller/AjaxController.php
namespace ModuleName\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class AjaxController extends AbstractActionController {
public function ajaxrecuestAction(){
// This function is called by zend to procces your ayax request
// you must test if it's an xmlHttpRequest
$request = $this->getRequest();
$is_xmlHttpRequest = ($request->isXmlHttpRequest()) ? 1 : 0;
if(!$is_xmlHttpRequest){
// If not you must return a normal page, a message page
// perhaps a forgiven message page, etc. It depends on your site
// logics
}else{
// The solution's KEY
// You must disable the zend's normal output
$viewmodel = new ViewModel();
$viewmodel->setTerminal($is_xmlhttprequest);
// Proccess the input and prepare your output
$output = CallTheLogicsToPrepareIt($request->getContent());
// send your response
$response = $this->getResponse();
$response->setContent($output);
return $response;
}
}
**EDIT: Just noted that, in your HTML, you didn't give an ID attribute to the "find" field. Therefore $('#find').val() will give you an error, something like "cannot find method val() of undefined. Add the id=find tag to your and it should work.
** Other Edit: Sorry about the confusion. Your form has id=find but what you want to send to the server (I believe), is the value of the fields. So give an ID=name to your input then use:
var data = {find: $('#name').val()};
You should start by using your console to see if the event is triggered. Something like:
<script>
$(document).ready(function() {
$("#submit").click(function(e){
e.preventDefault ? e.preventDefault() : e.returnValue = false; //This will prevent the regular submit
console.log('Hello');
});
});
</script>
(You do use Fire bug or the Chrome dev tools, right) ? If not, look at the end of this post.
If you can see the Hello in your console, you're on the right path. Then try to set your url in a variable and try to check it in your console:
<script>
var url = "<?php echo SITE_URL;?>Training/test";
$(document).ready(function() {
$("#submit").click(function(e){
e.preventDefault ? e.preventDefault() : e.returnValue = false; //This will prevent the regular submit
console.log(url);
});
});
</script>
Then you should see the url in the console, meaning you're still doing good.
If that works, try to set the data and check the output in the same way:
<script>
var url = "<?php echo SITE_URL;?>Training/test";
var data = {
find: $('#find').val()
};
$(document).ready(function() {
$("#submit").click(function(e){
e.preventDefault ? e.preventDefault() : e.returnValue = false; //This will prevent the regular submit
console.log(data);
});
});
</script>
Hoping everything still works (you saw the data), then try the actual full code and see if you have an error or something. Also, be sure to include an error function to your ajax call so you will have a response if something went wrong on the server.
<script>
var url = "<?php echo SITE_URL;?>Training/test";
$(document).ready(function() {
$("#submit").click(function(e){
e.preventDefault ? e.preventDefault() : e.returnValue = false; //This will prevent the regular submit
var url = "<?php echo SITE_URL;?>Training/test";
var data = {
find: $('#find').val()
};
$.ajax({
type:'POST',
url: url,
data: data,
success: function(response) {
alert (response);
},
error: function(resp) {
alert(resp.responseText);
}
});
});
});
</script>
Some tools to help you out:
If you are using FireFox, use FireBug for your debugging: https://addons.mozilla.org/fr/firefox/addon/firebug/
If you are using Chrome (my personal favorite), learn a bit more about Chrome Developer Tools: https://developers.google.com/chrome-developer-tools/?hl=fr
If you are using IE, please switch to something else for development purposes, then try it in IE to make sure you code is compatible (most likely won't be but it will be easier to find out why it doesn't work afterwards).
As for the line e.preventDefault......, look into this SO post for more details: https://stackoverflow.com/a/15913969/1483513
Hope this helps !

AJAX post returns HTML tags with the particular value

I'm trying to write a code that adds user comment using jquery's post.I passed parameters to ajax.php and received josn data, as the following:
var formObjectData = $('#' + form_id).serialize() + '&flag=add_comment'; // all
$.post(
'http://192.168.3.3/myblog/ajax.php',formObjectData,
function(data) {
if (!data)
alert("No data");
else {
if (data.msg!='')
$("#add_comment").html(data.msg);
}
},
'json'
);
on ajax.php
$cid = $classobj->add_comment($comment,$id); // to add the comment in db and return the comment id
$ajax['msg'] = $msg ? $msg : '';
if ($cid) {
$ajax['cid'] = $cid;
}
echo json_encode($ajax);
My problem is the jquery returns many irreverent html tags wihth the json data as the below
<html>
<head>
<style type="text/css">
</style>
</head>
</html>{"msg":"hello","cid":"600"}
what is the easest way to solve this problem?
Thanks in advance!!
If your ajax.php file contains any style or HTML, you will be given that data back when you perform your AJAX request. Remove any styling or HTML from your ajax endpoint. A simple way is to exit() or die() after the JSON encode (if there is HTML after it) or just remove it totally.
Also, remember to include the following code before json_encode($ajax):
header('Content-Type: application/json'); - this will ensure it is always recognised as a JSON object. I know Chrome certainly has problems inferring what your sending back is actually JSON!

javascript based Jquery ajax function, unable to send post values

Hello this is code snippet which i get from Jquery Ajax based search
I am done with everything, just the problem is the following script may not be sending the POST variable and its values or may be i am not properly fetching it.
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function() {
$("input[name='search_user_submit']").click(function() {
var cv = $('#newInput').val();
var cvtwo = $('input[name="search_option"]:checked').val();
var data = 'cv=' + cv + '&cvtwo=' + cvtwo; // sending two variables
$("#SearchResult").html('<img src="../../involve/images/elements/loading.gif"/>').show();
var url = "elements/search-user.php";
$.post(url, {
contentVar: data
}, function(data) {
$("#SearchResult").html(data).show();
});
});
});
});//]]>
</script>
In php file i have the following code:-
if (isset($_POST['cv']))
{
// My Conditions
}
else
{
// Show error
}
And its showing error, This means everything is correct just the post is not working properly, maybe.
Do the var data = 'cv=' + cv + '&cvtwo=' + cvtwo; // sending two variables will do the needful or we need to do any modifications. I know questions like this really annoy people, but what should i do i am stuck up.. #userD has really helped me a lot just, this part is left.
Since you're using $.post instead of $.ajax, your call should be:
$.post(url, data, function(response) {
/// ...
});
data must be a Javascript object, like this:
data = { "cv" : cv, "cvtwo" : cvtwo };
Check Jquery's documentation for more info:
http://docs.jquery.com/API/1.1/AJAX#.24.post.28_url.2C_params.2C_callback_.29

Categories