I have the following code which,currently im running on my local machine.I am making a call to a php script called getxml.php,which should send the contents of an xml file as the response.
But,instead of a GET request, in Firebug i see that an OPTIONS request is being made, like
OPTIONS getxml.php . I think im not making a cross domain Ajax request,but still am facing this problem . Any way to fix this ?
var employee_list = new Object;
$(function(){
$.ajax({
type:"GET",
url:"http://localhost/projectname/getxml.php",
datatype:"xml",
success: function(xml){
$(xml).find('employee').each(function(){
var name_text = $(this).find('name').text();
var url_text = $(this).find('url').text();
employee_list[name_text] = url_text;
$('<li></li>').html(name_text + ' (' + url_text + ')').appendTo('#update-target ol');
});
} //closing function
}); //closing $.ajax
}); //closing $(
getxml.php
<?php
//Send the xml file as response
header('Content-type: text/xml');
readfile('employee_results.xml');
?>
Thank You
Make sure getxml.php exists. OPTIONS usually means you have a slight misspelling.
change datatype to dataType and see if that fixes your problem. The rest of the code looks right.
edit: also, I'm not a PHP pro, but I wrote a map application which uses a similar approach. To return xml, I used:
header("Status: 200");
header("Content-type: text/xml");
echo file_get_contents($q,0); /*$q is the query/filename*/
exit();
I remember reading somewhere that header("Status: 200"); was required.
edit: Here is how I've done the same thing. I hope this helps.
/* call ajax method to retrieve earthquakes */
$.ajax({
type: "GET",
url: "../getxml.php?q=" + xmlLocation,
dataType: "xml",
success: function(xml){
$(xml).find('entry').each(function(){
/* Retrieve all needed values from XML */
var title = $(this).find('title').text();
var summary = $(this).find('summary').text();
var coord = $(this).find('georss\\:point').eq(0).text();
if(!coord){var coord = $(this).find('point').text();};
var points = coord.split(' ');
var latitude = parseFloat(points[0]);
var longitude = parseFloat(points[1]);
var htmlString = "<div class=\"infowindow\"><b>" +
title + "</b>" + "<p>" + summary + "<br></div>";
var myLatlng = new google.maps.LatLng(latitude,longitude);
var marker = new google.maps.Marker(
{
position: myLatlng,
map: map,
title: title
});
markers[markers.length] = marker;
addInfoWindow(marker, map, htmlString);
$('#output').text("Showing " + markers.length + " earthquakes");
});/* end each */
}
}); /* end $.ajax */
The php file is exactly as I posted above, but with "security" to respond only to ajax requests.
Related
I was trying to send a form details to a folder containing the php script to process and validated it using AJAX() method ,
But I am getting "Cross-Origin Request Blocked" error . I know this is cross browser problem but I am not able to find out a solution for this .
Writing a Proxy server is one option . Can someone help me out with this I am very new to all this .
here is my code
<script>
*<![CDATA[*/
$(document).ready(function(){
$("#abusoForm #enviar").livequery("click", function(e){
e.preventDefault();
console.log("Click is working");
var hidden = $('#mensaje').val();
var category = $('#opcmarcar').val();
var name = $('#nombre').val();
var phone = $('#telefono').val();
var mail = $('#email').val();
var cf_mail = $('#confirma_email').val();
var k = ""
var z = "anotherdomain.com";
var otro = $('#otro_email').val();
var E = $("#abusoForm #enviar").val();
//Ajax call happening here
var vajx = $.ajax({
url: z,
type: "POST",
data: {
'h': hidden,
'c': category,
'n': name,
'p': phone ,
'm': mail,
'cm': cf_mail,
'otro1': otro,
"enviar": E,
async: false
}
}).responseText;
//Now I have to use the variable vajx to post a message about the submition of the form ;
$('#resultip').html(vajx);
})
});
/*]]>*/
</script>
I read this article http://www.html5rocks.com/en/tutorials/cors/ but cant understand much
. Another possiblity would be to use CORS but I am not getting it how to use the script to use with JQUERY function AJAX().
I am new to AJAX using jquery. I have a json response as below:
[{"customer_name":"Customer A"},{"customer_name":"Customer B"},{"customer_name":"Customer C"}]
And my ajax file is :
function(result){
$('#resdiv').html(result);
console.log(result);
var json_obj = $.parseJSON(result);//parse JSON
alert(json_obj);
var output="<ul>";
for (var i in json_obj)
{
output+="<li>" + json_obj[i].customer_name + "</li>";
}
output+="</ul>";
$('#resdiv1').html(output);
}
Though I can view the JSON response in div id resdiv, the div id resdiv1 is empty ! Also alert(json_obj); does not alerts anything ! Whats wrong with the file ?
NB: I am learning from Zuch Tutorial
You dont need to parse the json again.Simply do a iteration and try like this
var json = [{"customer_name":"Customer A"},{"customer_name":"Customer B"},{"customer_name":"Customer C"}];
var output="<ul>";
$.each(json,function(key,val){
output+="<li>" + val.customer_name + "</li>";
});
output+="</ul>";
console.log(output);
See DEMO
check this out
// Need to parse if string.
var result = '[{"customer_name":"Customer A"},{"customer_name":"Customer B"},{"customer_name":"Customer C"}]';
var json_obj = $.parseJSON(result);//parse JSON
// No need to parse
var json_obj = [{"customer_name":"Customer A"},{"customer_name":"Customer B"},{"customer_name":"Customer C"}];
Also check this
// if undefined, you don't have resdiv1 div or you have call function before your div render.
alert($('#resdiv1').html());
Can you try this
function(result){
$('#resdiv').html(result);
console.log(result);
var json_obj = $.parseJSON(result);
//parse JSON alert(json_obj);
var output="<ul>";
$.each(json_obj,function(key,val){
output+="<li>" + val.customer_name + "</li>";
console.log(key+":::"+val);
});
output+="</ul>";
$('#resdiv1').html(output);
}
I wrote a JavaScript function to convert GeoJson data to WKT format. It works when i get the input value in the javascript code directly. But I don't know how to get the input from the php and send it back.
Here is the php code:
<?php
$geojson=file_get_contents("clipfeature.geojson");
$WKT = $_POST['wkt'];
echo ($WKT);
?>
So it gets geojson data from a file and I want to receive the converted WKT code from the Javascript function.
Please help me finish the JavaScript Code:
function converttoWKT (){
$.ajax({
type: "GET",
url: "readJson.php",
contentType: "application/json"
}).done(function (data) {
var JSONObject = How to give the value from PHP to this Variable;
var coordinate = JSONObject.features[0].geometry.coordinates;
var type= JSONObject.features[0].geometry.type;
var coordinate1 = "";
var coordinate2 = "";
for (var i=0; i< coordinate[0].length; i++) {
coordinate1= coordinate[0][i][0]+" "+coordinate[0][i][1];
coordinate2=coordinate1+","+coordinate2;
}
var WKT= "\""+ type + "((" + coordinate2;
WKT=WKT.substring(0,WKT.length-1);
WKT=WKT+"))\""
sendback ( );
});
function sendback(){$.post("readJson.php",
{'wkt':How to send the value of var WKT back to php 'wkt'
});
}
Basically:
var jsVar= "<? echo $myVariable_value_goes_in_here; ?>";
or, as mentioned above:
var JSONObject = <? echo json_encode($WKT); ?>;
// this NEED TO BE json, otherwise syntax error in JS!
Since you already know your return data will be JSON, you can just use $.getJSON() for convenience. This is a $.get() request paired with JSON.parse(). With $.getJSON(), the JSON is parsed on response. To send the data back, just use use jQuery's $.post().
Here's an edited version of your code.
function converttoWKT() {
$.getJSON('clipfeature.geojson', function(data) {
var coordinate = data.features[0].geometry.coordinates;
var type = data.features[0].geometry.type;
var coordinate1 = '';
var coordinate2 = '';
for(var i = 0; i < coordinate[0].length; i++) {
coordinate1 = coordinate[0][i][0] + ' ' + coordinate[0][i][1];
coordinate2 = coordinate1 + ',' + coordinate2;
}
var WKT = '"' + type + '((' + coordinate2;
WKT = WKT.substring(0, WKT.length - 1);
WKT = WKT + '))"'
sendback(WKT);
});
};
function sendback(data) {
$.post('readJson.php', {
'wkt': data
});
};
I am working on an application where I fetch data from database and process it using javascript/jquery like this:
$sqlEdit = "select revisionContent from tbl_revision where revisionId='".$_SESSION['contentId']."'"; //Query to fetch the result
$rsEdit = $dbObj->tep_db_query($sqlEdit);
$resEdit = $dbObj->getRecord($rsEdit);
$IdLessContent = $resEdit['revisionContent'];
<script language="javascript">
var getSavedContent = '<?php echo json_encode($IdLessContent); ?>';
var trimmedCont=($.trim(getSavedContent).slice(1));
//console.log(trimmedCont);
var lengthCont= trimmedCont.length;
var trimmedCont=$.trim(trimmedCont.slice(0,lengthCont-1));
console.log(trimmedCont);
var test = $('<div class="addId">');
test.append(trimmedCont);
//console.log(test.html());
test.children().each(function(index, value) {
$(this).attr('id', "com-"+randomString());
});
//console.log(test.html());
viewContent = test.html();
I get the required data in viewContent.I want to display it on the page in this section
<div id="mainWrap" onClick="fnDestroyEditable();">
<?php echo $resEdit['revisionContent']; ?> //THis is the unprocessed data displayed directly from database.I want to display the processed data here
</div>
I know we cannot get javascript variables to PHP as both are different (one server side and other client). But then how can I achieve this in my scenario?
EDIT I would like to add that the returned data is HTML stored in the database.So,I get the html->process it(add id attribute)->want to return back after processing
you can put the viewContent inside #mainWrap using javascript.
just make sure the DOM is loaded wrapping your js code with $(document).ready()
and add:
$('#mainWrap').html(viewContent);
at the end of your function.
$(document).ready(function () {
var getSavedContent = '<?php echo json_encode($IdLessContent); ?>';
var trimmedCont=($.trim(getSavedContent).slice(1));
//console.log(trimmedCont);
var lengthCont= trimmedCont.length;
var trimmedCont=$.trim(trimmedCont.slice(0,lengthCont-1));
console.log(trimmedCont);
var test = $('<div class="addId">');
test.append(trimmedCont);
//console.log(test.html());
test.children().each(function(index, value) {
$(this).attr('id', "com-"+randomString());
});
//console.log(test.html());
viewContent = test.html();
// put viewContent in the innerHtml of your wrapper
$('#mainWrap').html(viewContent);
});
if you need to send back info to the server you have to do it with ajax.
I added a javascript function addId() that will be invoked on click on one of the elements.
the new code is:
$(document).ready(function () {
var getSavedContent = '<?php echo json_encode($IdLessContent); ?>';
var trimmedCont=($.trim(getSavedContent).slice(1));
//console.log(trimmedCont);
var lengthCont= trimmedCont.length;
var trimmedCont=$.trim(trimmedCont.slice(0,lengthCont-1));
console.log(trimmedCont);
var test = $('<div class="addId">');
test.append(trimmedCont);
//console.log(test.html());
test.children().each(function(index, value) {
$(this).attr('id', "com-"+randomString());
});
//console.log(test.html());
viewContent = test.html();
// put viewContent in the innerHtml of your wrapper
$('#mainWrap').html(viewContent);
$('#mainWrap .addId').children().click(function({
addId(this);
}));
}
addId = function(elem){
// elem is the child element you clicked on
// $(elem).attr('id') should be "com-[randomString]"
$.ajax({
type: "POST",
url: "path/to/php/script", // update id PHP script
data: data, // whatever you need in json format
dataType: "json",
error: function() {
// error function you want to implement
errorFunction();
},
success: function(resp) {
// do whatever you need with the response from you PHP action
}
});
};
if you need to to call server with out human interaction just substitute
$('#mainWrap .addId').children().click(function({
addId(this);
}));
with:
$('#mainWrap .addId').children().each(function({
addId(this);
}));
if I undesrstand you, you shold only add in the end of your js code this line:
$('#mainWrap').html(viewContent);
If you want to send JS data to PHP, you should use ajax request.
so lets say this is my jquery portion of the code:
$.ajaxSetup ({
cache: false
});
load() functions
var loadUrl = "load.php";
$("#load_basic").click(function(){
$("#result").load(loadUrl + "?language=php&version=5");
});
});
and this is "load.php"
<?php $_GET['language'] .= "cool"; $_GET['version']+=2; ?>
How do I return the processed language and version vars back to my #result div?
Sorry if I'm doing this wrong. Pretty comfortable in php and jquery, but ajax sort of confuses me and I haven't found any tutorials that really clicked.
I know I can echo these vars out, and that will return the contents of load.php into my div.. but that seems clunky, and I doubt that's the way people actually do it..
JQuery
$("#load_basic").click(function(){
$.get(loadUrl + "?language=php&version=5", function(data){
var obj = eval(data)
$("#result").html(obj.language + " " + obj.version)
});
});
PHP
<?php $_GET['language'] .= "cool"; $_GET['version']+=2;
echo "{\"language\" : \"".$_GET['language']."\",\"version\" : \"".$_GET['version']."\"" ?>
not tested and not bullet-proof, but the concept is here. Return somthing in your PHP that you can read back (i choose JSON)
" What If I'm echoing out two or three vars in php, and I want them to be seperated and echoed out to different divs.. "
I'm ASP and not PHP but I think the prinicple is the same.
I have this is my requesting page:
<script type="text/javascript">
$(document).ready(function(){
$("#list").change(onSelectChange);
});
function onSelectChange(){
var selected = $("#list option:selected").val();
var bob = $("#list option:selected").text();
if (selected.length > 0) {
$.post("twopart.asp", { thing: selected, bob: bob }, function(data) {
var dataraw= data;
var dataarray = (dataraw).split("~~~");
var outone= dataarray["0"];
var outtwo= dataarray["1"];
var outthree= dataarray["2"];
$("#output1").html(outone);
$("#output2").html(outtwo);
$("#output3").html(outthree);
});
}
}
</script>
and this is in my processing page:
response.write bunch of stuff and ~~~
response.write bunch of stuff and ~~~
response.write more stuff
Sorry is the formatting is off- still learning how to do it.
Anyway, the "echoing page" echos its content with the three tildes stuck in there. Then I parse the return on the tildes and write different places.
Hope this is helpful.
The JSON answer by Grooveek is probably better.
try
$.ajax({
url:YOUR_URL,
dataType:'json',
type:'POST',
data:'&var1=value1&var2=value2',
beforeSend:function(){
//
},
success:function(response){
//complete
$('#container').html(response.result + ' ' + response.other);
}
});
in your php
$var1 = $_POST['var1'];
//your proccess
$result = array(
'result' => 'ok',
'other' => 'value'
);
echo json_encode($result);