I am using a free hosting site so that I can show my group the website I am currently working on. A problem I keep see occurring is that in the console there's the error:
XMLHttpRequest cannot load http://error.hostinger.eu/?. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://sampleclickinggame.esy.es' is therefore not
allowed access.
The URL is: http://sampleclickinggame.esy.es/index.html
The URL is: http://sampleclickinggame.esy.es/index.php
Both of the files produce the error
I have tried to use the PHP method of it but that doesn't work, I have also added an ajax version but that doesn't do anything. I mainly want to keep the file format as html, but if I need to change it I will.
UPDATE
The code:
<?php
header("Access-Control-Allow-Origin: *");
?>
<!DOCTYPE html>
<html>
<head>
<title>IO Chat</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.js"></script>
<script src="jquery.js"></script>
<script>
$.ajax({
url: "sampleclickinggame.esy.es",
type: method,
// This is the important part
xhrFields: {
withCredentials: true
},
// This is the important part
data: data,
success: function (response) {
// handle the response
},
error: function (xhr, status) {
// handle errors
}
});
</script>
<style>
body{
margin-top: 30px;
}
#messageArea{
display: none;
}
</style>
</head>
<body>
<div class="container">
<div id="userFormArea" class="row">
<div class="col-md-12">
<form id="userForm">
<div class="form-group">
<label>Enter UserName</label>
<input class="form-control" id="username" />
<br />
<input type="submit" class="btn btn-primary" value="Login" />
</div>
</form>
</div>
</div>
<div id="messageArea" class="row">
<div class="col-md-4">
<div class="well">
<h3>Online Users</h3>
<ul class="list-group" id="users"></ul>
</div>
</div>
<div class="col-md-8">
<div class="chat" id="chat"></div>
<form id="messageForm">
<div class="form-group">
<label>Enter Message</label>
<textarea class="form-control" id="message"></textarea>
<br />
<input type="submit" class="btn btn-primary" value="Send Message" />
</div>
</form>
</div>
</div>
</div>
<script>
$(function(){
var socket = io.connect();
var $messageForm = $('#messageForm');
var $message = $('#message');
var $chat = $('#chat');
var $messageArea = $('#messageArea');
var $userFormArea = $('#userFormArea');
var $userForm = $('#userForm');
var $users = $('#users');
var $username = $('#username');
$messageForm.submit(function(e){
e.preventDefault();
socket.emit('send message', $message.val());
$message.val('');
});
socket.on('new message', function(data){
$chat.append('<div class="well"><strong>'+data.user+'</strong>: '+data.msg+'</div>');
});
$userForm.submit(function(e){
e.preventDefault();
socket.emit('new user', $username.val(), function(data){
if(data){
$userFormArea.hide();
$messageArea.show();
}
});
$username.val('');
});
socket.on('get users', function(data){
var html = '';
for(var i = 0;i < data.length;i++){
html += '<li class="list-group-item">'+data[i]+'</li>';
}
$users.html(html);
});
});
</script>
</body>
</html>
For some reason it keeps redirecting to an error page for my hosting site and that's where the error is coming from. And as for the Uncaught SyntaxError: Unexpected token < error from the looks of it, it's from the error page aswell
Any thoughts on how to fix this?
Your problem is that you are trying to make a Cross Origin Request and the server you are calling is not configured to respond to CORS request from the domain you are sending.
Your html is located at http://sampleclickinggame.esy.es
but you are trying to make a server call to http://error.hostinger.eu/?
See how the domains are different? For security reasons the Browser does not allow this. When it sees a CORS request, it sends an OPTIONS request to the server first to see if the server will accept the request from the different domain. If it will, then the request will proceed as normal. In your case it looks like the server is not configured to receive a request from http://sampleclickinggame.esy.es
Your solution is to enable CORS on the server you are making the request to, or you must host everything on the same server/domain.
One last thought:
can I see the javascript that is being used to make this network call? I have seen the browser throw this CORS error a lot when it is actually a problem with the javascript request. The one thing that makes me think you might have javascript error is that the Console on your web page is saying this: "Uncaught SyntaxError: Unexpected token <"
Related
I have a code from a client that runs on a local server. The index page shows background and forms but on the online server it only show background image and nothing else
Here is the index.php script:
<?php include('header.php'); ?>
<body id="login">
<div class="container">
<form id="login_form" class="form-signin" method="post">
<h3 class="form-signin-heading"><i class="icon-lock"></i> Please Login</h3>
<input type="text" class="input-block-level" id="usernmae" name="username" placeholder="Username" required>
<input type="password" class="input-block-level" id="password" name="password" placeholder="Password" required>
<button name="login" class="btn btn-info" type="submit"><i class="icon-signin icon-"></i> Sign in</button>
</form>
<script>
jQuery(document).ready(function(){
jQuery("#login_form").submit(function(e){
e.preventDefault();
var formData = jQuery(this).serialize();
$.ajax({
type: "POST",
url: "login.php",
data: formData,
success: function(html){
if(html=='true')
{
$.jGrowl("Welcome to Thutoboswa Learning Management System", { header: 'Access Granted 😀 #WearAMask😷' });
var delay = 2500;
setTimeout(function(){ window.location = 'dashboard.php' }, delay);
}
else
{
$.jGrowl("Please Check your username and Password", { header: 'Login Failed' });
}
}
});
return false;
});
});
</script>
</div>
<!-- /container -->
<?php include('script.php'); ?>
</body>
</html>
Mozila Firefox console shows these warnings:
This page uses the non standard property “zoom”. Consider using calc() in the relevant property values, or using “transform” along with “transform-origin: 0 0”. gobojangojss.co.bw
Using //# to indicate sourceMappingURL pragmas is deprecated. Use //# insteadjquery-1.9.1.min.js:2:21
Layout was forced before the page was fully loaded. If stylesheets are not yet loaded this may cause a flash of unstyled content. modernizr-2.6.2-respond-1.1.0.min.js:4:3946
downloadable font: bad search range (font-family: "TR Century Gothic" style:normal weight:400 stretch:100 src index:0) source: https://gobojangojss.co.bw/admin/bootstrap/css/TR%20Century%20Gothic.ttf
downloadable font: bad range shift (font-family: "TR Century Gothic" style:normal weight:400 stretch:100 src index:0) source: https://gobojangojss.co.bw/admin/bootstrap/css/TR%20Century%20Gothic.ttf
downloadable font: cmap: bad id_range_offset (font-family: "TR Century Gothic" style:normal weight:400 stretch:100 src index:0) source: https://gobojangojss.co.bw/admin/bootstrap/css/TR%20Century%20Gothic.ttf
Source map error: Error: request failed with status 404
Resource URL: https://gobojangojss.co.bw/admin/vendors/jquery-1.9.1.min.js
Source Map URL: jquery.min.map
Goood day, Ace.
Check please if you uploaded 2 files to server:
header.php
script.php
Another solution is to open Chrome Console. Press F12
And in NAME column you will see the PHP file that work with you Ajax query.
Click on this php file and see what POST parameters come back from server to you.
update
this string tell us that yourcode missing jquery.
Resource URL: https://gobojangojss.co.bw/admin/vendors/jquery-1.9.1.min.js
Can you add this to functions,php file
wp_enqueue_script('jquery');
I have a form in which Ajax is used to send data to a php file.
THE DATA SENDS PROPERLY...EVERYTHING WORKS FINE...
BUT an "Error loading page" message pops up (using jquerymobile)
html file
<div data-role="page" id="cc">
<div data-role="header">
<h1>Home</h1>
</div>
<div data-role="content">
<form id="cname" align="left" action="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="" />
<input type="submit" value="Submit" data-inline="true">
</form>
<div id="result" style="visibility: hidden"></div>
</div>
</div>
<script type="text/javascript">
$("#cname").submit(function (e) {
e.preventDefault();
$.ajax({
url: 'http://www.clubbedin.isadcharity.org/createclub.php',
crossDomain: true, //set as a cross domain requests
type: 'post',
data: $("#cname").serialize(),
success: function (data) {
$("#result").html(data);
},
});
});
</script>
php file
header("access-control-allow-origin: *");
$name = $_POST['name'];
Your form must also have have this attribute:
data-ajax="false"
Without it jQuery Mobile will initialize its own ajax logic for form posting and you don't want that. Read more about it here or read my other answer on how to properly handle forms in jQuery Mobile.
Try adding this in your JavaScript:
jQuery.support.cors = true;
Try adding
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Content-Type, *
to your header
I have the following signup form near the bottom of a new website. As soon as the AJAX response loads, the page skips to the top of the page. As far as I can tell, I have included "return false" correctly. What am I missing? Thank you!
## index.php ##
<script type="text/javascript" src="mailing-list.js"></script>
<div class="signup container">
<form id="signup-form" action="<?=$_SERVER['PHP_SELF']; ?>" method="get">
<fieldset>
<legend><h2 style="align:center;">Enter Your Email Address</h2></legend>
<div class="row">
<div class="offset4 span3">
<input class="email" type="text" name="email" id="email" />
</div>
<div class="span1">
<input type="submit" name="submit" value="Join" class="btn btn-large btn-primary" />
</div>
</div>
<div id="response">
<? require_once('inc/store-address.php'); if($_GET['submit']){ echo storeAddress(); } ?>
</div>
</fieldset>
</form>
</div>
## and mailing-list.js ##
$(document).ready(function() {
$('#signup-form').submit(function() {
// update user interface
$('#response').html('Adding email address');
// Prepare query string and send AJAX request
$.ajax({
url: 'inc/store-address.php',
data: 'ajax=true&email=' + escape($('#email').val()),
success: function(msg) {
$('#response').html(msg);
}
});
return false;
});
});
$(document).ready(function() {
$('#signup-form').submit(function(e) {
e.preventDefault();
// update user interface
$('#response').html('Adding email address');
// Prepare query string and send AJAX request
$.ajax({
url: 'inc/store-address.php',
data: 'ajax=true&email=' + escape($('#email').val()),
success: function(msg) {
$('#response').html(msg);
}
});
return false;
});
});
I doubt it is executing the default form submit behavior. Prevent it byt using the preventDefault method.
$(function(){
$('#signup-form').submit(function(e) {
e.preventDefault();
//your existing code goes here
});
});
You need to prevent the form from submitting the data (even if it is to the same file). Otherwise the page will reload before your ajax call is done. You do this with .preventDefault();
Try
...
$('#signup-form').submit(function(event) {
event.preventDefault();
// update user interface
...
This is a jQuery Mobile question, but it also relates to pure jQuery.
How can I post form data without page transition to the page set into form action attribute. I am building phonegap application and I don't want to directly access server side page.
I have tried few examples but each time form forwards me to the destination php file.
Intro
This example was created using jQuery Mobile 1.2. If you want to see recent example then take a look at this article or this more complex one. You will find 2 working examples explained in great details. If you have more questions ask them in the article comments section.
Form submitting is a constant jQuery Mobile problem.
There are few ways this can be achieved. I will list few of them.
Example 1 :
This is the best possible solution in case you are using phonegap application and you don't want to directly access a server side php. This is an correct solution if you want to create an phonegap iOS app.
index.html
<!DOCTYPE html>
<html>
<head>
<title>jQM Complex Demo</title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<style>
#login-button {
margin-top: 30px;
}
</style>
<script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script src="js/index.js"></script>
</head>
<body>
<div data-role="page" id="login" data-theme="b">
<div data-role="header" data-theme="a">
<h3>Login Page</h3>
</div>
<div data-role="content">
<form id="check-user" class="ui-body ui-body-a ui-corner-all" data-ajax="false">
<fieldset>
<div data-role="fieldcontain">
<label for="username">Enter your username:</label>
<input type="text" value="" name="username" id="username"/>
</div>
<div data-role="fieldcontain">
<label for="password">Enter your password:</label>
<input type="password" value="" name="password" id="password"/>
</div>
<input type="button" data-theme="b" name="submit" id="submit" value="Submit">
</fieldset>
</form>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
</div>
</div>
<div data-role="page" id="second">
<div data-theme="a" data-role="header">
<h3></h3>
</div>
<div data-role="content">
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
<h3>Page footer</h3>
</div>
</div>
</body>
</html>
check.php :
<?php
//$action = $_REQUEST['action']; // We dont need action for this tutorial, but in a complex code you need a way to determine ajax action nature
//$formData = json_decode($_REQUEST['formData']); // Decode JSON object into readable PHP object
//$username = $formData->{'username'}; // Get username from object
//$password = $formData->{'password'}; // Get password from object
// Lets say everything is in order
echo "Username = ";
?>
index.js :
$(document).on('pagebeforeshow', '#login', function(){
$(document).on('click', '#submit', function() { // catch the form's submit event
if($('#username').val().length > 0 && $('#password').val().length > 0){
// Send data to server through ajax call
// action is functionality we want to call and outputJSON is our data
$.ajax({url: 'check.php',
data: {action : 'login', formData : $('#check-user').serialize()}, // Convert a form to a JSON string representation
type: 'post',
async: true,
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function (result) {
resultObject.formSubmitionResult = result;
$.mobile.changePage("#second");
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
} else {
alert('Please fill all nececery fields');
}
return false; // cancel original event to prevent form submitting
});
});
$(document).on('pagebeforeshow', '#second', function(){
$('#second [data-role="content"]').append('This is a result of form submition: ' + resultObject.formSubmitionResult);
});
var resultObject = {
formSubmitionResult : null
}
I have run into same issue where I am calling another .php page from my index.html.
The .php page was saving and retrieving data and drawing a piechart. However I found that when piechart drawing logic was added, the page will not load at all.
The culprit was the line that calls the .php page from my index.html:
<form action="store.php" method="post">
If I change this to:
<form action="store.php" method="post" data-ajax="false">
, it will work fine.
On using PHP and posting data
Use
data-ajax = "false" is the best option on <form> tag.
Problem is that JQuery Mobile uses ajax to submit the form. The simple solution to this is to disable the ajax and submit form as a normal form.
Simple solution: form action="" method="post" data-ajax="false"
I have a html form and I am making the json object as:
var JSobObject=
'{"name":"'+personObject.GetPersonName()+
'","about":"'+personObject.GetAbout()+
'","contact":"'+personObject.GetPersonContact()+'"}';
(Here personObject holds the form data)
trying to post it to Server.php as:
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//var url = "organizePeople.php?people=" + escape(people.toJSONString());
xmlhttp.open("POST","ServerJSON.php?person="+JSobObject,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(JSobObject);
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState==4) {
alert(xmlhttp.responseText);
}
}
I am not getting any response from the server.php In my server i am doing this
$person = $_POST['person'];
$objArray = json_decode($person);
print_r($objArray);
Can anyone help me that what I am doing wrong? I am in the learning stage. Just using JS/AJAX I want to prepare JSON and send it to server and get the response of the object datas.
Thanks in advance
I prefer that, you do this with jQuery. It is JavaScript based library to do things (like this) easier.
$.post({
url: "Server.php",
data: JSobObject,
dataType: "json"
}).done(function(msg) {
alert(msg);
});
You need to download jQuery - of course - to get code to working!
2 thoughts I'm having.
First of all, I'd sugest you move the xmlhttp.onreadystatechange assigment to above the send() call.
Secondly, have you checked with firebug if you're getting any reponse?
Have you tried calling your php page directly, rather than through ajax?
I'm not 100% sure, but probably you'll want something like
$data = json_decode($_POST, true);
$person = $data['person'];
The reason being you're post data is entirely a JSON encoded text string, so you'll need to decode the entire post before you can access the data separately.
You should check the rawpost from php first,
$_POST maybe fill slashes Automatedly
Use this code will help you
<!DOCTYPE html>
<html>
<head>
<title>Servlet Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="js/jquery.serializeJSON.min.js"></script>
</head>
<body>
<div class="jumbotron text-center">
<h1>Submit form Data to Database in JSON</h1>
</div>
<div class="container">
<div class="row">
<div class="col-sm-3"></div>
<div class="col-sm-5">
<h3>Enter the Details : </h3>
<form name="myform" id="myform">
<div class="form-group">
<label for="fullName">Name:</label>
<input type="text" name="fullName" class="form-control">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" name="email" class="form-control">
</div>
<div class="form-group">
<label for="subject">Subject:</label>
<input type="text" name="subject" class="form-control">
</div>
<div class="form-group">
<label for="mark">Mark:</label>
<input type="number" name="mark" class="form-control">
</form>
</div>
<button type="submit" class="btn btn-success " id="submitform">Submit</button>
</div>
<div class="col-sm-3"></div>
</div>
<script>
$(document).ready(function(){
$("#submitform").click(function(e)
{
var MyForm = JSON.stringify($("#myform").serializeJSON());
console.log(MyForm);
$.ajax(
{
url : "<your url>",
type: "POST",
data : MyForm,
});
e.preventDefault(); //STOP default action
});
});
</script>
</body>
</html>