Making AJAX() call result into Cross-Origin Request Blocked error - php

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().

Related

calling on a complex function with onClick (ajax)

So I have this chunk of code here (below). It waits for a video to finish playing and then it looks up a cookie, sends that info to a php script through ajax, gets back a url from json, and reloads an iframe with a new url.
So I think you'll agree, it's sorta a lot going on.
Its purpose is to advance ONE forward in a playlist of videos. I am trying to create a button area where a user can click a >> sort of button and go forward. Which is exactly what this function does.
Rather than starting from scratch with a new function, is there a way to activate all of the above function functionality (ajax and all) when the user clicks that button?
<script>
function ready(player_id)
{
$f('play').addEvent('ready', function()
{
$f('play').addEvent('finish', onFinish);
});
function onFinish(play)
{
var now_video_var = $.cookie('now_video');
console.log ('player ' + now_video_var + ' has left the building');
var intermediate_integer = parseInt(now_video_var);
var request2 = $.ajax({
url : "geturl.php",
data : {intermediate_integer : intermediate_integer},
type : 'post'
}).done(function(data) {
var gotfrom = jQuery.parseJSON(data);
var NEWURL = gotfrom[1] ;
console.log(gotfrom);
console.log(data);
console.log(gotfrom[1]);
var theiframeforrealyo = document.getElementById('play');
$(theiframeforrealyo).attr("src", "http://player.vimeo.com/video/" + gotfrom[1] +"?api=1&player_id=play&title=0&byline=0&portrait=0&autoplay=1");
var new_video_var = intermediate_integer +1;
$.cookie('now_video', new_video_var);
console.log ( 'cookie function ok: the cookie is....');
console.log ($.cookie('now_video'));
});
}
}
window.addEventListener('load', function() {
//Attach the ready event to the iframe
$f(document.getElementById('play')).addEvent('ready', ready);
});
</script>

Processing PHP variable in javascript and returning back to PHP

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.

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

jQuery notifications, first not showing

I am using AJAX extensively and my PHP based notification system was not sufficient.
I have this function:
<script>
function user_notify($string, $class){
if($class == null){
$class = 'error';
}
$('<div class="' + $class + '"><div class="notification-text">' + $string + '</div></div>').hide().appendTo('#system-notifications').fadeIn('slow');
}
function DeleteTask(SpanName, TaskId){
if (confirm("Are you sure you want to delete this task?")) {
var curDateTime = new Date(); //For IE
var status = document.getElementById('status');
var poststr = "uniqueID=" + curDateTime.getTime() ;
var SpanName = SpanName;
if(SpanName == 'project_todos_complete'){
var showCompleted = 1;
} else {
var showCompleted = 0;
}
//alert (SpanName);
makePOSTRequest('http://*****webdesigns.com/project_manager/include/ajax/global.php?action=delete_task&showCompleted=' + showCompleted + '&id=' + TaskId, poststr, SpanName);
}
if(ajax_status == 4){
user_notify('Task deleted.', 'success');
ajax_status = null;
}
}
</script>
I have a global javascript variable that holds the readyState. If 4 is a response from the server, we can assume the AJAX was successful (I know, not neccessarily the cgi/php is execute if any). So I store that, and within the function that called the AJAX post, if the readyState is 4, I call the user_notify function.
It works beautifully with one exception: the first action that should trigger a notification does not. All consecutive actions successfully generate a message. It's not a specific action that doesn't work, just the first one.
The html:
<body>
<div id="system-notifications"></div>
<div class="wrapper">...</div>
What am I missing here?
UPDATE:
I am in the process of moving legacy javascript/Ajax calls to jQuery/Ajax. Everything works except one aspect: the targeted div does not 'refresh' with the return data from the .ajax jQuery call. The notification pops up (the first time and all consecutive times), the php executes (refreshing the page verfies this), but the div does not update with the html that the PHP script generates.
$('form#addToDoForm').submit(function(){
var project_id = $('#addToDoForm input[name=project_id]');
var assigned_id = $('#addToDoForm input[name=assigned_user_id]');
var description = $('#addToDoForm textarea[name=description]');
var responsible_id = $('#addToDoForm input[name=responsible_user_id :selected]');
alert(responsible_id.val());
return false;
var due = $('#addToDoForm input[name=due]');
var result_div = 'project_todos_' + project_id;
var query_string = 'action=add_to_do&id=' + project_id;
var ajax_url = 'http://avwebdesigns.com/basecamp/include/ajax/global.php?' + query_string;
var successMessage = '<b>' + description.val() + '</b> added.';
var data =
'project_id=' + project_id.val() +
'&assigned_user_id=' + assigned_id.val() +
'&responsible_user_id=' + responsible_id.val() +
'&description=' + encodeURIComponent(description.val()) +
'&due=' + encodeURIComponent(due.val()); // encodeURIComponent()
$.ajax({
type: 'POST',
url: ajax_url,
data: data,
cache: false,
success: function(data){
$('#'+result_div).html(data); // $('#'+result_div).html(data.returnValue);
user_notify(successMessage, 'success');
},
error:function(data){
$('#'+result_div).html(data);
user_notify(failureMessage, 'error');
}
});
return false;
});
Any ideas?
You are missing the non-blocking characteristics of an AJAX call probably. I can't really tell what makePOSTRequest does, but judging from your design I assume you expect it to be synchronous where it probably is not. Due to the asynchronous nature of an AJAX call, you need to pass a callback function to the call that is called when the AJAX request completes.
What probably happens in your case is that makePOSTRequest immediately returns and because the first request hasn't finished yet, ajax_status will not be 4 yet. Then, by the time the second request is sent, your first will have completed and your global variable will have been set to 4, so this time it works and this is also the cause why it works in all subsequent attempts.
This shows another flaw in your design: it's actually a very bad idea to capture the status of an AJAX request in a global variable. These requests are potentially sent in a concurrent fashion so you would have several requests that share one and the same variable - this calls for a 'race condition'. Have a look at the examples in the Ajax section of the jQuery documentation to see how to handle this correctly with the help of a callback function.

OPTIONS request being made for $.ajax

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.

Categories