I implement chrome extension and i used jquery $.ajax to get data from the server side by json, but the response returned with additional javascript code and this made the error always fired instead of the success although the response returned the json i sent from the server side.
the ajax call:
$.ajax({
url:'http://www.domain.com/ajax/getTags',
data:{'cookie':cookie_value},
type:'get',
dataType:'json',
beforeSend:function(){
},
success:function(data){
},
error:function(xhr, status, error){
alert(xhr.responseText);
}
});
and the response is :
{"status":"error","msg":"<span class='error_msg alert'>Please complete the missing fields.<\/span>"}
<script type="text/javascript">
var uid = '3887';
var wid = '4102';
</script>
<script type="text/javascript" src="http://cdn.popcash.net/pop.js"></script>
the first line is the actual data sent by the server and all the next lines is additional data i don't know from where it came.
I used PHP in the server side and this is the script that return the json data
$json['status'] = 'error';
$json['msg'] = "<span class='error_msg alert'>Please complete the missing fields.</span>";
echo json_encode($json);
What's wrong? and how can i solve it ?
The server side page you are calling is returning Content-Type:text/html. You can start by setting this to return application/json in the PHP script.
<?PHP
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);
The JS scripts in the body looks suspect (especially given that you don't recognise this script), have you observed this script on all page calls. It looks like some kind of ad content delivery. Does the server you are hosting on belong to you? If so have you swept if for adware/malware?
Related
i am sending ajax request from html page using jquery to send the bulk emails and fetch the data from the server.
here is the code to send request for bulk mail
var sendReq = $.ajax({
type: 'post',
data: "leftID="+JSON.stringify(leftID)+"&rightID="+JSON.stringify(rightID)+"&mode="+mode,
dataType: 'json',
url:"bulk.php"
});
sendReq.done(function( data ) {
$("#bms-ack").html(data.status);
$("#bms-ack").fadeIn('slow');
$("#bms-ack").fadeOut(6000);
console.log(data);
console.log("success");
});
sendReq.fail(function(jqXHR, data){
$("#bms-ack").html(data.status);
$("#bms-ack").fadeIn('slow');
$("#bms-ack").fadeOut(6000);
console.log("fail");
});
now the issue is when i send a request to php page it will send mails and respond with success message.
as the php is returning the response back to the client so will this ajax request going to get blocked ? because when i send another request from jqtable to fetch new data it takes time until the previous request of ajax to send bulk mail hans't finished. and eventually my jqtable keeps loading.
how do i get rid of blocking request , should i remove returning success message from php and if i do so then how the user will know that the request has been submitted ?
If I understand you correctly your issue is that you can't fire another javascript call while the first one is running? That's because Javascript is single-threaded in most browser implementations.
Some light reading:Is JavaScript guaranteed to be single-threaded?
As far as I know, if you send an AJAX petition, is exactly the same as requiring a new page in a non-asynchronous way: As long as the page is not sent to the browser, you keep waiting for the result, and any other request is just a refresh.
So, if you want to achieve a "non-blocking" AJAX way, send the AJAX petition to "differents" URLs. I mean:
url:"bulk.php" => Change to url: "bulk.php?v=3"
the query string is just a foo, and it's only to change the URL you're calling.
When you'll make your AJAX petitions, just add a query string for every petition you're doing (with a ?v=X is more than enough, where X could be even one of the data you're retrieving, the id of the row, whatever...), and it'll work like a charm, as the browser think is a different petition and don't prevent you (block you) to retrieve the values the PHP file is generating (although you know the values are different because you're sending different data, :D)
Update
Uhm... It should allow you keep working. Just for checking, could you try the next piece of code and tell me what happens?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
for(var $i=0; $i<5; $i++) {
$.ajax({
type: 'post',
url:"ajax.php?v="+$i,
success: function(data) {
console.log(data)
}
});
console.log('Browser: ' + $i);
}
});
</script>
</head>
<body>
AJAX TEST
</body>
</html>
AJAX File: (ajax.php)
<?php
sleep(5);
echo 'WAAAAAAAA';
To me, it sends 5 AJAX calls to the server at the same time (not blocking behaviour) almost immediately. I think that this is exactly what you want to achieve, could you test your browser and tell me if you're receiving the same? And by the way, could you post an image of the browser behaviour with the AJAX posts?
I have found many threads regarding this issue, but unfortunately I couldn't get it running. Problem is I don't know much about JQuery.
I am trying to make an Ajax call using JQuery in order to fetch multiple records from a mysql database. I have the following function :
function updateWebpage ()
{
$.ajax({
url: './sale/api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(rows) //on recieve of reply
{
for (var i in rows)
{
var row = rows[i];
var username = row[0];
var stateId = row[1];
$('#output').append("<b>id: </b>"+username+"<b> stateId: </b>"+stateId)
.append("<hr />");
}
}
});
};
My api.php is executing a mysql query with something like this:
$array = retrieveUsersInfo('%'); //fetch result
echo json_encode($array);
My main issue, is how to debug an issue like this? Since ajax is calling asynchronously another file, I cannot view any errors. From my firefox debugger, I can see that the $.ajax function is entered, but success is not.
Thanks in advance.
a couple things to try.
hit the api url directly in a browser (not through ajax) and make sure it returns the valid response.
add an error: function(err){} to your jquery ajax call. this method will get called if there is something other than a 200 response back from the server.
I use Chrome's developer tools more than firefox/firebug. It has a Network tab in it that shows me all the communication between the client and the server. You should see a call out to your api in that tab.
just off hand, i think you need to make sure the mime-type is set to text/json in your php file.
In this script, using php's return will not work, whereas echo will. Thing is, if I use echo, and someone where to access the page directly, they would be able to see the output without the formatting.
<script type="text/javascript">
$(function() {
$('.callAppend').click(function() {
$.ajax({
type: 'GET',
url: 'recent.php',
dataType:'HTML',
cache:false,
success: function(data){
console.log(data);
//}
},
});
return false;
});
});
</script>
This the php script
<?php
$feedback = 'Hello this is the php page';
return $feedback; //Use echo, and all works fine.
?>
return is used for returning a value from a function to another piece of PHP code.
jQuery is not part of the execution of the PHP code on the server, so it has no idea what is really going on server side. jQuery is waiting for the rendered server response, which is what echo provides.
This SO answer provides a solution to only allow an AJAX script to be called by that type of request:
Prevent Direct Access To File Called By ajax Function
Even though it is checking for 'XMLHttpRequest', someone could make this type of request from something else other than you weboage.
When you use AJAX to load a URL, you're loading the raw output of that URL. Echo produces output but return doesn't. You'll need to do some reason on the subject of OOP to understand what the purpose of return is.
Echo is the correct way to send output.
I'm trying to send an AJAX request to a page to interpret some data, and if it complies with what i'm looking for, send another AJAX request back. Right now I can see the first request is being made, but I'm not getting one back
//message.php
<head>
<script>
function org_name(str){
alert(str); //this alert appears, so I know the data is being received by this function
$.get("common_functions.php", { group_name: str} );
}
</script>
</head>
Then, on common_functions.php I have a similar request back, however, I'm not sure exactly what the issue is. The alert box doesn't even appear so I'm confused as to why the console would say the request was sent
//common_functions.php
if(isset($_GET['group_name'])){
?>
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
alert('common_functions'); //this does not appear
$.get("message.php", { name: "test"} );
</script>
<?
}
When I open up the javascript console in chrome I see the request sent form message to common_functions, but apparently the request on common_functions isn't sending one back
//text from javascript console
Request URL:http://localhost/message/common_functions.php?group_name=test
Request Method:GET
Status Code:200 OK
Does anyone see something obvious that I'm doing wrong or missing? If it makes a difference, common_functions is included in message.php because I do use some other functions from that page for my php.
You have to do something with your data. Right now, you're making an AJAX call, and doing nothing with your data.
So something like the following would work:
$.ajax({
url: "common_functions.php",
data: { group_name: str },
type: "GET",
success: function (data) {
$(data).appendTo("head");
}
});
Use $.ajax if you want control over execution states:
$.ajax({
type: "POST",
url: "common_functions.php",
data: { name: "test"},
success: function(r)
{
// user r as output
},
error: function(xhr, ajaxOptions, thrownError)
{
// error report
alert(xhr.responseText);
}
});
In this case you can see if execution was successful or if error occurred.
Also you can use firebug add-on for firefox or chrome to detect if response was sent. There is also an excellent tool called Fidler, which can give you much better overview over request/response states.
Here is an excellent tutorial for ajax debugging.
$.get will strip out <script> tags. You can use another jQuery AJAX method load() that won't, or use $.getScript. If you need content and script you can do both by making an ajax request for the content, and in the success callback of that ajax, call for the script with $.getScript
load() replaces all the content in the specified selector
$('#myDiv').load('common_functions.php', { name: "test"})
Will take all the content of the php output and replace all the contents of #myDiv but will also run the scripts
you may use a library that does that for you automatically, using http://phery-php-ajax.net
in your case, it would be
function messages($data){
$r = new PheryResponse;
// return your messages
return $r->json($messages);
}
function common($data){
$r = new PheryResponse;
switch ($data['group_name']){
case 'messages':
$r
->include_script(array(
'jquery' => 'http://code.jquery.com/jquery-1.8.2.js'
))
->phery_remote('messages'); // load your messages
break;
}
return $r;
}
Phery::instance()->set(array(
'common' => 'common',
'messages' => 'messages'
))->process();
on your page load
$(function(){
phery.remote('common', {'group_name': 'messages'});
});
you don't have to do anything else. btw, if you are including jQuery AFTER you are using $.get(), it won't work, obviously
The client website needs to do a cross-domain JQuery Ajax call to a php file on my server, the php file will query the database for a bunch of stored javascripts which then need to be sent back to the client and be executed on the client's website. This is what i have so far, haven't done the grabbing javascript from database yet and it works. Is this the best way to do this (assuming i can grab the javascripts directly from the database without adding the escape sequence when echo'ing back to the client)? Thanks.
This is what i have so far:
client side:
$.ajax({ url: "http://localhost:8888/test.php",
dataType: "script",
});
server side (test.php):
<?php
echo "alert(\"WORKS!\");";
?>
Review the ajax documentation and handle the success callback option on the ajax method:
$.ajax({
url: "http://localhost:8888/test.php",
dataType: "html",
success : function(data) { alert(data); }
});
As noted by Ricardo, your PHP script should echo HTML or some other content appropriate for your scenario.
See http://api.jquery.com/jQuery.get/
And http://api.jquery.com/jQuery.getJSON/