Just realized I was going about this all wrong:( I have a bunch of input fields that I want to submit using JQuery .post() or equivelant so I don't navigate away from the page. I have a database driven form that creates a row of multiple inputs using foreach $row and the output looks like this:
<tr class="even"><td width=200>Settings</td><input type="hidden" id="Settings[0]" value="1"><td><input type="textbox" id="Settings[1]" size="75" value="settings.php"></td><td><select id="Settings[2]"><option value="0" selected>No Parent</option><option value="1">Settings</option><option value="2">Grid Demo</option><option value="3">TEST</option><option value="4">Grid Options</option><option value="5">setGridOptions</option><option value="6">Menu Items</option><option value="7">Ajax Menu</option></select></td><td><input type="textbox" id="Settings[3]" size="5" value="0"></td><td><input type="hidden" id="Settings[4]" value="INACTIVE"> <input type="checkbox" id="Settings[4]" value="ACTIVE"></td></tr>
<tr class="odd"><td width=200>Grid Demo</td><input type="hidden" id="Grid_Demo[0]" value="2"><td><input type="textbox" id="Grid_Demo[1]" size="75" value="grid.php"></td><td><select id="Grid_Demo[2]"><option value="0" selected>No Parent</option><option value="1">Settings</option><option value="2">Grid Demo</option><option value="3">TEST</option><option value="4">Grid Options</option><option value="5">setGridOptions</option><option value="6">Menu Items</option><option value="7">Ajax Menu</option></select></td><td><input type="textbox" id="Grid_Demo[3]" size="5" value="100"></td><td><input type="hidden" id="Grid_Demo[4]" value="INACTIVE"> <input type="checkbox" id="Grid_Demo[4]" value="ACTIVE"></td></tr>
<tr class="even"><td width=200>TEST</td><input type="hidden" id="TEST[0]" value="3"><td><input type="textbox" id="TEST[1]" size="75" value="test.php"></td><td><select id="TEST[2]"><option value="1">Settings</option><option value="2">Grid Demo</option><option value="3">TEST</option><option value="4">Grid Options</option><option value="5" selected>setGridOptions</option><option value="6">Menu Items</option><option value="7">Ajax Menu</option></select></td><td><input type="textbox" id="TEST[3]" size="5" value="0"></td><td><input type="hidden" id="TEST[4]" value="INACTIVE"> <input type="checkbox" id="TEST[4]" value="ACTIVE"></td></tr>
I had been working so hard in php to pull the data into an array and run it through json_encode getting it ready to send to .post() when I realized that it would only continue to save whatever it was when the page was loaded, and not the current state after edits.
Now being so much older and wiser than I was when I started this project, I realize that won't work and I need to be using the .val(), but not sure how I should be setting this up since I don't know how many rows there will be, or what the names will be, how do I keep everything associated so things don't get mixed up?
The PHP side looks like this before it gets processed.
<?
include 'db.php';
$i=0;
foreach($db->query('SELECT * from navmenu') as $row) {
$rowarray[$row[0]] = array();
echo ($i % 2)?'<tr class="odd">':'<tr class="even">';
print_r("<td width=200>" . $row[2] . "</td>");
print_r("<input type=\"hidden\" id=\"");
$row[2] = str_replace(' ', '_', $row[2]);
print_r("". $row[2] . "[0]\" value=\"" . $row[0] . "\">");
print_r("<td><input type=\"textbox\" id=\"" . $row[2] . "[1]\" size=\"75\" value=\"" . $row[3] . "\"></td>");
//parent selection
print_r("<td><select id=\"" . $row[2] . "[2]\">");
if($row[1] == "0"){
print_r("<option value=\"0\" selected>No Parent</option>");
}
foreach($db->query('SELECT * from navmenu') as $option) {
print_r("<option value=\"" . $option[0] . "\"");
if($row[1] == $option[0]){
print_r(" selected");
}
print_r(">" . $option[2] ."</option>");
}
// end foreach
print_r("</select></td>");
print_r("<td><input type=\"textbox\" id=\"" . $row[2] . "[3]\" size=\"5\" value=\"" . $row[4] . "\"></td>");
// setup status whether active or not
print_r("<td><input type=\"hidden\" id=\"" . $row[2] . "[4]\" value=\"INACTIVE\"> "); //set value so it never passes NULL
if ($row[3] == "ACTIVE"){
print_r("<input type=\"checkbox\" id=\"" . $row[2] . "[4]\" value=\"ACTIVE\" checked=\"true\"></td></tr>");
}
else{
print_r("<input type=\"checkbox\" id=\"" . $row[2] . "[4]\" value=\"ACTIVE\"></td></tr>");
}
print_r("\n");
$rowarray[$row[0]]= array("id" => "$row[0]", "parentid" => "$row[1]", "name" => "$row[2]", "url" => "$row[3]", "sortorder" => "$row[4]", "status" => "$row[5]", "tooltip" => "$row[6]");
$i++; //increment by one
}
?>
This was what I was trying to use for the JQuery:
<script>
$(document).ready(function () {
$("a[id^=formsubmit]").click(function ( event ) {
$.post( "functions.php?do=adminmenu", $( "#saveForm" ).serialize() );
}
,function (data) {
$( ".contentarea2" ).html( data );
},"html");
});
</script>
If I understand your question correctly, you're asking how to send all form data without knowing ahead of time what that form data is? Like so:
$("#form").submit(function(e) {
e.preventDefault();
// abort any pending request
if (request) {
request.abort();
}
var $form = $(this);
var $inputs = $form.find("input, select, button, textarea");
var postData = $form.serialize();
// note: we disable elements AFTER the form data has been serialized
$inputs.prop("disabled", true);
request = $.ajax({
url: "submit.php",
type: "POST",
data: postData
})
.done(function(response, textStatus, jqXHR) {
// do something
})
.fail(function(jqHXR, textStatus, errorThrown) {
console.error('Error: ' + textStatus, errorThrown);
});
});
As far as processing it on the PHP end, you should name the fields which might have a variable number of values as an array (using brackets), for example:
<input type="text" name="ids[]" />
Then you can loop through it and process accordingly.
Related
I'm trying to POST submit the data to mysql using php from append javascript.
Here's the modal where data come from append which is in php.
<tr onload="calculate()">
<?php
foreach ($conn->query("SELECT * FROM panapricelist") as $info){
echo "<td><input type='checkbox' id='promotitle' name='check' value='".$info['ProductId']."' ></td>";
echo "<td><textarea rows='4' cols='7' maxlength='60' name='pcode' class='pcode' id='ProductCode' disabled>".$info['ProductCode']."</textarea></td>";
echo "<td><br><textarea rows='5' cols='40' maxlength='50' name='puse' class='productuse' id='productuse' disabled>".$info['ProductUse']." </textarea></td>";
echo "<td><br><textarea rows='4' cols='50' maxlength='50' name='pdesc' class='description' id='productDesc' disabled>".$info['ProductDesc']."</textarea></td>";
echo "<td id='msrp'><textarea rows='4' cols='10' maxlength='50' name='Msrp' class='msrp' id='productMsrp' disabled>".$info['Msrp']."</textarea></td>";
echo "<td style='width: 10%;'><textarea rows='4' cols='10' name='cost' maxlength='50' class='cost' id='cost' disabled>".$info['DealerPhp']."</textarea></td></tr>";
}
?>
</tbody>
Here's the append js from modal to table.
$(document).ready(function() {
$("#button_add").click(function() {
var favorite = [];
$.each($("input[name='check']:checked").each( function() {
// favorite.push($(this).val());
var getRow = $(this).parents('tr'); //variable for the entire row
var value = (getRow.find('td:eq(1)').html()); // Product Code
var value1 = (getRow.find('td:eq(2)').html()); // for Suggested Product Use
var value2 = (getRow.find('td:eq(3)').html()); // for product Description
var value3 = (getRow.find('td:eq(4)').html()); // for MSRP PHP
var value4 = (getRow.find('td:eq(5)').html()); // for Dealer PHP
var value5 = (getRow.find('td:eq(0)').html()); // for Dealer PHP
$('#item-row').append('<tr><td class="item-name"><textarea value="'+ value +'</textarea></td><td class="item-name"><textarea class="check" name="check[]" value= "' + value1 + ' </textarea> </td><td class="item-name"><textarea value= "' + value2 +' </textarea></td><td class="item-name"><textarea value= "' + value3 + ' </textarea> </td><td><textarea name="Msrp" value="' + value4 + '</textarea></td><td class="item-name"><textarea class="qty" id="qty" name="qty[]"> </textarea></td><td class="item-name"><textarea id="price" class="price" name="price[]" disabled></textarea></td></tr>');
}));
});
});
Questions is. how can i POST submit to mysql using PHP PDO the value come from append javascript??
You'll need to put any input data inside of a form, then create a PHP script that handles the POST request and INSERTS the data into your MySQL database.
Your form tag should look something like this:
<form class="post-form" action="script_that_handles_post.php" method="post">
So, you'll want to use $_POST['']. For example, the name in your first table row is name="check", you'll use $_POST['name'] to get the value of that field. Do that for each field that you want to store. Preferably, you should store each of those in their own variables or an array.
Then, for your AJAX you'll have to include the library somehow. If you aren't already, put this in your footer below the jquery source:
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
Now you can add your AJAX POST request. Here's some code that should do it:
$(".post-form").submit(function (event) {
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url:$form.attr('action'),
type:'POST',
data: serializedData
});
request.fail(function (jqXHR, errorThrown){
console.error(
"Error: " + errorThrown
);
});
request.always(function () {
$inputs.prop("disabled", false);
});
event.preventDefault();
});
What this code is doing is taking the action path of your form and posting the data from the inputs of the fields there.
I hope this helps.
I need a way of retrieving data from a processing script into a Request page using Ajax, PHP. The code below shows this error:
SyntaxError: JSON.parse: unexpected character at line 1 column 13 of the JSON data
var data4=JSON.parse(data4);
Please, note that I have search but have not been able to get solution. So, I thought maybe there is a way of passing the result to the requesting page without using json_encode.
<script type="text/javascript" src="includes/scripts/newJquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("select.partno").change(function() {
var selectedCustomer = $(".partno option:selected").val();
$.ajax({
type: "POST",
url: "process-grpid.php",
dataType: "json",
data: {
custid: selectedCustomer
}
}).done(function(data4) {
var data4 = JSON.parse(data4); //Error Area
//using php-mysql before
$("#desc").html(data4.ref);
$("#purch").html(data4.lprice);
});
});
});
</script>
<form>
<table>
<tr>
<th>Item Code/Part NO:</th>
<?php
include("db_connection.php");
$s = mysqli_query($connection,"SELECT * FROM tab_stock ORDER BY itemName ASC");?>
<td>
<select name="partno" class="partno">
<option>Select PartNo</option>
<option value="N/A">N/A</option>
<?php while($rw = mysqli_fetch_array($s)){ ?>
<option value="<?php echo $rw['itemName'];?>">
<?php echo $rw['itemName'];?>
</option>
<?php };?>
</select>
</td>
<th>Description:</th>
<td id="desc"></td>
</tr>
<tr>
<th>Last Purchase Price:</th>
<td id="purch"></td>
</tr>
</table>
</form>
process-grpid.php (Processing Script)
<?php
if (isset($_POST["custid"])) {
include 'includes/session.php';
include 'includes/db_connection.php';
include 'includes/functions.php';
$partid = $_POST["custid"];
if ($partid !== 'Select PartNo') {
$gets = "SELECT * FROM tab_stock WHERE itemName='" . $partid . "'";
$get = mysqli_query($connection, $gets);
$row = mysqli_fetch_array($get);
$desc = $row['description'];
$lprice = $row['Rate'];
if ($partid == 'N/A') {
$res["sta"] = 0;
$res["ref"] = "<input type='text' class='desc' name='descr' size='50' required='required'/>";
$res["lprice"] = "<input type='text' id='puch' name='lastpur' required='required'/>";
} else {
$res["sta"] = 1;
$res["ref"] = "<input type='text' value='$desc' class='desc' name='descr' size='50' readonly='readonly' required='required'/>";
$res["lprice"] = "<input type='text' id='puch' name='lastpur' value='$lprice' readonly='readonly' required='required'/>";
}
echo json_encode($res);
}
}
?>
When I run this Application, it shows an error of SyntaxError: JSON.parse: unexpected character at line 1 column 13 of the JSON data
var data4=JSON.parse(data4)
But when checked with Firebug, in the HTML and RESPONSE TAB, it shows the expected result. Question, what alternative way of getting result from a processing script to the requesting page, withput uisng json_encode and JSON.parse(response)?
Try removing
dataType: "json"
of the call ajax
Update:
If the configuration is dataType: json, you'll get a javascript object is no longer necessary JSON.parse
Try not using the JSON.parse at all ... as you get a native JavaScript Object back, not a JSON String ...
I took your code and made some tests. Next code works for me:
test.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function myAjax () {
var selectedCustomer = 1; // DATA FOR PHP.
$.ajax( { type : "POST",
url : "test.php",
data : { "custid" : selectedCustomer }, // DATA FOR PHP.
success: function ( data4 ) {
var data4 = JSON.parse( data4 );
alert( data4.custid );
alert( data4.sta );
alert( data4.ref );
alert( data4.lprice );
$("#desc").html( data4.ref ); // <TD> IN <BODY>.
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
</head>
<body>
<button onclick="myAjax()">echo hello</button>
<table>
<tr>
<td id="desc"></td>
</tr>
</table>
</body>
</html>
test.php
<?php
if ( isset( $_POST[ "custid" ] ) )
{ $res = array();
$res["custid"] = $_POST[ "custid" ];
$res["sta"] = 2;
$res["ref"] = "<input type='text' class='desc' name='descr' size='50' required='required'/>";
$res["lprice"] = "<input type='text' id='puch' name='lastpur' required='required'/>";
echo json_encode( $res );
}
?>
Notice I deleted the ajax line dataType : "json",, because as soon as I include it this code throws an error. Copy-paste previous codes in two files called "test.html" and "text.php", they work fine.
Instead of
echo json_encode($res);
Use:
echo json_encode(array('res' => $res));
And instead of:
var data4 = JSON.parse(data4);
Use:
var d = data4.res;
And than use "d" like an array. Here is the JS code I am trying to tell you:
$(document).ready(function() {
$("select.partno").change(function() {
var selectedCustomer = $(".partno option:selected").val();
$.ajax({
type: "POST",
url: "process-grpid.php",
dataType: "json",
data: {custid: selectedCustomer}
}).done(function(data4) {
var d = data4.res;
$("#desc").html(d['ref']);
$("#purch").html(d['lprice']);
});
});
});
If still there is an error, it is probably in the usage of "d" and you can change d['ref'] to d[1] and d['lprice'] to d[2].
I see that there is also a mistake when trying to concatenate $desc and $lprice to the input strings.
$res["ref"] = "<input type='text' value='" . $desc. "' class='desc' name='descr' size='50' readonly='readonly' required='required'/>";
$res["lprice"] = "<input type='text' id='puch' name='lastpur' value='" . $lprice . "' readonly='readonly' required='required'/>";
And a plus... if you use these variables only if $partid != 'N/A', why don't you move the query to inside the else statment? Doing this, you avoid to execute the query all the time.
if ($partid !== 'Select PartNo') {
if ($partid == 'N/A') {
$res["sta"] = 0;
$res["ref"] = "<input type='text' class='desc' name='descr' size='50' required='required'/>";
$res["lprice"] = "<input type='text' id='puch' name='lastpur' required='required'/>";
} else {
$gets = "SELECT * FROM tab_stock WHERE itemName='" . $partid . "'";
$get = mysqli_query($connection, $gets);
$row = mysqli_fetch_array($get);
$res["sta"] = 1;
$res["ref"] = "<input type='text' value='" . $row['description'] . "' class='desc' name='descr' size='50' readonly='readonly' required='required'/>";
$res["lprice"] = "<input type='text' id='puch' name='lastpur' value='" . $row['Rate'] . "' readonly='readonly' required='required'/>";
}
echo json_encode($res);
}
I have called the page search.php from ajax:
function search(){
var title=$("#search").val();
if(title!=""){
$.ajax({
type:"post",
url:"search.php",
data:"title="+title+"&idTratta="+<?php echo $idTratta ?>,
success:function(data){
$("#result").html(data);
$("#search").val("");
}
});
}
}
Now in search.php I get the result of a query in a html table and I created radio buttons in a form that when each form is submitted I get the value of the radio button's clicked and update a row in the db:
$title = $_POST["title"];
$idTratta = $_POST["idTratta"];
$SimpleUsers = new SimpleUsers();
$users = $SimpleUsers -> searchUser($title, $idTratta);
foreach ($users as $user) :
echo "<tr>
<td>" . $user["nome"] . "</td>
<td>" . $user["role"] . "</td>
<td class='right'><form action='' method='post'><label>
<input type='radio' name=" . $user["nome"] . " id='c' value='1' ";
if ($user["role"] == 'configuratore')
echo "checked='checked' />C</label>";
else
echo "/>C</label>";
echo "<label>
<input type='radio' name=" . $user["nome"] . " id='va' value='2' ";
if ($user["role"] == 'visualizzatore avanzato')
echo "checked='checked' />VA</label>";
else
echo "/>VA</label>";
echo "<label>
<input type='radio' name=" . $user["nome"] . " id='v' value='3' ";
if ($user["role"] == 'visualizzatore')
echo "checked='checked' />V </label>";
else
echo "/>V </label>";
echo "<input type= 'submit' name='sub_" . $user["nome"] . "'value='Cambia'/></form></td>
</tr>";
$sub = 'sub_';
if ($_POST[$sub . '' . $user["nome"]]) {
$permission = $_POST[$user["nome"]];
$SimpleUsers -> updateUserPermission($user["nome"], $idTratta, $permission);
}
endforeach;
The problem is that in search.php I am unable to catch POST variables, how I can get it?
EDIT
This is the piece of code which doesn't work:
if ($_POST[$sub . '' . $user["nome"]]) {
$permission = $_POST[$user["nome"]];
$SimpleUsers -> updateUserPermission($user["nome"], $idTratta, $permission);
}
The data shouldn't be parsed as text but instead as an js array like this:
data: {title: title, idTratta : <?php echo $idTratta ?>},
EDIT:
A example for sending the form data would be:
var formData = JSON.stringify($("#myForm").serializeArray());
formData['idTratta'] = <?php echo $idTratta ?>;
$.ajax({
type:"post",
url:"search.php",
data:formData,
success:function(data){
$("#result").html(data);
$("#search").val("");
}
});
And than using json_decode in your php form to turn it into a PHP array again. Its kind of dirty but it should work
Try this method
$.post("`search.php`", { title : title , idTratta : '<?php echo $idTratta ?>'},
function (data) {
$("`#result`").html(data);
$("`#search`").val("");
});
I have a html form in which user can select an option upon which ajax call should be fired to php controller.
<form action="<?php echo URL . 'task/show_list/' . $this->tasks[0]->list_id;?>" method="GET" id="#sortTaks">
<select name="sort_task" id="selectSortTask">
<option value="" selected="selected">Sort by:</option>
<option value="byName">Name</option>
<option value="byDeadline">Deadline</option>
<option value="byPriority">Priority</option>
<option value="byStatus">Status</option>
</select>
<input type="submit" value="Submit">
</form>
Now, i would like that sort functionality provided asynchronously with ajax. This is the corresponding php code:
//controller
public function show_list($list_id)
{
if (isset($list_id)) {
$task_model = $this->loadModel('TaskModel');
$check = $task_model->checkUserPermission($list_id);
if ($check) {
$tasks = $task_model->showTasks($list_id);
$this->view->tasks = $tasks;
$this->view->render('task/task');
} else {
header('location:' . URL . 'dashboard/index');
}
} else {
header('location:' . URL . 'dashboard/index');
}
}
//model
public function showTasks($list_id)
{
if (isset($_GET['sort_task']) and !empty($_GET['sort_task'])) {
$sort_parameter = strip_tags($_GET['sort_task']);
$sort_order = $this->sortData($sort_parameter);
$sort_order = 't.task' . $sort_order;
} else {
$sort_order = 't.task_name';
}
$sql = "SELECT t.task_name, t.task_id, t.task_priority, t.task_deadline, t.task_completed, l.list_id
FROM task AS t
LEFT JOIN list AS l ON l.list_id = :list_id AND l.list_id = t.list_id
WHERE l.user_id = :user_id
ORDER BY $sort_order";
$query = $this->db->prepare($sql);
$query->execute(array(':list_id' => $list_id, ':user_id' => $_SESSION['user_id']));
return $query->fetchAll();
}
//view snippet
echo '<td>' . $value->task_name . '</td><td>' . $priority . '</td><td>';
echo $task_deadline->format('l jS \of F Y h:i:s A');
echo '</td><td>';
echo $overdue_until->format('%R %a day/s, %h hours, %i minutes');
echo '</td><td>' . $status . '</td>';
echo '<td><a href="' . URL . 'task/edit_task/' . $value->list_id . '/' . $value->task_id . '">Edit</td>';
echo '<td><a href="' . URL . 'task/delete_task/' . $value->list_id . '/' . $value->task_id . '">Delete</td>';
echo '<td><a href="' . URL . 'task/completed/' . $value->list_id . '/' . $value->task_id . '">Completed</td>';
echo '</tr>';
What is the best approach in solving this problem? I'm a little bit confused with how should ajax call look like regarding mvc structure and presenting sorted data back to user.
Any help is much appreciated.
For now i have this:
$(document).ready(function(){
$('#selectSortTask').change(function(e){
e.preventDefault();
var sortParam = $('#selectSortTask').val();
$.ajax({
url: $(this).attr('action'),
type: "GET",
data: {sort_task: sortParam},
dataType: 'json',
success: function(data){
alert(data);
},
error: function(error){
alert(error);
}
});
return false;
});
});
Which alerts object Object as error. How to modify this ajax call and model/view/controller to get desired result? Alerts are for debugging purposes.
I have a form with the option to add another row at the click of a button.
This new row will have a select list as it's input type.
The select list needs to process information from a database that was retrieved on page load.
How can I have the new select list perform a while loop on the data from the database once it is created via the add button.
Here is the code I have so far.
PHP:
echo "<div id=\"FieldGroup\">";
echo "<select name=\"add_project_service_1\" class=\"project_details_service\" value=\"\" required >";
while($result->fetch())
{
echo "<option value=\"".$item_number."\">".$item_number." - ".$description."</option>";
}
echo "</select> ";
echo "<label>Quantity: </label><input type=\"text\" name=\"add_project_quantity_1\" class=\"project_details_quantity\" placeholder=\"Quantity\" value=\"\" /> ";
echo "<label>Value: </label><input type=\"text\" name=\"add_project_value\" class=\"project_details_value\" placeholder=\"Value\" value=\"\" /><br>";
echo "</div>";
echo "<input type=\"button\" value=\"Add Button\" id=\"addField\"><input type=\"button\" value=\"Remove Button\" id=\"removeField\">";
Javascript:
<script>
$(document).ready(function() {
var counter = 2;
$("#addField").click(function () {
if(counter>50){
alert("Only 50 extra fields allowed.");
return false;
}
var newFieldDiv = $(document.createElement('div'))
.attr("id", 'FieldDiv' + counter);
newFieldDiv.after().html('<select name="add_project_service_' + counter + '" class="project_details_service" value="" required >' +
'while($result->fetch())
{
echo "<option value=\"".$item_number."\">".$item_number." - ".$description."</option>";
}</select> ' +
'<label>Quantity: </label><input type=\"text\" name=\"add_project_quantity_' + counter + '\" class=\"project_details_quantity\" placeholder=\"Quantity\" value=\"".$quantity."\" /> ' +
'<label>Value: </label><input type=\"text\" name=\"add_project_value_' + counter + '\" class=\"project_details_value\" placeholder=\"Value\" value=\"".$value."\" /><br>');
newFieldDiv.appendTo("#FieldGroup");
counter++;
});
$("#removeField").click(function () {
if(counter==2){
alert("No more fields to remove.");
return false;
}
counter--;
$("#FieldDiv" + counter).remove();
});
});
</script>
Inserting the while loop into the javascript doesn't work.
How can this be accomplished so when I add a field the options are listed and fields are populated?
javascript is exectued on client side while php interpreted on the server side.
Once you've send the page to the client, the only way to edit the page without reloading a new one is with javascript and ajax call (xmlhttprequest). The client doesn't use php neither download php page from the server.
You could do an ajax call to your page with jquery
$.ajax{
url: "mypage.php",
type: "GET",
dataType: "jsonp",
success: function( myObject ) {
console.dir( myObject );
}
}
// mypage.php
header('Content-type: application/json');
echo json_encode( $myObject );
// for you it will be
echo json_encode( $result->fetch() );