problem : ajax error with google chrome
index.html --- POST ---> page1.php --- link ---> page2.html
“index.html” contains a <form> that posts to “page1.php”
“page1.php” contains a link to “page2.html”
“page1.php” contains an ajax call to “ajax.php”
how to make the problem appear ?
visit “index.html”
post to “page1.php”
follow link to “page2.html”
go back to “page1.php” with the back button
reload “page1.php” with F5
accept to re-submit the datas
ajax error : the ajax call fails with an empty error message
why is... that thing ?
index.html :
<html>
<head>
</head>
<body>
index
<form method="post" action="page1.php">
<input type="submit">
</form>
</body>
</html>
page1.php :
<html>
<head>
<script src="jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
function call_ajax()
{
$.ajax
(
{
type: "POST",
url: "ajax.php",
success: function( response )
{
console.log( response );
},
error: function (xhr, ajaxOptions, thrownError)
{
console.log( '%o', xhr );
console.log( '%o', xhr.responseText );
console.log( '%o', thrownError );
}
}
);
}
$( document ).ready(function() {
call_ajax();
});
</script>
</head>
<body>
page 1
page2
</body>
</html>
page2.html :
<html>
<head>
</head>
<body>
page 2
back
</body>
</html>
ajax.php :
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('error_reporting', E_ALL);
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
$r = array( 'message' => 'one two one two, this is a test' );
echo json_encode( $r );
?>
Might it be, that there is something wrong with the configuration of your server/browser?
I tried to confirm your problem by creating the files with exactly the same code as above in my local installation of lighttpd using PHP via fastcgi and running Chromium version 30.0.1553.0 (209444), but was unable to reproduce your issue.
When looking at the console, the log always shows the correct output whether I access page1.php from index.html or from page2.html using the "back" link and refreshing with F5.
Object {message: "one two one two, this is a test"}
Related
is there any way to call a controller function when someone click on a check box. Like There are 4 check box with each has a category so when a user click on particular category then it will hit an API that process the filter request from the backend. I searched on Google but there is option to change it to
But that I don't want. Do I have to use jquery or else?
As in the comment section you can achive this via JQuery/Javascript. I have added a simple example with JQuery for your reference. What I achive here is first catch all check un check events and then via Ajax I send a request to the server. So that controller function will get called. You can test this via network tab when you check or uncheck a checkbox.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Check the Status of Checkboxes</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
//Add CSRF token to headers
$.ajaxSetup({
headers:
{ 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
$('input[type="checkbox"]').click(function(){
const val = $(this).val()
if($(this).prop("checked") == true){
alert(val+' Checked and sending data to server')
$.ajax({
type: "POST",
url: "file", // Route
data: { checkbox_val:val }
})
.done(function( msg ) {
alert( "Data: " + msg );
});
}else{
alert($(this).val()+' unchecked');
$.ajax({
type: "POST",
url: "file",
data: { checkbox_val:val }
})
.done(function( msg ) {
alert( 'Record removed' );
});
}
});
});
</script>
</head>
<body>
<input value="A" type="checkbox"> A
<input value="B" type="checkbox"> B
<input value="C" type="checkbox"> C
</body>
</html>
Take a look at:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Récupération d'un contenu HTML en Jquery Ajax</title>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<script type="text/javascript">
function recupTexte() {
$.ajax({
url: "data.xml"
})
.done(function( texte ) {
$('body').append( " : " + texte );
});
}
setInterval(recupTexte, 1000);
</script>
</body>
</html>
data.xml
test
When I go to my web browser Safari, I have "test" displayed, but when I edit my data.xml file manually to "changed", Safari continues to display "test" and no "changed". Why ? I don't understand...
So, just to say it, this code only works in safari, and in local. When I put it in a server, nothing is displayed....
This might be an issue due to caching of get request. Try disabling the cache using :
$.ajaxSetup({ cache: false });
or inside your ajax call
$.ajax({
cache: false,
//other options...
});
I have been struggling with this for a couple days and have yet to find any real solutions online yet. I have a form that allows users to enter their email, then after they enter it fades out and is replaced by another form. I am using ajax to submit data from a form to a symfony2 controller, which stories it in the database and sends a response. However, the response ends up just sending me to a blank page with the response data displayed, instead keeping me on the same page and just fading the boxes as needed. I think my issue is with how I have the controller actions set up and the routing files.
EDIT
Well now the issue is that when I click on the submit button nothing happens. Nothing is sent to the controller, so nothing is being stored and no response is being given. What I changed was based on the answer by #PaulPro, appending the
<script> $('#emailForm').submit(submitForm); </script>
to the end of the html page. Thanks in advance for any help and insight!
The controller has 2 relevant actions, the one that renders the TWIG Template with the form, and the one that handles the ajax form submission and returns the response.
public function emailAction()
{
return $this->render('Bundle:email.html.twig');
}
public function submitEmailAction()
{
$em = $this->getDoctrine()-> getEntityManager();
$email = new Email();
$request = $this->getRequest();
$emailVar = $request->request->get('emailSignup');
$email -> setEmail($emailVar);
$em->persist($email);
$em->flush();
$return=array("responseCode"=>200);
$return = json_encode($return);
return new Response($return, 200, array('Content-Type'=>'application/json'));
}
This is the routing for those actions, most likely the culprit of it all:
Bundle_email:
pattern: /email
defaults: { _controller: Bundle:email }
requirements:
_method: GET
Bundle_submitEmail:
pattern: /submitEmail
defaults: { _controller: Bundle:submitEmail }
requirements:
_method: POST
And then here is the email.html.twig template and ajax script:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="{{asset('css/styles.css')}}" rel="stylesheet" type="text/css" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
function submitForm(){
var emailForm = $(this);
var path = "{{path('Bundle_submitEmail')}}"
$.ajax ( {
type: 'POST',
url: $("#emailForm").attr("action"),
emailSignup: $("#emailId").val(),
success: function(data){
if(data.responseCode==200 ){
$('.email-signup-form').fadeOut();
$('.share-form').delay(500).fadeIn();
}
}
});
return false;
}</script>
</head>
<body>
<form id="emailForm" action="{{path('Bundle_submitEmail')}}" method="POST" class="email-signup-form">
<input type="email" placeholder="e-mail address" name="emailSignup" id="emailId" required="true"/>
<input type="submit" value="Go">
</form>
<form class="share-form">
</form>
<script> $('#emailForm').submit(submitForm); </script>
</body>
</html>
You don't ever call submitForm (the function that tells the browser to use AJAX rather than a full page load). Just add a script at the end of your body that looks like:
<script>
$('#emailForm').submit(submitForm);
</script>
i have a very basic jqm/phonegap app
here is my html
<html>
<head>
<title>jQuery Mobile Web App</title>
<link href="jquery-mobile/jquery.mobile-1.0.min.css" rel="stylesheet" type="text/css"/>
<link href="style.css" rel="stylesheet" type="text/css">
<script src="jquery-mobile/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="jquery-mobile/jquery.mobile-1.0.min.js" type="text/javascript"></script>
</head>
<body >
<div data-role="page" id="home" >
<div data-role="header">
<h1>p</h1>
</div>
<div data-role="content" style="text-align:right" id="c1">
</div>
</div>
</div>
</div>
here is my js code which is placed in the body of html code
<script>
function get_news_list(id , link_ , refresh_ ){
jQuery.support.cors = true;
$.ajax({
url : link_ ,
success:function(data){
$('#c1').html(data);
} ,
error : function(data) {
alert(data.toSource);
}
});
}
get_news_list('latest' , 'http://pnup.ir/?feed=json' , refresh_);
</script>
when i run it as a webpage i get
this alert
if firefox
function toSource() {
[native code]
}
in chrome
undefined
which i assume is ok cuz it's a cross domain ajax request and it fails in a web browser (altho in firebug it's status is ok 200 it just doesn't return anything as response )
but when i test it on my android device i get the same undefined . i thought cross domain ajax request isn't problem once i rune it as app in android device ?
am i missing something ? should i use jsonp ? its a wordpress website and with json feed plugin its feeds are available in json but getting jsonp feed would be a nightmare ... at least i dont know how !
i implemented jsonp recently in one of my phonegap + jquerymobile project, i had the same issue but i used asp.net for my services
calling the service like below worked for me all you have to do is add ?fnCallBack=? at the end of the url
$.ajax({
url : link_+'?fnCallBack=?',
contentType : "application/json; charset=utf-8",
dataType : "json",
jsonp : 'json',
cache : false,
success : function(result) {
if (result != 'Error') {
var valX = JSON.stringify(result);
valX = JSON.parse(valX);
} else {
navigator.notification.alert("An error occured, Please try later");
}
}
});
and on the server side when you send json response just add fnCallBack like this
string jsoncallback = context.Request["fnCallBack"];
context.Response.Write(string.Format("{0}({1})", jsoncallback,jsonData));
this way i solved my cross domain issue so hoping you ll get a clue from this
The following code is a very simple ajax call to server that alerts back on success and complete events.
From a reason I cannot understand on my development machine it works fine and alerts on success and complete but on server it never alerts on success. WHY ???
**
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function dummy() {
$.ajax({
url: 'services/chatEngine.asmx/dummy',
async: true,
type: "POST",
complete: function () { alert('Done'); },
success: function (a, b, c) {
alert('Success');
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</ajaxToolkit:ToolkitScriptManager>
<div id="userList">Users:<br /></div>
<input id="Button3" type="button" value="dummy" onclick="dummy()" />
</div>
</form>
</body>
</html>
**
The server side dummy function returns nothing, code follows -
<WebMethod(True)>
Public Function dummy() As String
Return ""
End Function
You need to find out where the failure is.
1) Is the client making the request? Use your browsers developer tool request monitor or something like Charles to look at the request data. make sure the URL is correct.
2) Is the server getting the request? Use server logs or attach a debugger to verify the request is received.