Cannot get AJAX answer to GET - php

I'm trying to achieve the following:
when you click on H1, JQuery GETs info for certain key from the server and sends it back to user, where jquery is showing prompt with this info. PHP in server.php
$link = mysql_connect("mysql.hostinger.com.ua", "_my_login_", "_my_password_") or die("NOOO!");
mysql_select_db("u994953720_db");
$key;
if(isset($_GET['Key'])) {
$key = $_GET['Key'];
$selected = mysql_query("SELECT * FROM `Table` WHERE `Key`='".$key."'", $link);
$selected_row = mysql_fetch_array($selected);
if($selected_row!=null){
$response = array(
"result" => $selected_row['Value']
);
echo json_encode($response);
exit;
}else{
$response = array(
"result" => "Nope."
);
echo json_encode($response);
exit;
}
}
jQuery in the main page:
$('h1').on('click', function () {
$.ajax({
type: 'GET',
url: '/server/server.php',
data: {
'Key': 'Roman'
},
success: function(data) {
alert(data.result);
},
dataType: 'json'
});
});
But I don't have any effect. Could you guys show me how to fix my mistakes?
P.S.Working not working example
P.S.I am only starting learning PHP, so there can be some really stupid mistakes.
UPDATE: I've done everything like you guys said (I don't care about safety yet), but it still doesn't work. In the console there is the following message:
XHR finished loading: GET "http://site0.hol.es/server/server.php?Key=Roman".
When I include error method to ajax:
error: function(requestObject, error, errorThrown) {
alert("request objqect: " + requestObject + " . Error: " + error + " . Error thrown: " + errorThrown);
}
, there is an alert: parsing error, unexpected token <
UPDATE 1: I've understood, that my while page is being writed to json result, like here, but I don't have any other echo-s, how can it happen?
UPDATE: I've figured out, that PHP was sending the whole page what it was placed in, so, I simply removed that) But thank you for your comments about safety, I'll correct it

By looking at your site I can see that you are returning HTML + JSON. Try throwing an exit after your echo:
echo json_encode($response);
exit;
Also - you are not handling a no data state at all. You should be do something like:
if(isset($_GET['Key'])) {
// your valid request code
} else {
echo json_encode(array('result' => false, 'reason' => "You must send a Key"));
}
Furthermore you can debug you php code by hitting the endpoint directly and var_dumping/debugging the code that is run there. For starters, what is the output of $selected_row = mysql_fetch_array($selected); when you go to http://site0.hol.es/server/server.php?Key=Roman
Finally - just little warning, as others have mentioned. You are wide open to SQL injection attacks. Look into using PDO -
What PDO is:
http://php.net/manual/en/book.pdo.php
Why to use it:
http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
How to use it: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers

Related

Ajax success if statement and echo mySQL query result

I have an Ajax script that makes a call to a php file on my server every twenty seconds.
The server then runs a simple mysql query to return the contents of a particular field.
If that field is blank I want the php file to echo the word "pending", which when caught by the success handler will recall the initial function. However if that field is not blank, it will contain a URL to which I want to redirect the user to. That field will update any where between 5 seconds and 5 minutes from the start of the first call and that time cannot be changed.
I think the main issue may be with my php file, in that I dont think it is echoing the data in a way that the success handler recognises. However I have detailed both parts of my code as whilst the success handler seems to be constructed correctly I am not 100% sure.
Very new to this, so apologies if I have not explained myself correctly but if anyone could assist that would be great:
UPDATE - for clarity what I am looking to achieve is as follows:
Ajax call to my php file.
PHP file queries database
If field queried contains no data echo the word "pending" to the ajax success handler (IF) which in turn recalls the original function / ajax call.
If field queried contains data (will be a URL) echo this result to the ajax success handler (ELSE)in a format that will redirect the user via window.location.assign(data).
FURTHER UPDATE
I managed to solve this question with using a combination of the advice from #mamdouhalramadan and #martijn
I also have changed setInterval to setTimeout as the poll function was causing responses to stack up should the server be running slowly and as such cause errors. I also added in cache: false and a further option in the success handler to take into account slightly different behaviour in IE:
AJAX
function poll() {
$.ajax({
url: 'processthree.php?lead_id='+lead_id,
type: "GET",
cache: false,
async: false,
success: function(data3) {
//alert("pending called " + data3)
if(data3.indexOf("pending") >-1 ){
setTimeout(poll, 20000);
}
else if ( (navigator.userAgent.indexOf('MSIE') != -1) ) {
//alert("Submit success - MSIE: " + data3);
parent.window.location.replace(data3);
}
else{
//alert("process three called " + data3)
window.top.location.assign(data3);
}
},
error: function(xhr, error){
//alert("Error");
//alert("Error: " + error + ", XHR status: " + xhr.status);
},
});
}
setTimeout(poll, 20000);
PHP
$query = ("SELECT column FROM table WHERE id = '$lead_id'") or die(mysql_error());
$result = mysql_query($query);
$return = array();
while($row = mysql_fetch_assoc($result))
{
$return = 'pending';
if($row['column'] != '')
{
$return = $row['column'];
}
}
echo $return;
I believe using json might help you out here, not to mention it is safer, like so:
function poll() {
$.ajax({
url: 'processthree.php?lead_id='+lead_id,
type: "GET",
dataType: 'json',//specify data type
success: function(data3) {
if(data3.res.indexOf("pending") >-1 ){
//rest of the code.....
then in your php:
$return = array();
while($row = mysql_fetch_assoc($result))
{
$return['res'] = 'pending';
if($row['column'] != '')
{
$return['res'] = $row['column'];
}
}
echo json_encode($return);
Note: use PDO or MYSQLI instead of mysql as it is deprecated.

ajax / php response adding unwanted br tag

For some reason Im getting a <br/> tag from nowhere in my response from the PHP function...
Here is the ajax:
var paid_value = 'Paid';
$.ajax({
url: 'http://localhost/myshop/owe_money/add_paid.php',
type: 'post',
data: { paid_value:paid_value } ,
beforeSend: function() {
$("#ajax-result").html('Before');
},
success: function(data) {
$("#ajax-result").html(data);
$('input[name="mark_as_paid"]').val(data);
},
error: function(xhr, ajaxOptions, thrownError) {
$("#ajax-result").html('Error');
}
});
And the PHP:
function add_paid() {
include('../db_connect.php');
$paid_value = $_POST['paid_value'];
if (is_numeric($paid_value)) {
$sql = "UPDATE paid SET first_item = $paid_value";
} else {
$sql = "UPDATE paid SET first_item = '".$paid_value."'";
}
if (mysqli_query($connect, $sql)) {
echo $paid_value;
} else {
echo "Unsuccesful".mysqli_error($connect);
}
die;
}
add_paid();
My response should simply be saying "Paid", but instead is saying "<br /> Paid".
on the face of it, it looks sound. You'll probably find that the br is going in somewhere else. Maybe it's even already in the file?
If it is finding it's way into the $_POST variable, you could temporarily hack the issue to use
$paid_value = strip_tags($_POST['paid_value]);
This answer comes with no warranty whatsoever!
In your jQuery code, change the success block to:
success: function(data) {
$("#ajax-result").html(data);
$('input[name="mark_as_paid"]').val(data);
console.log(data)
},
Open your debugger in the browser and view the console. This will write the value of data as sent from your PHP script, and may or may not have the line break in it. I suspect that the line break may be coming from the fist page but this will allow you to see this.
I cannot see any problem with the code so I think it has to do with the form/input where you are displaying the result - you have not included this.
you can use replace tag in success ajax
data.replace("but the br tag","");
but it will still exist in the database

How to trigger the "error" callback in JQuery AJAX call using in PHP

I have PHP code snippet the following:
if (!($result = mysql_query($query, $link))) {
die("Invalid SQL query: " . $query);
}
And I have JQuery code snippet the following:
$.ajax({
url: "....search.php",
data: ...,
async: false, //to trigger error alert
success: function(xml) {
...
},
error: function(xml) {
foundError = true;
},
dataType: "xml"
});
if(foundError) {
setProgress("Could not complete the search because an error was found", ProgressBar.ERROR);
}
Is it possible to have the die call trigger JQuery error function callback? If not, how would I trigger it otherwise?
Try this:
if (!($result = mysql_query($query, $link))) {
header("HTTP/1.1 404 Not Found");
}
Choose the error appropriate for your application
You cannot signal client-side code from the server (at least, not in the way you're expecting).
When using AJAX, best to use proper HTTP response codes and have jQuery act upon those in the error: callback.
You cannot access the ajax error like that as there was no ajax error. What you could do, is check your xml variable in the success section; if it starts with Invalid SQL query you know there was a php error.
To tidy things up, you probably want to return some more information (xml / json) in case of an error instead of just a string.

How can I access my PHP variables when calling ajax in jQuery?

I am attempting to create a simple comment reply to posts on a forum using the AJAX function in jQuery. The code is as follows:
$.ajax({type:"POST", url:"./pages/submit.php", data:"comment="+ textarea +"& thread="+ currentId, cache:false, timeout:10000,
success: function(msg) {
// Request has been successfully submitted
alert("Success " + msg);
},
error: function(msg) {
// An error occurred, do something about it
alert("Failed " + msg);
},
complete: function() {
// We're all done so do any cleaning up - turn off spinner animation etc.
// alert("Complete");
}
});
Inside the submit.php file I have this simple if->then:
if(System::$LoggedIn == true)
{
echo "Yes";
} else {
echo "No";
}
This call works on all other pages I use on the site, but I cannot access any of my variables via the AJAX function. I've tested everything more than once and I can echo back whatever, but anytime I try to access my other PHP variables or functions I just get this error:
Failed [object XMLHttpRequest]
Why am I unable to access my other functions/variables? I must submit the data sent into a database inside submit.php using my already made $mySQL variable, for example. Again these functions/variables can be accessed anywhere else except when I call it using this AJAX function. After hours of Googling I'm just spent. Can anyone shed some light on this for me? Many thanks.
The PHP script that you have only returns a single variable. Write another script that that returns JSON or if you are feeling brave XML. below is a quick example using JSON.
In your javascript
$.ajax({
type: 'GET'
,url: '../pages/my_vars.php'
,dataType: 'json'
,success: function(data){
// or console.log(data) if you have FireBug
alert(data.foo);
}
});
Then in the php script.
// make an array or stdClass
$array = array(
'foo' => 'I am a php variable'
,'bar' => '... So am I'
);
// Encodes the array into JSON
echo json_encode($array);
First thing, you have a space in the Data Parameter String for the URL - will cause problems.
Secondly, your success and error functions are referencing a variable msg. It seems you are expecting that variable to be a string. So, the question then becomes - What is the format of the output your PHP script at submit.php is producing?
A quick read of the jQuery API suggests that, if the format of the response is just text, the content should be accessible using the .responseText property of the response. This is also inline with the response you say you are getting which states "Failed [object XMLHttpRequest]" (as you are trying to turn an XHR into a String when using it in an alert.
Try this:
$.ajax( {
type: "POST" ,
url: "./pages/submit.php" ,
data: "comment="+ textarea +"&thread="+ currentId ,
cache: false ,
timeout: 10000 ,
success: function( msg ) {
// Request has been successfully submitted
alert( "Success " + msg.responseText );
} ,
error: function( msg ) {
// An error occurred, do something about it
alert( "Failed " + msg.responseText );
} ,
complete: function() {
// We're all done so do any cleaning up - turn off spinner animation etc.
// alert( "Complete" );
}
} );

Modify the server side functions using jquery

I am developing one website using cakephp and jquery technologies.
Server-side there are some functions which handles SQL queries.
As per requirement I want to modify server side functions on client side using jQuery AJAX call.
E.g. : Below is the function on server side to modify users information.
function modifyUser(username,userid) {
//update query statements
}
Then jquery AJAX call will be like this:
$.ajax({
url: 'users/modiyUser',
success: function() {
alert("Updation done") or any statements.
}
});
and I want to modify above i.e. server side function depending upon client input criteria.
$.ajax({
function users/modiyUser(username,userid) {
// I will write here any other statements which gives me some other output.
}
});
Above AJAX call syntax may not present, but i think you all understood what I am trying to do I simply wants to modify/override server side functions on client side.
Please let me know is there any way to resolve above mentioned requirement.
Thanks in advance
You cannot call a PHP functions from the client directly. You can only make an HTTP request to a URI.
The URI determines the PHP script run. Input can be taken via $_GET, $_POST, and $_COOKIE (among others, but those are the main ones).
You can either write separate scripts for each function or determine what to do based on the user input.
You could have a server-side function in a separate PHP file to do this, and make an AJAX call call into that function first to perform the modification. But client-side changes to server-side code are just not possible.
I can't actually imagine why you would want to do this, though.
why override a function???
can i suggest this?
in PHP
try {
// functions here....
function modifyUser($username,$userid) {
//update query statements
if(!is_string($username)) throw new Exception("argument to " . __METHOD__ . " must be a string");
if(!is_string($userid)) throw new Exception("argument to " . __METHOD__ . " must be a string");
// do some modification codes....
}
function delete($userid){
// do stuff blah blahh...
}
// $_POST or $_GET etc. here
if(isset($_GET["modify"])){ // I make use of get for simplicity sake...
$username = $_GET['username'];
$userid = $_GET['userid'];
modifyUser($username,$userid);
$ret = array();
$ret["error"] = false;
$ret["msg"] = "$username has been modified";
echo json_encode($ret);
} else if(isset($_GET["delete"])) {
$userid = $_GET['userid'];
delete($userid);
$ret = array();
$ret["error"] = false;
$ret["msg"] = "$username has been deleted";
echo json_encode($ret);
}else {
// the client asked for something we don't support
throw new Exception("not supported operation");
}
}
catch(Exception $e){
// something bad happened
$ret = array();
$ret["error"] = true;
$ret["msg"] = $e->getMessage();
echo json_encode($ret);
}
in jQuery ajax
$.ajax({
url: 'ajax.php',
data : { modify : true, // sample for modify... can also be delete : true,
username : $('#username').val(),
userid : $('#userid').val() },
type: 'GET',
dataType: 'json',
timeout: 1000,
error: function(){
alert('error in connection');
},
success: function(data){
if(data.error)
alert('Something went wrong: ' + data.msg);
else {
alert('Success: ' + data.msg);
}
}
});

Categories