Trying to get information from database with jQuery - php

I am VERY new to jQuery, and I have been trying to get information from my SQL database whenever the user chooses a new option in a datalist form. This is the code:
<form>
<input list="chemicals" name="chemicalsearch">
<datalist id="chemicals">
<?php while ($info3=mysql_fetch_array($info2)) {
echo "<option value='$info3[name]'>$info3[formel]</option>";
}
?>
</datalist>
</form>
<script type="text/javascript">
$('#chemicals').on('change', function() {
var record_id = $(this).val();
var data = {
'id': record_id
};
$.ajax({
type: "GET",
url: '/Chemistry%20Calculator/getchemical.php',
data: data,
success: function(response) {
document.getElementById('formel').innerHTML = data.formel;
},
error: function(jqXHR, textStatus, errorThrown) {
}
});
});
</script>
And then the PHP file:
<?php
include_once 'connect.php';
$info="SELECT * from chemicals where name='$id'";
$info2=mysql_query($info) or die("Wrong link. This page does not exist.");
$info3=mysql_fetch_array($info2);
$name = $info3['name'];
$formel = $info3['formel'];
$massa = $info3['molmassa'];
$array = array($name, $formel, $massa);
$data = json_encode($array);
echo $data;
?>
Please be patient with me here, as I have never used jQuery before. And yes, I am aware of the fact that I'm using the old MySQL syntax, I will change that as soon as I get this working.
Any help would be greatly appreciated :)

You are not writing what exactly is the problem, either from the side of php or javaScript. But anyway, correct your syntax to php regarding the variables. Like below:
<?php while ($info3=mysql_fetch_array($info2)) {
echo '<option value="'.$info3[name].'">'.$info3[formel].'</option>';
}?>
and later on your query...$info='SELECT * from chemicals where name="'.$id.'"'

The success method is 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 or the dataFilter callback function, if specified;
A string describing the status;
The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object.
In your case:
success: function(data, textStatus, jqXHR) {
//The "data" returned from server is assigned to HTML element here
document.getElementById('formel').innerHTML = data;
}
A side note: usage of mysql_* functions is deprecated, use PHP PDO instead.
EDIT: Do not forget to include jQuery library in your file, before trying to execute the code $(“#chemicals")..... The error of $ being undefined means exactly that.

Related

Multiple Ajax call with same JSON data key calling one php file

I am trying to validate list of dynamic text fields.
Validation needs an AJAX call to interact with server.
At the backend I have written just one php file that reads the input request data and performs operation. Below is the example.
abc.js
row_count = 6
for (i = 1; i <=row_count; i++) {
id = "#val"+i.toString() ;
$(id).change(function(){
input_val="random";
$.ajax({
url:"url.php",
type:post,
async:true,
dataType: 'json',
data : {temp:input_val},
success:function(result){},
error: function (request, status, error) {}
});
});
}
url.php
<?php
$random_val = $_POST['temp'];
$cmd = 'systemcommand '.$random_val;
$flag = exec($cmd);
if ($flag == 0){
echo json_encode(array("status"=>'Fail'));
}
else{
echo json_encode(array("status"=>'Success'));
}
?>
It works fine when the row_count = 1 (Just one text field) but fails when the input is more than 1.
When the count is more than 1, the php script is not able to read the request data(The key in JSON data "temp"). it is blank in that case.
Any lead or help should be appreciated.
Thanks
Your javascript bit needs some adjusting, because you do not need to define an ajax for every single element. Use events based on a class. Also, since input behave differently than select, you should setup two different event class handlers.
function validateAjax ( element ) {
var input_val = element.val();// get the value of the element firing this off
$.ajax({
url: "url.php",
type: 'post',
async: true,
dataType: 'json',
data : { temp: input_val },
success: function(result) {
// check your result.status here
},
error: function (request, status, error) { }
});
}
$(".validate_change").on("change",function() { // for selects
validateAjax( $(this) );
});
$(".validate_input").on("input",function() { // for text inputs
validateAjax( $(this) );
});
And for your select or input you add that appropriate class.
<select class="validate_change" name="whatever"><options/></select>
<input class="validate_input" name="blah">
PS
I really worry about this code you have:
$cmd = 'systemcommand '.$random_val;
$flag = exec($cmd);
So, you are just executing anything that is coming in from a webpage POST var??? Please say this website will be under trusted high security access, and only people using it are trusted authenticated users :-)

Use Jquery AJAX to get PHP Object

To try and be as short and sweet, yet as descriptive as possible i am having issues grabbing a PHP Object through Jquery Ajax.
I am a semi-new PHP developer and i have created an object containing some strings and variables as shown here:
calculation.php
$return = new stdClass;
$return->success = true;
$return->errorMessage = "Oops, something went wrong!";
$return->Score = number_format($scoreFromSheet,1);
$return->roi = number_format($roiFromSheet,1);
$return->dvScoreAnalysis = $scoreAnalysis;
$return->className = $className;
$json = json_encode($return);
echo $json;
I have constructed a very crude Ajax call to the PHP file to try to access the json_encoded object. As shown here:
finalPage.php
$(document).ready(function(){
var data;
$.ajax({
dataType: "json",
url: './dvs_calculation/calculation.php',
data: {data:data},
success: function (json) {
alert('working');
console.log(json[0].Score);
},
error: function(xhr, textStatus, errorThrown) {
alert( "Request failed: " + textStatus );
}
});
});
I have echo'd the object to the DOM to display the output of my object, and it looks pretty solid:
$json output
{
"success":true,
"errorMessage":"Oops, something must've gone wrong!",
"Score":"65.5",
"roi":"25.8",
"ScoreAnalysis":"High Deal Viability"
}
When using the Ajax function i receive a parse error and it prints out nothing from the success function. Not sure where i am going wrong. Any help or reference greatly appreciated.
Access the Score value from the json response as
json.Score //gives you the value of Score key from json
Also according to the code provided, you aren't passing anything to the php side as the data variable is just defined

$_POST is empty even though I can see the $_POST data in firebug post, html, and response tabs

So I'm grabbing the state of a jquery date picker and a dropdown select menu and trying to send those two variables to another php file using AJAX.
var_dump($_POST);
results in this on the webpage:
array(0) {
}
BUT, when I look at the Net panel in Firebug, I can see the POST and GET urls and it shows the Post, Response, and HTML all showing the variables that I sent to the PHP file, but when dumping, it shows nothing on the page.
I've been looking through other similar issues on SO that has led me to changing the php.ini file to increase the post size and to updating my ajax call to use json objects and then parse through it on the php side.
Currently I'm just trying to get passing a string to work, and my code looks like this:
AJAX:
$("#submit_button").click(function() {
// get date if selected
var selected_date = $("#datepicker").datepicker("getDate");
// get show id if selected
var selected_dj = $("#show-list").val();
// put the variables into a json object
var json = {demo : 'this is just a simple json object'};
// convert to json
var post_data = JSON.stringify(json);
// now put in variable for posting
var post_array = {json : post_data};
$.ajax({
type: "POST",
url: template_dir + "/get-show-logs.php",
data: post_array,
success: function(){
alert("Query Submitted");
},
error: function(xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
}
});
// clear div to make room for new query
$("#archived-posts-container").empty();
// now load with data
$("#archived-posts-container").load(template_dir + "/get-show-logs.php #get_logs");
});
Now this is the php that's running from the .load() call, and where I'm trying to access the $_POST variables:
get-show-logs.PHP:
<div id="get_logs">
<?php
if(isset($_POST["json"])){
$json = stripslashes($_POST["json"]);
$output = json_decode($json);
echo "im here";
var_dump($output);
// Now you can access your php object like so
// $output[0]->variable-name
}
var_dump(getRealPOST());
function getRealPOST() {
$pairs = explode("&", file_get_contents("php://input"));
$vars = array();
foreach ($pairs as $pair) {
$nv = explode("=", $pair);
$name = urldecode($nv[0]);
$value = urldecode($nv[1]);
$vars[$name] = $value;
}
return $vars;
}
?>
</div>
You can see that I'm trying just accessing the $_POST variable, and the isset check isn't passing, (the page isn't echoing "im here"), and then I'm also trying parsing through the input myself, and that is also empty.
the output on the page looks like this:
array(1){[""]=>string(0)""}
BUT, once again, the Firebug Net panel shows the following under the Response tab:
<div id="get_logs">
im hereobject(stdClass)#1 (1) {
["demo"]=>
string(33) "this is just a simple json object"
}
array(1) {
["json"]=>
string(44) "{"demo":"this is just a simple json object"}"
}
</div>
I'm not sure what could be causing the issue, the Firebug can see it, but the php file sees an empty array.
Now I'm very new at using ajax and $_POST and such, so if you read anything that you're not 100% sure about, don't assume that I know anything about it! Speak up! haha.
Also, I'm doing this with MAMP on Localhost, so I'm not sure if that leads to any issues.
Thanks for the help in advance!
You aren't using the response in your AJAX call currently. See this example which will output the returned response to the console.
$.ajax({
type: "POST",
url: template_dir + "/get-show-logs.php",
data: post_array,
success: function(response){
console.log(response);
},
error: function(xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
}
});
Success
Type: Function( Anything data, String textStatus, jqXHR jqXHR )
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 or the dataFilter callback function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object.
-http://api.jquery.com/jquery.ajax/
Also this might be a good page to read more about jQuery and AJAX, https://learn.jquery.com/ajax/jquery-ajax-methods/.

PHP and JavaScript Change Status in MySQL

So I have a to-do list of items that are dynamically populated by user input. Each has a checkbox next to it, when checked, the status of the to-do item in MySQL database should be modified.
I thought of doing it this way:
echo "<input type='checkbox' onclick='changeState($theid);' />";
where $theid is the row id in the table.
What would the javascript/jquery changeState() function look like to be able to update the database properly?
Here is the javascript code that seems to not work at all (it is placed in the <head> of the HTML file:
<script language="javascript">
function changeState()
{
jQuery('body').delegate('input[type="checkbox"][data-state-id]', 'change', function(event){
jQuery.post('updatedata.php', {
'rowid': jQuery(this).attr('data-state-id')
//'state': jQuery(this).is(':checked')
});
});
}
</script>
any ideas why?
You should read more about AJAX calls, preferably with .post() function, and then update the data in database on the server side.
Good luck.
Based on the examples from the documentation of jQuery's .post(), you can implement something like this (in JavaScript with jQuery):
var changeStatus = function(id){
$.post("updateState.php", { 'id': id } );
};
and on the server side (eg. in updateState.php):
$id = (int)$_POST['id'];
// here make some query using $id to update the state
// in a manner you prefer
EDIT:
But I would prefer something like that:
1) on server side, displaying the checkbox (notice different quotes and (int) cast):
echo '<input type="checkbox" data-state-id="' . (int)$theid . '" />';
2) somewhere in JavaScript (see jsfiddle as a proof):
jQuery(main_container).delegate('input[type="checkbox"][data-state-id]', 'change', function(event){
jQuery.post('update_state.php', {
'id': jQuery(this).attr('data-state-id'),
'state': jQuery(this).is(':checked')
});
});
3) somewhere on server side (in update_state.php):
$id = (int)$_POST['id'];
$state = (bool)$_POST['state'];
$query = 'UPDATE `states` SET `state`="' . $state . '" WHERE `id`="' . $id . '";';
// here execute the query, obviously adjusted to your needs
You don't need to think of this as: "JavaScript will update the SQL Record", think of this as "JavaScript will tell a API to update that id."
So basically what you have to do is make an API with PHP; and then make JavaScript do the correct API Call via $.ajax, that should do the trick.
$.ajax({
url: '/path/to/api.php',
type: 'POST',
dataType: 'xml/html/script/json/jsonp',
data: {param1: 'value1'},
complete: function(xhr, textStatus) {
//called when complete
},
success: function(data, textStatus, xhr) {
//called when successful
},
error: function(xhr, textStatus, errorThrown) {
//called when there is an error
}
});

JSON data response from PHP server is empty

I'm having a hard time figuring this one out. Seems like no matter what I try, PHP always ends up returning an empty array. Here's the code of my main file(index.php):
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$(".ajaxlink").click(function() {
callServer();
return false; //Stop link from redirecting
});
});
var test = { "testName": "testValue" }
var testJSON = JSON.stringify(test);
function updatePage(data) {
document.getElementById("testDiv").innerHTML = data;
}
function callServer() {
$.ajax({
type: "POST",
url: "ajax/server.php",
data: testJSON,
success: function(data) {
updatePage(data);
},
//Upon error, output message containing a little info on what went wrong
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('An Ajax error occured\ntextStatus = ' + textStatus + '\nerrorThrown = ' + errorThrown + '\nstatus = ' + XMLHttpRequest.status);
}
});
}
</script>
<div id="testDiv">Something here</div>
Link! <br>
This basically runs the callServer() function when you click the "Link!". It then sends the test json data, that is { "testName": "testValue" } to server.php. Firebug reports that the json-data is indeed sent to the server.php.
My server.php looks like this:
<?php
print_r($_POST);
?>
This returns the following in the testDiv:
Array
(
)
The datatype in the .ajax function is not defined, so whatever output the server.php file spits out, it should be readable. All the necessary libraries(json, jquery) are included in my document as well. I'm running this on Apache 2.2 and PHP 5.3.1, but it shows the same on my webserver (which is a host for thousands of websites). The content-type used in the request-header is 'application/x-www-form-urlencoded; charset=UTF-8' so that should work correctly.
Thanks for your time.
Best regards
soren
I think you send the data in a wrong way. Either you send a string like testName=testValue or you assign the value in test directly to the data parameter of .ajax() and don't use the stringify method.
Because, if you use stringify, the actual sent data will be (I assume, I am not sure here):
'{ "testName": "testValue" }'
but this is not a valid parameter string.
It should be of form
'testName=testValue'
So use test directly, .ajax() will convert the object into an appropriate string:
function callServer() {
$.ajax({
type: "POST",
url: "ajax/server.php",
data: test,
success: function(data) {
updatePage(data);
},
//Upon error, output message containing a little info on what went wrong
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('An Ajax error occured\ntextStatus = ' + textStatus + '\nerrorThrown = ' + errorThrown + '\nstatus = ' + XMLHttpRequest.status);
}
});
}
I'm not sure your output from your PHP script is JSON formatted.
If you're using a newer version of PHP (which you are) you'll have access to the json_encode and json_decode functions. Instead of doing:
print_r($_POST);
Try:
print json_encode($_POST);
If your version of PHP doesn't have these functions you can use a library such as the Zend_Json class in the Zend Framework, in order to encode your PHP variables as JSON before outputting them.
And when it comes back, it'll be a JSON-formatted string. Setting the dataType in your jQuery.ajax call should evaluate it to a JS object. If not you would either have to call the Javascript eval function on it, or (preferably) use JSON.parse(data).
Use firefox and Live Http Headers extension.
With this you'll be able to see exactly where the problem lies,
Php or Js code.
live http headers

Categories