So I decided to start using prototype and here's my first question. I'm trying to send out an ajax request to a php page which updates s single record. When I do this by hand (ie: typing the address + parameters it works fine but when I use this code from javascript:
var pars = 'trackname=' + track + '&tracktime=' + time;
new Ajax.Request('php/setSongTime.php', {
method: 'get',
parameters: pars,
onSuccess: function(transport){
var response = transport.responseText || "no response text";
alert("Success! \n\n" + response);
},
onFailure: function(){ alert('Something went wrong...') }
The onSuccess fires and displays the correct information from php, but the update is not made. What the php returns is the UPDATE string, so I'm checking the parameters and they look fine. Does anyone see a problem? Thanks...
Total javascript:
/*This file handles all the user-based computations*/
//variable declarations to be used throughout the session
var untimedSongArray = [];
function beginProcess(){
new Ajax.Request('php/getUntimed.php', {
method: 'get',
onSuccess: function(transport){
var response = transport.responseText || "no response text";
untimedSongArray = response.split("+");
alert(response);
getFlashMovie("trackTimer").timeThisTrack(untimedSongArray[0]);
//alert("Success! \n\n" + response);
//var html = response;
},
onFailure: function(){ alert('Something went wrong...') }
});
}
function getFlashMovie(movieName) {
var isIE = navigator.appName.indexOf("Microsoft") != -1;
return (isIE) ? window[movieName] : document[movieName]; }
function setSongTime(track, time){
alert("track " + track + " has a time of " + time);
//$.get("php/setSongTime.php", { trackname: track, tracktime: time } );
var pars = 'trackname=' + track + '&tracktime=' + time;
new Ajax.Request('php/setSongTime.php', {
method: 'get',
parameters: pars,
onSuccess: function(transport){
var response = transport.responseText || "no response text";
alert("Success! \n\n" + response);
},
onFailure: function(){ alert('Something went wrong...') }
});
}
Total php code:
<?php
//turn on error reporting
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
//header('Content-Type: text/xml');
/////////////Main script
//pull variables
//need to do some error checking here
$trackname = ($_GET['trackname']);
$tracktime = ($_GET['tracktime']);
//remove leading track information
$trackname = str_replace('../music_directory/moe/moe2009-07-18/', '', $trackname);
$trackname = str_replace('.mp3', '', $trackname);
//echo $trackname;
//connect with database
$con = mysql_connect("localhost","root","");
if(!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("musicneverstopped", $con);
//end connecting to database
//////////////////////////////////////////
//update given song time
$sql = "UPDATE songs SET length = ".$tracktime." WHERE unique_song_id = ".$trackname;
echo $sql;
mysql_query("UPDATE songs SET length = '$tracktime' WHERE unique_song_id = '$trackname'");
//error check
//if(!$attempt){
//die(mysql_error());
//}
//////////////////////////////////////////
//close database connection
mysql_close($con);//close mysql connection
?>
Anyone see any failing errors?
Try echoing the exact same SQL you actually run in mysql_query (store it in $sql then pass that into the query, instead of writing out the query twice).
Then try running the query that gets echoed out in the response directly in the mysql command line on your server and see what happens.
Also, just to echo Max on the importance of escaping your SQL queries, I would add to the input sanitisation that you should use bind variables in your query, rather than just concatenating your user input with the rest of the SQL.
Something like this would ensure your variables are suitably escaped to avoid an SQL injection attack.
$sql = "UPDATE songs SET length = '%s' WHERE unique_song_id = '%s'";
$query = sprintf(
$sql,
mysql_real_escape_string($tracktime),
mysql_real_escape_string($trackname)
);
mysql_query($query);
Found it! Somehow I was getting an extra space before the finalized $trackname. ltrim fixed it right up. Thanks to everyone and thanks to those that mentioned security features. I'll definitely implement those. Dan
Related
I am implementing own custom function for historical extract in CSV format from MySQL database using jQuery-Ajax in WordPress environment. I have an HTML where user selects the start date and end date and clicks on a button and then the process works.
When the JSON response is in the range of 900kb to 1 MB, then extraction works. But when the response size increases beyond this then AJAX callback goes in error and returns nothing.
Below is the JavaScript file:
jQuery(document).ready(function(jQuery) {
jQuery('#extract_btn').click(function(){
var startdate = jQuery( '#from-date' ).val();
var enddate = jQuery( '#to-date' ).val();
var data1 = {
action: 'hist_extract',
fromdate: startdate,
todate: enddate
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
jQuery.ajax({
type:"post",
url:MyAjax1.ajaxurl,
data:data1,
success:function(response) {
if (response == '')
return;
alert('Got this from the server: ' + JSON.parse(response));
JSONToCSVConvertor(response, "Historic Price", true);
},
error:function(xhr, status, error){
alert('Error in response');
var err = JSON.parse(xhr.responseText);
alert(err.Message);
}
});
});
});
function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
alert('Start of Json Convertor')
//If JSONData is not an object then JSON.parse will parse the JSON string in an Object
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var CSV = '';
//Set Report title in first row or line
//CSV += ReportTitle + '\r\n\n';
//This condition will generate the Label/Header
if (ShowLabel) {
var row = "";
//This loop will extract the label from 1st index of on array
for (var index in arrData[0]) {
//Now convert each value to string and comma-seprated
row += index + ',';
}
row = row.slice(0, -1);
//append Label row with line break
CSV += row + '\r\n';
}
//1st loop is to extract each row
for (var i = 0; i < arrData.length; i++) {
var row = "";
//2nd loop will extract each column and convert it in string comma-seprated
for (var index in arrData[i]) {
row += '"' + arrData[i][index] + '",';
}
row.slice(0, row.length - 1);
//add a line break after each row
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
alert(CSV);
//Generate a file name
var fileName = "Edding_";
//this will remove the blank-spaces from the title and replace it with an underscore
fileName += ReportTitle.replace(/ /g, "_");
//this trick will generate a temp "a" tag
var link = document.createElement("a");
link.id="lnkDwnldLnk";
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
var blob = new Blob([CSV]);
if (window.navigator.msSaveOrOpenBlob) // IE hack;
window.navigator.msSaveBlob(blob, fileName+".csv");
else
{
var a = window.document.createElement("a");
a.href = window.URL.createObjectURL(blob, {type: "text/plain"});
a.download = fileName+".csv";
document.body.appendChild(a);
a.click(); // IE: "Access is denied"
document.body.removeChild(a);
}
}
Below is the functions.php having custom hook:
//----------------------------------------------------------------------------------
//Below is the custom Javascript hook for Historic Extract
//----------------------------------------------------------------------------------
function price_history() {
$handle = 'hist_extract';
$list = 'enqueued';
if (wp_script_is( $handle, $list )) {
return;
}
else
{
// registering and enqueueing the Javascript/Jquery
wp_enqueue_script('jquery');
wp_register_script('hist_extract', get_template_directory_uri() . '/js/Historic_Price.js', array( 'jquery' ), NULL, false );
wp_enqueue_script('hist_extract');
wp_localize_script('hist_extract', 'MyAjax1', array(
// URL to wp-admin/admin-ajax.php to process the request
'ajaxurl' => admin_url('admin-ajax.php'),
// generate a nonce with a unique ID "myajax-post-comment-nonce"
// so that you can check it later when an AJAX request is sent
'security' => wp_create_nonce('my-special-string')
));
error_log('Js for Historic Price loaded successfully');
error_log(admin_url('admin-ajax.php'));
}
}
add_action('wp_enqueue_scripts', 'price_history');
//----------------------------------------------------------------------------------
// Custom function that handles the AJAX hook for Historic Extract
//----------------------------------------------------------------------------------
function historic_data_extract() {
error_log('Start of report data function on ajax callback');
// check_ajax_referer( 'my-special-string', 'security' );
$from_date = $_POST['fromdate'];
$to_date = $_POST['todate'];
$convert_from_date= date("Y-m-d", strtotime($from_date));
$convert_to_date = date("Y-m-d", strtotime($to_date));
error_log($from_date );
error_log($to_date);
error_log($convert_from_date);
error_log($convert_to_date);
//******************************************
//Custom Code for fetching data from server database
//********************************************
//header("Content-Type: application/json; charset=UTF-8");
define("dbhost", "localhost");
define("dbuser", "xxxxxxxxx");
define("dbpass", "xxxxxxxxx");
define("db", "xxxxxxxx");
$emparray = array();
$conn = mysqli_connect(dbhost, dbuser, dbpass, db);
// Change character set to utf8
mysqli_set_charset($conn,"utf8");
if ($conn )
{
$query = "SELECT PR_PRICE_HIST_TBL.PR_PRODUCT_ID,PR_PRICE_HIST_TBL.PR_URL_ID,PR_PRICE_HIST_TBL.PR_SHOP_NAME,PR_PRICE_HIST_TBL.PR_LAST_CHECKED,PR_PRICE_HIST_TBL.PR_CUST_PROD_CODE,PR_PRICE_HIST_TBL.PR_PRODUCT_NAME,PR_PRICE_HIST_TBL.PR_LAST_PRICE,PR_PRICE_HIST_TBL.PR_CONV_PRICE,PR_PRICE_HIST_TBL.PR_DOMAIN,PR_PRICE_HIST_TBL.PR_COUNTRY_CODE,PR_PRICE_HIST_TBL.PR_AVAILABLE,PR_PRICE_HIST_TBL.PR_AVAIL_DESCR,PR_PRICE_HIST_TBL.PR_PRICE_TIME,PR_PRICE_HIST_TBL.PR_FAULT_FLAG,PR_PRICE_HIST_TBL.PR_FAULT_TIME,PR_PRICE_HIST_TBL.PR_FAULT_MSG,TABLE_72.MIN_PRICE,TABLE_72.MAX_PRICE,TABLE_72.AVG_PRICE,TABLE_72.DEV_PRICE
FROM PR_PRICE_HIST_TBL
INNER JOIN TABLE_72 ON PR_PRICE_HIST_TBL.PR_URL_ID=TABLE_72.PR_URL_ID AND
PR_PRICE_HIST_TBL.PR_SHOP_NAME=TABLE_72.PR_SHOP_NAME AND
PR_PRICE_HIST_TBL.PR_PRODUCT_NAME=TABLE_72.PR_PRODUCT_NAME
AND PR_PRICE_HIST_TBL.PR_LAST_CHECKED BETWEEN '$convert_from_date' AND '$convert_to_date';";
error_log($query);
$result_select= mysqli_query($conn,$query);
error_log(mysqli_num_rows($result_select));
error_log(mysqli_error($conn));
while($row = mysqli_fetch_assoc($result_select))
{
error_log(json_encode($row));
$emparray[] = $row;
}
//error_log(json_encode($emparray));
echo json_encode($emparray);
die();
}
}
add_action('wp_ajax_hist_extract', 'historic_data_extract');
add_action('wp_ajax_nopriv_hist_extract', 'historic_data_extract');
From the code above, you can see, I have tried to implement many things by going over different forums. But I am stuck here. I am not able to understand where could be the potential problem. FYI..I am hosting this on GoDaddy Server. I tried below things:
Tried to make query execution faster by removing views from join. It seems, query is fetching results in around 15 seconds
Format of the data in JSON and tried async: false, but not working
Tried to modify values in init.php. But of no use.
pload_max_filesize = 64M
post_max_size = 64M
memory_limit = 400M
file_uploads = On
max_execution_time = 300
Tried to implement (error:function) for AJAX response. Where only the first alert('Error in response'); is throwing. But can not see the XHR response text.
Any help is appreciated. Please let me know if I miss something or want more information.
The best way to solve the issue is to have a good night's sleep.
Thanks for your clues.
Issue was: In xhr my ajax request was going in cancelled status.
Solution: I was missing preventdefault() in my function.
Now I can see MBs of JSON response. Thanks again for provided clues.
Currently preventdefault() has solved my issue. If you feel, anything else also needs to be taken care as a best practice in my code. Please do not hesitate to comment.
Thanks.
I have problem to get jsonp from my server by id.
I am sure that my php is good, but i don't know how to parse id from php server to htlm-jquery.
My php page is:
<?php
header('Content-type: application/json');
include 'config.php';
$con = mysql_connect($dbhost, $dbuser, $dbpass) or die ("Could not connect: " . mysql_error());
mysql_select_db($dbname, $con);
$id=$_GET['id'];
$sql = "select * from ios where id=$id";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
////////////////////
?>
And this works great, i got json object by id in php.
You can check for example http://www.dr-trkuljic.com/tekst.php?id=1 (you can try with id 2, 3, and 4) you will get result.
But i don't know how to parse that in jquery in my html page
I am using this in my html page:
$(document).ready(function(){
var output = $('.nesa');
$.ajax({
url: 'http://www.dr-trkuljic.com/tekst.php',
dataType: 'jsonp',
data: 'id',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
//var ispisi = '<li>' + item.naziv + '</li>' ;
var ispisi = item.naziv + item.tekst;
output.append(ispisi);
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
});
So, my question is how to parse (show) by id in my html page?
To be precise how that result from my server http://www.dr-trkuljic.com/tekst.php?id=1 get in my html page?
Thank you.
1 If you are on the same domain
In php change
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
to
echo json_encode($records);
JS success:
success: function(data, status){
var jsonData = JSON.parse(data);
var total = jsonData.length;
for(var i = 0; i < total; ++i){
var ispis = jsonData[i].naziv + " " + jsonData[i]item.tekst;
console.log("My ispis ", ispis);
}
}
2 if you want to use JSONP. (get response from another domain or phonegapp )
When you need a response from another domain you can't use AJAX request, what you can do is load a new script in document for example in tag, You load that script as js script with your response. Inside that js script you put your response in some variable, and also you can call some function that is defined in already loaded js file. for example
echo "var myVar = " . json_encode($records) . '; myCallbackFunc();';
Than load that file as js file to your document
and somewhere in that or where ever js that you want to get response - myVar will contain your response that you can use, and when response load your callback function will be called
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'http://www.dr-trkuljic.com/tekst.php?id=1';
head.appendChild(script);
function myCallbackFunc(){
// Do something with myVar
var total = myVar.length;
for(var i = 0; i < total; ++i){
var ispis = myVar[i].naziv + " " + myVar[i]item.tekst;
console.log("My ispis ", ispis);
}
}
EDIT
Just double check if server response - javascript syntax is ok.
As I felt my previous answer was incorrect, allow me to edit:
After you remove the '(' and ')' from around the json array, you can simply use this quick and easy shorthand format for your jQuery http call: (all parsing is already performed because of the Content-Type header). You are then free to access the appropriate properties of the object.
For further examples on how to use jQuery's $.get() and $.post(), etc... visit this link:
http://api.jquery.com/category/ajax/shorthand-methods/
$(document).ready(function(){
var output = $('.nesa');
var idNumber = 1;
$.get('http://www.dr-trkuljic.com/tekst.php', {id: idNumber}, function(data, status){
$.each(data, function(i,item){
//var ispisi = '<li>' + item.naziv + '</li>' ;
var ispisi = item.naziv + item.tekst;
output.append(ispisi);
});
}).fail(function(){
output.text('There was an error loading the data.');
});
});
To overcome cross-domain errors, you can send this header in your php file with the appropriate url of where you're working from:
header("Access-Control-Allow-Origin: http://your-domain-or-localhost");
I have a page that dynamically creates (using jQuery) Input boxes for the user. The user can then enter values in each input box he created. On clicking the save button a call is made to a javascript function that iterates through all the input boxes user created and sends these values using an XMLHttpRequest to the process.php file which inserts these values into the DB.
This code works fine if i send only one Request at a time. But if i loop it and send the value from each box on each iteration (means, send multiple requests using loop), only the last Request finds success. All the other calls except the last call gets aborted (found it using firebug).
Any idea why is this happening?
My code:
<script>
function saveTimeSlots(){
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
}
catch(e){
alert('Issue with browser.')
}
ajaxRequest.onreadystatechange = function(){
if( ajaxRequest.readyState==4 ){
alert(ajaxRequest.responseText); //This returns empty except for last call
}
}
var timeSlots = document.getElementById('formSlots').childNodes;
var date = $.datepicker.formatDate('dd-mm-yy', new Date($('#datepicker').datepicker("getDate")));
for(j=0; j<timeSlots.length; ++j){
var time = timeSlots[j].getElementsByTagName("input")[0].value;
var status = 1;
var queryString = "?date=" + date + "&time=" + time + "&status=" + status;
ajaxRequest.open("GET", "process.php" + queryString, true);
ajaxRequest.send(null);
}
}
</script>
<input type="button" value="Save time slots" class="custom-button" onclick="saveTimeSlots()"/>
Following is the code of process.php
<?php
mysql_connect( $dbhost,$user,$pwd );
mysql_select_db( $dbase ) or die( mysql_error() );
$date = mysql_real_escape_string( $_GET['date'] );
$time = mysql_real_escape_string( $_GET['time'] );
$status = mysql_real_escape_string( $_GET['status'] );
$query = "INSERT INTO time_slots (`date`,`time`,`status`) VALUES ('" . $date . "','" . $time . "'," . $status . ")";
echo $query;
if( mysql_query( $query ) ){
echo "Success";
}else{
echo mysql_error();
}
mysql_close();
}
?>
This is what Firebug shows:
GET http://localhost/process.php?date=24-06-2012&time=1&status=1 Aborted
GET http://localhost/process.php?date=24-06-2012&time=2&status=1 Aborted
GET http://localhost/process.php?date=24-06-2012&time=3&status=1 200 OK 31ms
You cannot use an instance of XMLHttpRequest for more than one request. Create a new instance for each request.
Since you're already using jQuery, I recommend to use $.ajax (or $.get) to fetch the request.
function saveTimeSlots(){
$('#formSlots').children().each(function() {
var time = $(this).find('input:first').val();
var status = 1;
var queryString = "?date=" + date + "&time=" + time + "&status=" + status;
$.get("process.php" + querystring, function(responseText) {
alert(responseText);
});
});
}
You are using the same XMLHttpRequest object for all the requests, so as soon as you start the request, the next one starts another request on it which aborts the previous one.
Make a new XMLHttpRequest object for each request or just use jQuery's ajax. It's not good to have jQuery and not use it.
I cannot get my $_POST to work for some reason..Here is the code:
*Javascript that gets called from href onClick event:*
function feedVote(postId, vote) {
if(vote == "1") {
document.getElementById('voteUpSpan' + postId).innerHTML = "Thank you for voting!";
document.getElementById('voteDownSpan' + postId).innerHTML = "";
var i = new Image();
var d = new Date();
i.src = "voteUp.php?time=" + d.getTime() + "&postId=" + postId;
}
}
So it spoofs a image and runs my voteUp.php page passing the parameters without changing the current page.
<?php
$id = $_POST['postId'];
$con = mysql_connect("localhost", "username", "password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
$update = mysql_query("UPDATE posts SET upvote = upvote + 1 WHERE id = '$id'");
mysql_close($con);
echo "$id";
?>
The echo "$id"; returns nothing so its obviously not even putting a variable in $id which is why my sql statement is not being run but why...
When I run the code in Google Crome, I use the network tracking feature under Inspect source code and this is the url it fires off when it runs my spoof image.
test.com/voteUp.php?time=1327644851907&postId=35
**I editted some of the information out like my database name and username/password and website url.
Those parameters are known as GET params, not POST.
Use the $_GET super global (use it in the same way as $_POST) to access them.
If you want post, do some jquery ajax post, like this:
Instead of:
var i = new Image();
var d = new Date();
i.src = "voteUp.php?time=" + d.getTime() + "&postId=" + postId;
change it with this:
$.ajax({
url: "voteUp.php",
cache: false,
type: 'POST',
data: {time: d.getTime(), postId: postId},
success: function(data){}
});
Note: you need jquery on that webpage!
Variables that appear in the query string of the URL (i.e. after the ? character) are accessed using the $_GET array rather than $_POST.
So I've been banging my head against my desk for a few hours on this one and i'm not getting anywhere so help would really be appreciated.
The code below has two jquery event handlers which fire off an ajax request. The first one uses GET and the data it gets back from the server is JSON encoded - it works fine. The second one ( "button#addTx" ) returns causes Firebug to produce this error:
uncaught exception: [Exception...
"prompt aborted by user" nsresult:
"0x80040111 (NS_ERROR_NOT_AVAILABLE)"
location: "JS frame ::
resource://gre/components/nsPrompter.js
:: openTabPrompt :: line 468" data:
no]
Line 0
which is no help to at all. The server side script is printing raw html to the screen and the aim is that a jquery html replace will be used to update to the page which initiates the request. The data is POSTed correctly as the database updates but beyond that I have no clue. I have rewritten it to try a GET and still produce the same error :-(
Help would be amazing - thank you, Simon
$(document).ready(function(){
$("button.delete").click(function(){
var txid = this.id;
var amountID = "#amount" + txid;
var amount = $(amountID).html();
// <![CDATA[
var url = "delete.php?txid=" + txid + "&am=" + amount;
$.ajax({
type: "GET",
url: url,
success: function(msg){
txid = "ul#" + txid;
$(txid).hide();
var values = msg;
var e = "#" + values.category + "AmountLeft";
var a = values.amount;
$(e).html(a);
}
});
});
$("button#addTx").click(function(){
// <![CDATA[
var url = "addTran.php";
//var dataV = var data = "category=" + document.getElementById("category").value + "&what=" + document.getElementById("what").value + "&amount=" + document.getElementById("amount").value + "&date=" + document.getElementById("date").value;
$.ajax({
type: "POST",
url: "addTran.php",
//async: false,
data: "category=Groceries&what=Food&amount=2.33&date=2/3/2011",
success: function(msg){
$("transList").replaceWith(msg);
}
});
});
});
and here is the server side script
<?php
session_start();
include('functions.php');
//if the user has not logged in
if(!isLoggedIn())
{
header('Location: index.php');
die();
}
$category = $_POST['category'];
$what = $_POST['what'];
$amount = $_POST['amount'];
$date = $_POST['date'];
$category = mysql_real_escape_string($category);
$what = mysql_real_escape_string($what);
$amount = mysql_real_escape_string($amount);
$date = mysql_real_escape_string($date);
$date = convertDate($date);
//add trans to db
include('dbcon.php');
$query = "INSERT INTO transactions ( category, what, amount, date) VALUES ( '$category','$what','$amount','$date');";
mysql_query($query);
//grab the remaining amount from that budget
$query = "SELECT amount_left FROM cards WHERE category = '$category';";
$result = mysql_query($query);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$oldAmountLeft = $row["amount_left"];
//update the amount left
$amountLeft = $oldAmountLeft - $amount;
mysql_free_result($result);
//add new value to db
$query = "UPDATE cards SET amount_left = '$amountLeft' WHERE category = '$category';";
mysql_query($query);
//generate the list of remaining transactions, print to screen to send back to main page
$query = "SELECT txid, what, amount, date FROM transactions WHERE category = ('$category');";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$d = convertDateReverse($row["date"]);
$what = $row["what"];
$amount = $row["amount"];
$txid = $row["txid"];
?>
<li><ul class="trans" id="<? echo $txid; ?>"><li class="date"><? echo $d; ?></li><li class="what"><? echo $what; ?></li><li class="amount" id="amount<? echo $txid; ?>"><? echo $amount; ?></li><button class="delete" id="<? echo $txid; ?>">Delete</button><li></li></ul></li>
<?
}
mysql_free_result($result);
mysql_close();
header("Content-type: application/x-www-form-urlencoded"); //do I need this? I have a " header("Content-type: application/json"); " in the working one
?>
PROBLEM SOLVED: so in the html markup the form that holds the fields of data should have an
onsubmit="return false;"
in it!
Thanks for all the help guys, I have implemented all your suggestions and my code is now soooo much smaller and easier to manage!
Cheers
Simon
Thx for posting the solution. Similarly banged my head for a while trying to solve a similar problem with NS_ERROR_NOT_AVAILABLE without luck. Useful for for people using Django <--> Javascript to do XMLHttpRequests as well. On the Django side, there is an
error: [Errno 32] Broken pipe
...that corresponds with the NS_ERROR that appears in the firebug console for the JS failure.(googleBait) It's hard to know where to start tracing the problem - server side or client side.
Thx again.