ajax satuts cancelled after some attempts - php

im making and update in mysql table when button click, the problem is ajax jquery not working sometimes. It works fine and somehow after x attempts it stop working and stars cancelling my pettitions
my jquery code:
$.ajax({
type:'GET',
url: 'php/updateCosto.php',
data:{
obrero: $obrero,
fechai: $fechaa,
fechaf: $fechab,
costo: $costoS,
},
success: function(result){
if (result == 1) {
alert('Registro Actualizado');
location.reload(true);
}else {
console.log("no actualizado entrada");
alert('Registro No Actualizado');
location.reload(true);
}
}
}); // fin del ajax
the php one:
<?php
include('../db/conn.php');
$maestro = mysql_real_escape_string($_GET['obrero']);
$costosemanal = mysql_real_escape_string($_GET['costo']);
$fechai = mysql_real_escape_string($_GET['fechai']);
$fechaf = mysql_real_escape_string($_GET['fechaf']);
$update = "UPDATE tbl_costos
SET costo_semanal = '$costosemanal'
WHERE fechai = '$fechai'
AND fechaf ='$fechaf'
AND obrero = '$maestro'";
$result = mysql_query($update);
$rows = mysql_affected_rows();
echo ($rows);
mysql_free_result($result);
?>
the problem is after x number of attempts the success part of ajax object is not being used and im getting the STATUS (canceled) from network.
I dont know if it is an issue of CORS AJAX pettition or something!!

Related

PHP AJAX Notifications if MySQL query returns no rows

Situation
I've got a working script that sends an ajax request to get_code.php. This script is run from the main page - index.php. The get_code.php script queries my MySQL DB for a row and then sends back the data to index.php.
Current code
jQuery in index.php
<script type="text/javascript">
$("#Code").click(function(){
var cde = $("#codeinput").val();
$.ajax({
method:'POST',
url:'get_code.php',
data: {va_code:cde},
dataType: 'json',
success: function(output_string){
$('#rtable').append(output_string);
$("#codeinput").val('');
var prc = $(".price:last");
prc.focus();
}
});
});
</script>
PHP script get_code.php
<?php
include('dbc.php');
$code = $_POST['va_code'];
$cq = mysql_query("SELECT * FROM variants where va_code='$code'")or die(mysql_error());
if(!$cq){
mysql_close();
echo json_encode('There was an error running the query: ' . mysql_error());
}elseif(!mysql_num_rows($cq)){
mysql_close();
echo json_encode('No results returned');
}else{
$output_string = '';
$output_string .= '<tr>';
while($row = mysql_fetch_assoc($cq))
{
$output_string .= '<td>'.$row['cost'].'</td>';
//etc. etc. lots more output here
}
$output_string .= '</tr>';
}
mysql_close();
echo json_encode($output_string);
?>
Problem
However, if no results are found for the query, nothing is returned on the page to notify the user. Ideally I'd like to open a modal, or display a div in which I can use the data the user input. I just can't work out for the life of me how to check if $cq returns no results, and if so then to display something on index.php like a notification saying 'Your code was not found'.
Appreciative of any help
You could return a result flag. This is a good logic and easy to understand.
If no row was found :
die(json_encode(['result' => false, 'error' => 'No code was found']));
If some code found :
die(json_encode(['result' => true, 'output' => $output_string]));
And in js :
...
success: function(data){
if (!data.result) {
alert(data.error);
} else {
$('#rtable').append(data.output);
$("#cmtcodeinput").val('');
var prc = $(".price:last");
prc.focus();
}
}
...
Hope it helps.

PHP Script doesnt return variables to AJAX

The code is for simple login validation.
The PHP script doesnt seem to run when returning values to JavaScript but runs fine when there are not variables to return.
So is there anything wrong or do I need to add anything else to return the values from PHP.
<?php
header('Content-type: application/json; charset=utf-8');
include("config.php");
$formd=array();
//Fetching Values from URL
$username2=$_POST['username1'];
$password2=$_POST['password1'];
$query = mysqli_query($db,"SELECT username FROM login WHERE username = '$username2'");
$result=mysqli_fetch_assoc($query);
$sql=mysqli_query($db,"SELECT password FROM login WHERE username = '$username2'");
$resul=mysqli_fetch_assoc($sql);
$row = mysqli_fetch_array($query,MYSQLI_ASSOC);
$count = mysqli_num_rows($query);
$pass=$resul['password'];
if((password_verify($password2,$pass))and($count==1)) {
echo "ds";
} else {
echo "no";
$formd['no']="Invalid password or username"
}
mysqli_close($db); // Connection Closed
echo json_encode($formd);
exit();
?>
JavaScript
<script>
$(document).ready(function(){
$("#submit").click(function(){
var username = $("#username").val();
var password = $("#password").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'username1='+ username + '&password1='+ password;
if(username==''||password=='') {
alert("Please Fill All Fields");
} else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
dataType: "json",
data: dataString,
success: function(data){
alert(data.no);
}
});
}
return false;
});
});
</script>
your Php code has 2 echo statements
if((password_verify($password2,$pass))and($count==1))
{
echo "ds"; // first
}
else
{
echo "no"; // first
$formd['no']="Invalid password or username"
}
mysqli_close($db); // Connection Closed
echo json_encode($formd); // second
This way, your php script returns malformed JSON data and hence $.ajax() cannot handle it.
Also, as others pointed out, please use the developer console to verify your script returns the expected data.
The if else part of your php script has an echo statement and then outside the if else you echo the array $formd. This malforms the JSON response. Also, you should use exit(1) as there is no exception being raised in your code.
Here the snippet you should use to get the script working.
if((password_verify($password2,$pass))and($count==1))
{
echo "ds";
}
else
{
// echo "no"; this is not required
$formd['no']="Invalid password or username"
}
mysqli_close($db); // Connection Closed
echo json_encode($formd);
exit(1);

Login Intel XDK with AJAX and PHP, MySql not works

I have this code
$("#btn_log").click(function(){
var frm=$("#frm_usuario").serialize();
$.ajax({
type:"GET",
url:"http://www.MYWEB.com/cstapp/validarUsuario.php",
data:frm,
dataType:'json',
success:function(response){
if(response.estado==1){
window.location.href = response.url;
} else {
alert("ERROR");
}
}
});
});
And the PHP for get it
$usuario= strtolower(htmlentities($_REQUEST["txt_usuario"], ENT_QUOTES));
$clave=htmlspecialchars(trim($_REQUEST['txt_clave']));
$sql="SELECT * FROM table WHERE usuari='$usuario' AND passw='$clave'";
$result = mysql_query($sql,$connection) or die('La consulta falló'.mysql_error());
$tmp_usu="";
$tmp_clave="";
$arr_rpta=array();
while($obj = mysql_fetch_object($result)) {
$tmp_usu=$obj->nomusuari;
$tmp_clave=$obj->passw;
$tmp_id=$obj->id;
}
if(($tmp_usu==$usuario)&&($tmp_clave==$clave)){
$arr_rpta=array("estado"=>1,"url"=>"segunda.html","id" => $tmp_id);
}else{
$arr_rpta=array("estado"=>"0","url"=>"fallo en ellogin");
}
echo json_encode($arr_rpta);
Ok, this works on my computer. Not works on XDK compilation apk and not works on a XDK simulator.
Has anyone any suggestions? Thank you very much

AJAX POST handler causing "uncaught exception"

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.

prototype ajax not properly executing query

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

Categories