PHP script not getting called from ajax function - javascript

this is a noob question.
my javascript function(part of knockout.js model that I have defined):
self.loadData = function(){
alert("loadData got called");
$.ajax({
url: 'database_connection.php',
dataType: 'json',
success: function(data){ //json string of records returned from server
alert('success from server call');
},
error: function(){
alert('error from server call');
}
});
};
Contents of database_connection.php:
<?php
echo "this is called";
$db = new MySqli('localhost', 'username', 'password', 'database');
$activities = $db->query("SELECT * FROM MainActivity");
$activities_r = array();
while($row = $activities->fetch_array()){
$val = $row['mActivityID'];
$act = $row['Name'];
$activities_r[] = array('val'=>$val, 'act' => $act);
}
echo json_encode($activities_r);
?>
The php is correct, coz if I directly access this file through browser, it correctly displays the result from database table.
However, when executed through the loadData function, I get two alerts:
1. "loadData is called"
2. "error from server call"
the first line of database_connection.php is not being executed since I cant see the result of echo, so that means the script is not getting called.
Am I using the ajax function wrongly?

Your AJAX request contains:
dataType: "json"
This means that if server returns invalid JSON with a 200 OK status then jQuery fires the error function
Use the following code to ensure the reponse is JSON format.. (PHP vsersion)
header('Content-Type: application/json');
Note : empty response is also considered invalid JSON; you could return {} or null which validate as JSON

you need to add headers in php file, because your data type is json in ajax call.
header('Content-Type: application/json');
echo json_encode($activities_r);

You need to set the type of your request and may be remove dataType. Also in the success callback it was one extra bracket. Check it :
self.loadData = function(){
alert("loadData got called");
$.ajax({
url: 'database_connection.php',
type : 'GET',
// dataType: 'json',
sucess: function(data){ //json string of records returned from server
alert('success from server call');
},
error: function(){
alert('error from server call');
}
});
};

Related

Passing Javascript Variable to PHP File

I was wondering if you could help. I am attempting to pass a variable to a PHP file, then run a SQL query, using that variable, then pass back the result as a variable to the javascript. Currently, I have successfully received the PHP back to the javascript using Ajax, but not able to sending the ServiceName to the PHP File. It is essential that the files stay separate. Also just to clarify I have replaced certain sections for privacy, however, they are correct and working in the code. I have also used a $_GET method already, however, I could only get the javascript to access a new window and not return the PHP variable.
My current code is as follows:
// If the user changes the ServiceID field.
if (sender.getFieldName() == 'ServiceID')
// Declare the value of the new Service name and save it in the variable A.
a = sender.getValue();
{
// if it equals a new variable.
if (sender.getValue() == a) {
// Place it within the URL, in order for it to be processed in the php code.
window.location.href = "http://IP/development/Query01.php?service=" + a;
// Attempted code
// echo jason_encode(a);
// $.ajax({var service = a;
// $.post('http://IP/development/Query01.php', {variable: service});
// }
//use AJAX to retrieve the results, this does work if the service name is hard coded into the PHP.
$.ajax({
url: "http://IP/development/Query01.php",
dataType: "json", //the return type data is jsonn
success: function(data) { // <--- (data) is in json format
editors['Contact2'].setValue(data);
//alert(data);
//parse the json data
}
});
}
}
}
<?php
$serverName = "SeverIP"; //serverName\instanceName, portNumber (default is 1433)
$connectionInfo = array( "Database"=>"DatabaseName", "UID"=>"Username", "PWD"=>"Password
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$service = $_GET['service'];
if ($conn)
{
//echo "Connection established.<br />";
}
else
{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$sql = ("SELECT DefaultContact2 FROM tblServices WHERE ServiceName = '$service'");
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false)
{
die( print_r( sqlsrv_errors(), true));
}
while ($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
$dC2 = $row['DefaultContact2'];
}
echo json_encode ($dC2);
sqlsrv_free_stmt( $stmt);
?>
Any help would be greatly appreciated.
You could send data using your Ajax request like so.
$.ajax({
url: "http://IP/development/Query01.php",
method: "POST" // send as POST, you could also use GET or PUT,
data: { name: "John", location: "Boston" }
dataType: "json",
success: function(data) {
editors['Contact2'].setValue(data);
}
});
Then in PHP access the sent data:
<?php
print_r($_POST);
/*
[
"name" => "John",
"location" => "Boston"
]
*/
?>
You cannot pass the javascript's variable to php on same page.
You can do this with ajax call with POST or GET method, and then you can send the manipulated data back to you browser and store it in your javascript's object or variable.
You can do it in a single Ajax call.
Remove from your code this line:
window.location.href = "http://IP/development/Query01.php?service=" + a;
And modify a bit the Ajax call
$.ajax({
type: 'GET'
data : {
service: sender.getValue();
},
url: "http://IP/development/Query01.php",
dataType: "json", //the return type data is jsonn
success: function(data){ // <--- (data) is in json format
editors['Contact2'].setValue(data);
//alert(data);
//parse the json data
}
});
I put the same variable name for the Get in the Ajax call. But I don't know if your query01.php should accept to do now both actions in the same call.
Thank you guys for your help. Just thought it would be useful, if I posted of what I went with in the end, regardless of whether it is the right way, it certainly done the job.
// If the user changes the ServiceID field.
if (sender.getFieldName() == 'ServiceID')
{
// Variable Declaration
serviceName = sender.getValue();
{
// Use JQuery.Ajax to send a variable to the php file, and return the result.
$.ajax({
// Access the PHP file and save the serviceName variable in the URL, to allow the $_GET..
// method to access the javascript variable to apply it within the SQL Query.
url: "http://ServerName/development/DefaultContact1.php?service=" + serviceName,
// retrieve the result, using json.
dataType: "json", // the return type data is jsonn
success: function(data)// <--- (data) is in json format
{
// pre-fill the contact1 field with the result of the PHP file.
editors['Contact1'].setValue(data);
}
// End of Ajax Query
});
// End of function to prefill Contact1 field.
Thank again for your responses!

Transferring hash maps over ajax and converting to php array

I'm making an interpreter for a mini language, and I'm storing related information in hash maps. I'm convering those hash maps with JSON stringify, to send them over via ajax to the server side.
This is is the post-JSON stringify code I'm sending over to the server side:
{"kv":["24","23","20"],"interface":"dropdown"},{"ma":["2","3","4"],"interface":"button"}
On the server side, how could I easily make a php array out of the "kv":["24","23","20"] bit without searching for certain characters?
Before sending it over ajax the output of json array is:
{"kv":["24","23","20"],"interface":"dropdown"},{"ma":["2","3","4"],"interface":"button"}
After receiving it, the data is:
{"kv":["24","23","20"],"interface":"dropdown"},{"ma":["2","3","4"],"interface":"button"}
after the htmlspecialchars_decode function, it becomes:
{"kv":["24","23","20"],"interface":"dropdown"},{"ma":["2","3","4"],"interface":"button"}
json_decoding that gives me null
The ajax code:
function addValues(jsonArray) {
alert(jsonArray);
$.ajax({
url: 'insertTree.php',
type: 'POST',
data: 'dataToReceive=' + jsonArray,
success: function(data) {
//called when successful
alert(data);
window.location.reload();
},
error: function(e) {
//called when there is an error
console.log(e.message);
}
});
}
the php receiving code:
$dataReceived = htmlspecialchars(strip_tags($_POST["dataToReceive"]));
$dataRefined = htmlspecialchars_decode($dataReceived);
$var = json_decode($dataRefined, true);
var_dump($var['kv']); //null
Use json_decode to get the value. Since your base string isn't valid JSON, I massaged it a bit to get it to be
$string = '{"kv":["24","23","20"],"interface":"dropdown"},{"ma":["2","3","4"],"interface":"button"}';
$data = explode('|', str_replace('},{', '}|{', $string));
foreach($data as $str) {
$var = json_decode($str, true);
if(isset($var['kv'])) var_dump($var['kv']);
}

jQuery Ajax call not returning anything

I have an Asynchronous call in jQuery where a POST request returns an HTTP 200, but there is no response text or anything to work with from the endpoint in question.
I'm confused as to what could be the cause on my Localhost, as when I use the same call to poll a service like JSONTest, I get a valid object back in return.
This is what the result endpoint looks like, written in PHP using Slim
$app->post("/search", function() use ($app) {
try {
$request = $app->request;
$body = $request->getBody();
$input = json_decode($body);
//Prepare search string
$query = "%". $input->query . "%";
$grade = '%grade ' . $input->grade . "%";
$meta = $input->meta;
$proc_results = array();
$item = new stdClass();
$item->id = 1;
$item->source = "source";
$item->type = "lesson_plan";
$item->description = "Description of the Lesson Plan";
$item->date_created = 1234567890;
$proc_results[] = $item;
$app->response()->header('Content-Type','application/json');
$app->response()->body(json_encode($proc_results));
} catch (Exception $e) {
}
});
This call does return a JSON response when using a utility like POSTMAN, but when I use the following test jQuery code, I get an Object that has no responseText or any sign that my interpreter has the object.
$.ajax({
"type":"POST",
"url":"http://localhost:9001/search",
"data":{"query":"math","grade":"4"}
}).done(function(result) {
console.debug(result);
});
Am I missing a component in my done() call to poll the resources? Is my Slim call sending malformed JSON? If needed I can get a working demo up online.
Type, url, data should not be strings. Try as not string. It should work. Also the keys of data shouldnot be string.
Try this
$.ajax({
type:"POST",
url:"/search",
data:{query:"math",grade:"4"}
}).done(function(result) {
console.debug(result);
});
Try setting the datatype to be JSON, expanding on #doniyor's answer:
$.ajax({
type:"POST",
url:"/search",
datatype:"json",
data:{query:"math",grade:"4"}
}).done(function(result) {
console.debug(result);
})
see: http://api.jquery.com/jquery.ajax/
Seems from your comments that you are looking for JSON as a result.
I found the root cause: I was not sending valid JSON for PHP to parse. By adding JSON.stringify it responds as expected:
$.ajax({
type:"POST",
url:"http://localhost:9001/search",
dataType:"json",
contentType: "application/json",
data: JSON.stringify({"query": "math", "grade": "4", "meta": "z"})
}).done(function(result) {
console.debug(result);
});
Thanks guys for helping.

Best practice when changing PHP Data to JS Data via AJAX (especially arrays)

(Secondary title): ajax array recieved as json encoded PHP array not behaving as javascript array
For some reason, my PHP array gets sent over to JavaScript just fine, but when I try to access an individual key of the array, it doesn't return anything, or it returns some other value which doesn't correspond. I am of course using json_encode() in the corresponding PHP file (echoClientData.php):
$id = $_GET['selected_id'];
$id = str_replace("clientSel","",$id);
$getclientinfo = "SELECT * FROM `clients` WHERE `ClientID` = $id";
if ($result = $Database->query($getclientinfo))
{
$row = $result->fetch_row();
$output = $row;
}
echo json_encode($output);
This code works fine:
$.ajax(
{
url: "echoClientData.php?selected_id=" + HTMLid,
type: 'GET',
success: function(data)
{
test = data;
$('#client-detail-box').html(test);
}
});
And returns an array into the #client-detail-box div, e.g.
["1566","","Adrian","Tiggert","","","","","","","","","","","","0000-00-00","0000-00-00","0.00","","0","","","102","Dimitri Papazov","2006-02-24","102","Dimitri Papazov","2006-02-24","1","0","0"]
However, when I do
$.ajax(
{
url: "echoClientData.php?selected_id=" + HTMLid,
type: 'GET',
success: function(data)
{
test = data[3]; // should be "Tiggert"
$('#client-detail-box').html(test);
}
});
}
It returns
5
You may need to do one of two things when returning JSON from PHP.
Either set your content type in PHP before echoing your output so that jQuery automatically parses it to a javascript object or array:
header('Content-type: application/json');
or specify that jQuery should treat the returned data as json:
$.ajax(
{
url: "echoClientData.php?selected_id=" + HTMLid,
type: 'GET',
dataType: 'json',
success: function(data)
{
var test = data[3]; // should be "Tiggert"
$('#client-detail-box').html(test);
}
});
Be aware, that in your current PHP script, in the event that your query fails, you will be json_encodeing an undefined variable.
Also, your PHP code is entirely open to SQL injection. Make sure you sanitize your $id, either by casting it to (int) or by escaping it before sending it through in your query.
Have you tried using JSON.parse on the value you are getting back from PHP?
e.g.
$.ajax(
{
url: "echoClientData.php?selected_id=" + HTMLid,
type: 'GET',
success: function(data)
{
test = JSON.parse(data); // should be "Tiggert"
$('#client-detail-box').html(test[3]);
}
});
That seems like it would be a fix.

How to get the type of the returned object from .POST ajax call?

Im using ajax .POST to run php script that suppose to return true/false. Im returning true/false using "echo" in my script. But after i get the result back to JS i compare the received text in an IF statement that never works! here is my code
$.ajax({ url: 'admin_checkuser.php',
data: {action: window.myId},
type: 'post',
success: function(output) {
if (output == "true"){
and here is the php script that being called
include_once('class.MySQL.php');
$userid = $_POST['action'];
$oMySQL = new MySQL();
$query = "Select * FROM videotable WHERE uid = '$userid'";
$oMySQL->ExecuteSQL($query);
$bb = $oMySQL->iRecords;
$aa = $oMySQL->aResult;
if ($bb == 0){
$query = "INSERT INTO videotable VALUES ('','$userid','true')";
$oMySQL->ExecuteSQL($query);
echo 'true';
exit();
}else{
$sharing = mysql_result($aa,0,"share");
echo $sharing;
exit();
}
I made sure that i receive true\false by doing "alert(output)" and it always displays true\false so i really dont understand why my IF statement fails even when alert(output) shows true
Thanks in advance!
Trying to parse the type of an ajax response tends to be super unreliable, in my experience.
For that reason, I (now) make darn sure that whenever I write a server side function that is meant for returning ajax data, I keep it perfectly in line with my own set response "standard", and then set my response type in the ajax method to JSON.
Doing so makes handling errors much more predictable.
An example of a standardized response would be:
$ajaxResponse = array(
'data' => $someData,
'result' => true,
'message' => 'your yadayada was succesful',
'timestamp' => time()
);
print json_encode($ajaxResponse);
and in ajax, your response would be like:
success: function( response ) {
if(response.result) {
alert(response.message);
}
}
Sorry if this isn't much help but you could try:
$.ajax({ url: 'admin_checkuser.php',
data: {action: window.myId},
type: 'post',
dataType: 'json',
success: function(output) {
if (output) { ... }
and
echo json_encode(true);
// echo json_encode($sharing);
The jQuery documentation gives more detail on what this call returns: http://api.jquery.com/jQuery.ajax/.
success(data, textStatus, jqXHR)Function, Array
A function to be called if the request succeeds. The function gets
passed three arguments: The data returned from the server, formatted
according to the dataType parameter; a string describing the status;
and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery
1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.
It looks like you are expecting the data that is returned from the AJAX call to be the string "true" in your test, so if that isn't passing it must be you are getting back something other than this exact string.
I recommend using the net tab of Firebug in Firefox to see the XHR request and to examine the response of what you are getting back to see if it is something other than what you expect.

Categories