Sencha ajax call to php file - php

I'm both a sencha and ajax newbie. I'm trying to return some data from a php file that connects to a mysql server. I'm triggering an ajax request when I press a button.
Here is my sencha code for when the button is pressed........
onShow: function(){
setInterval(function(){
console.log("Server pinged");
myRequest = Ext.Ajax.request({
url: 'http://localhost/getpoi.php',
method: 'GET',
params: {
poiid: '3'
},
callback: function(response) {
console.log(response.responseText);
}
});
},5000);
},
My getpoi php file code is as follows.......
<?php
$poiid = $_GET["poiid"];
$lat;
$long;
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("murmuration_db", $con);
$result = mysql_query("SELECT * FROM POI WHERE id=$poiid");
while($row = mysql_fetch_array($result))
{
$lat = $row['anchor_geolocation_lat'];
$long = $row['anchor_geolocation_lon'];
}
$response = $lat. ' '. $long;
echo $response;
return $response;
mysql_close($con);
?>
The php file is working because if I change set poiid to 3 in the file itself and open it in the browser, I get the position. But if I call it within the sencha app through the button the console is logging 'server pinged' correctly but is logging 'undefined' instead of the co-ordinates. Any ideas what I'm doing wrong?
Thanks in advance
A

it look like you ajax is not sending the request right.
Try this:
setInterval(function(){
console.log("Server pinged");
myRequest = Ext.Ajax.request({
url: 'http://localhost/getpoi.php?poiid=3',
method: 'GET',
callback: function(response) {
console.log(response.responseText);
}
});
to be sure that is loading press F12, go to Network and look the requests. ;)
(Firebug or Inspect Element on Chrome)

Related

Ajax call failing; xhr.responseXML is undefined

I'm trying to make a simple ajax call:
When the user selects and option, some info about that option will be
echoed into a div (this is dynamic)
Here's my code for the ajax call
ajax.js
$(document).ready(function()
{
//Add Event
//Currently Broadcasting #Zone
$('#beacon0').on('change', function ()
{
var Selected = $(this).find("option:selected");
var SelectedText = Selected.text();
var SelectedEncoded = encodeURIComponent(SelectedText);
$.ajax
({
url: 'ajax-addevent.php',
data: 'n_beacon='+ SelectedEncoded,
dataType: 'JSON',
success: function(returnClass)
{
var resultajax = jQuery.parseJSON(returnClass)
console.log(resultajax);
},
error: function(xhr, status, error)
{
var errors = JSON.parse(xhr.responseText);
console.log("failed");
console.log (errors);
}
});
});
});
SO the ajax call should give the name of the zone in the URL, so I can $_GET the parameter in my php script. This is the php I run just to test the ajax call.
ajax-addevent.php
<?php
include("classes/event.class.php");
$event = new Event();
$GetZoneName = $_GET['n_beacon'];
$ZoneName = urldecode($GetZoneName);
$arrayDetails = $event->getBeaconEvent($ZoneName);
while($row = mysqli_fetch_array($arrayDetails))
{
$EventTitle = $row["n_title"];
$EventLink = $row["n_link"];
$EventDate = $row["n_date"];
}
$arr = array( "EventTitle" => $EventTitle,
"EventLink" => $EventLink,
"EventDate" => $EventDate );
header("content-type:application/json");
$json_arr = json_encode($arr);
return $json_arr;
?>
My problem is that the ajax call fails and gives me this as result:
What's wrong why my ajax call? Can you help?
EDIT Update Code:
You're trying to get an XML response when the returned datatype is JSON - xhr.responseXML will always be undefined unless the response is valid XML.
Try using xhr.responseText instead. You can use JSON.parse(xhr.responseText) to get a javascript object out of it.
Another good technique is to use the dev tools of your current browser to inspect the network response directly (F12 in Firefox or Chrome, then open the Network tab).

Using Ajax to generate an alert box

I want to pop up an alert box after checking whether some data is stored in the database. If stored, it will alert saved, else not saved.
This is my ajax function:
AjaxRequest.POST(
{
'url':'GroupsHandler.php'
,'onSuccess':function(creategroupajax){ alert('Saved!'); }
,'onError':function(creategroupajax){ alert('not saved');}
}
);
but now it show AjaxRequest is undefined.
How can I fix this?
This of course is possible using Ajax.
Consider the below sample code for the same.
Ajax call :
$.ajax({
url: 'ajax/example.php',
success: function(data) {
if(data == "success")
alert('Data saved.');
}
});
example.php's code
<?php
$bool_is_data_saved = false;
#Database processing logic here i.e
#$bool_is_data_saved is set here in the database processing logic
if($bool_is_data_saved) {
echo "success";
}
exit;
?>
function Ajax(data_location){
var xml;
try {
xml = new XMLHttpRequest();
} catch (err){
try {
xml = new ActiveXObject("Msxml2.XMLHTTP");
} catch (error){
try {
xml = new ActiveXObject("Microsoft.XMLHTTP");
} catch (error1){
//
}
}
}
xml.onreadystatechange = function(){
if(xml.readyState == 4 && xml.status == 200){
alert("data available");
}
}
xml.open("GET", data_location, true);
xml.send(null);
}
window.onload = function(){
Ajax("data_file_location");
}
You can create an addtitional table with date(time) of last update database and check if this date is later. You can use standard setInterval function for it.
This is possible using ajax. Use jQuery.ajax/pos/get to call the php script that saves the data or just checks if the data was saved previously (depends on how you need it exactly) and then use the succes/failure callbacks to handle its response and display an alert if you get the correct response.
Below code based on jQuery.
Try it
$.ajax({
type: 'POST',
url: 'http://kyleschaeffer.com/feed/',
data: { postVar1: 'theValue1', postVar2: 'theValue2' },
beforeSend:function(){
// this is where we append a loading image
$('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
},
success:function(data){
// successful request; do something with the data
$('#ajax-panel').empty();
$(data).find('item').each(function(i){
$('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
});
},
error:function(){
// failed request; give feedback to user
$('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
use the ajax to call the script and check values in the database through the script. If
data present echo success else not.lets look an example of it.
Assuming databasename = db
Assuming tablename = tb
Assuming tableColumn = data
Assuming server = localhost
Ajax:
$.ajax({
url: 'GroupsHandler.php',
success:function(data){
if(data=="saved")
{
alert("success");
}
}
});
Now in the myphpscript.php :
<?php
$Query = "select data from table";
$con = mysql_connect("localhost","user","pwd"); //connect to server
mysql_select_db("db", $con); //select the appropriate database
$data=mysql_query($Query); //process query and retrieve data
mysql_close($con); //close connection
if(!$empty(mysql_fetch_array($data))
{
echo "saved";
}
else
{
echo " not saved ";
}
?>
EDIT:
You must also include jquery file to make this type of ajax request.Include this at the top of your ajax call page.
<script src='ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' type='text/javascript'></script>
First, decide whether to use POST or GET (I recommend POST) to pass AJAX data. Make a php file (ajax.php) such that it echos true or false after checking whether some data is stored in the database. You may test with a variable $your_variable = "some_data_to_check"; having a data inside and once you are finished, you may replace it with $your_variable = $_POST["ajaxdata"];.
Then in your page, set up AJAX using jQuery plugin like:
var your_data_variable = "data_to_send";
$.ajax({
type: "POST",
url: "ajax.php",
data: 'ajaxdata=' + your_data_variable,
success: function(result){
if(result == "true"){
alert("saved");
}else{
alert("not saved");
}
}
You may have a look at jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery.

Using Ajax to generate an alert box after checking whether some data are stored in database [duplicate]

I want to pop up an alert box after checking whether some data is stored in the database. If stored, it will alert saved, else not saved.
This is my ajax function:
AjaxRequest.POST(
{
'url':'GroupsHandler.php'
,'onSuccess':function(creategroupajax){ alert('Saved!'); }
,'onError':function(creategroupajax){ alert('not saved');}
}
);
but now it show AjaxRequest is undefined.
How can I fix this?
This of course is possible using Ajax.
Consider the below sample code for the same.
Ajax call :
$.ajax({
url: 'ajax/example.php',
success: function(data) {
if(data == "success")
alert('Data saved.');
}
});
example.php's code
<?php
$bool_is_data_saved = false;
#Database processing logic here i.e
#$bool_is_data_saved is set here in the database processing logic
if($bool_is_data_saved) {
echo "success";
}
exit;
?>
function Ajax(data_location){
var xml;
try {
xml = new XMLHttpRequest();
} catch (err){
try {
xml = new ActiveXObject("Msxml2.XMLHTTP");
} catch (error){
try {
xml = new ActiveXObject("Microsoft.XMLHTTP");
} catch (error1){
//
}
}
}
xml.onreadystatechange = function(){
if(xml.readyState == 4 && xml.status == 200){
alert("data available");
}
}
xml.open("GET", data_location, true);
xml.send(null);
}
window.onload = function(){
Ajax("data_file_location");
}
You can create an addtitional table with date(time) of last update database and check if this date is later. You can use standard setInterval function for it.
This is possible using ajax. Use jQuery.ajax/pos/get to call the php script that saves the data or just checks if the data was saved previously (depends on how you need it exactly) and then use the succes/failure callbacks to handle its response and display an alert if you get the correct response.
Below code based on jQuery.
Try it
$.ajax({
type: 'POST',
url: 'http://kyleschaeffer.com/feed/',
data: { postVar1: 'theValue1', postVar2: 'theValue2' },
beforeSend:function(){
// this is where we append a loading image
$('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
},
success:function(data){
// successful request; do something with the data
$('#ajax-panel').empty();
$(data).find('item').each(function(i){
$('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
});
},
error:function(){
// failed request; give feedback to user
$('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
use the ajax to call the script and check values in the database through the script. If
data present echo success else not.lets look an example of it.
Assuming databasename = db
Assuming tablename = tb
Assuming tableColumn = data
Assuming server = localhost
Ajax:
$.ajax({
url: 'GroupsHandler.php',
success:function(data){
if(data=="saved")
{
alert("success");
}
}
});
Now in the myphpscript.php :
<?php
$Query = "select data from table";
$con = mysql_connect("localhost","user","pwd"); //connect to server
mysql_select_db("db", $con); //select the appropriate database
$data=mysql_query($Query); //process query and retrieve data
mysql_close($con); //close connection
if(!$empty(mysql_fetch_array($data))
{
echo "saved";
}
else
{
echo " not saved ";
}
?>
EDIT:
You must also include jquery file to make this type of ajax request.Include this at the top of your ajax call page.
<script src='ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' type='text/javascript'></script>
First, decide whether to use POST or GET (I recommend POST) to pass AJAX data. Make a php file (ajax.php) such that it echos true or false after checking whether some data is stored in the database. You may test with a variable $your_variable = "some_data_to_check"; having a data inside and once you are finished, you may replace it with $your_variable = $_POST["ajaxdata"];.
Then in your page, set up AJAX using jQuery plugin like:
var your_data_variable = "data_to_send";
$.ajax({
type: "POST",
url: "ajax.php",
data: 'ajaxdata=' + your_data_variable,
success: function(result){
if(result == "true"){
alert("saved");
}else{
alert("not saved");
}
}
You may have a look at jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery.

Problem to display server side data mysql to phone WebOS!

I am new to WebOS Dev and just started before a week. So, need a little bit help.
From last 2 days I'm stuck in one problem.
I want to display my server side data to client mobile, with the help of palm sample project I am able to display static posted data on client mobile(display every time same posted data values).
But, I want to post value from text box(Display data which is posted via textbox).
if you already installed webos SDK then you can find the sourcecode from here
C:\Program Files\Palm\SDK\share\samplecode\samples\Data\....
just try to run both method AJAX GET and AJAX POST , i want to do some thing like in AJAX GET method(Google ex.)
my modified code is
ajaxPost-assistant.js (i want to add textbox in this code and display data which is posted by this page )
var myassistant = null;
function AjaxPostAssistant()
{
}
AjaxPostAssistant.prototype.setup=function()
{
myassistant = this;
this.textFieldAtt = {
hintText: 'hint',
textFieldName: 'name',
modelProperty: 'original',
multiline: false,
disabledProperty: 'disabled',
focus: true,
modifierState: Mojo.Widget.capsLock,
limitResize: false,
holdToEnable: false,
focusMode: Mojo.Widget.focusSelectMode,
changeOnKeyPress: true,
textReplacement: false,
maxLength: 30,
requiresEnterKey: false
};
this.model = {
'original' : 'Palm',
disabled: false
};
this.controller.setupWidget('sendField', this.textFieldAtt, this.model);
this.buttonModel1 = {
buttonLabel : 'Push to send post',
buttonClass : '',
disable : false
}
this.buttonAtt1 = {
//type : 'Activity'
}
this.controller.setupWidget('post_button',this.buttonAtt1,this.buttonModel1)
Mojo.Event.listen(this.controller.get('post_button'),Mojo.Event.tap,this.handlePost.bind(this));
}
AjaxPostAssistant.prototype.handlePost=function(event)
{
var posturl='http://openxcellca.info/Parthvi/webos/ajaxpost1.php';
var postdata='fname=Ajay';
var myAjax = new Ajax.Request(posturl, {
method: 'post',
evalJSON: 'force',
postBody: postdata,
contentType: 'application/x-www-form-urlencoded',
onComplete: function(transport){
if (transport.status == 200)
myassistant.controller.get('area-to-update').update('Success!');
else {
myassistant.controller.get('area-to-update').update('Failure!');
}
myassistant.controller.get('server-response').update('Server Response: \n' + transport.responseText);
},
onFailure: function(transport){
myassistant.controller.get('area-to-update').update('Failure!\n\n' + transport.responseText);
}
});
}
AjaxPostAssistant.prototype.activate = function(event) {
/* put in event handlers here that should only be in effect when this scene is active. For
example, key handlers that are observing the document */
}
AjaxPostAssistant.prototype.deactivate = function(event) {
/* remove any event handlers you added in activate and do any other cleanup that should happen before
this scene is popped or another scene is pushed on top */
}
AjaxPostAssistant.prototype.cleanup = function(event) {
/* this function should do any cleanup needed before the scene is destroyed as
a result of being popped off the scene stack */
}
ajaxPost-scene.htm
<div x-mojo-element="Button" id="post_button"></div>
<div id="area-to-update"></div>
<br>
<div id="server-response"></div>
ajaxpost1.php
<?php
$con = mysql_connect("localhost","user","pwd");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$qry = "SELECT * FROM user WHERE fname='.$_POST['fname'].'";
$result = mysql_query($qry);
while($row = mysql_fetch_array($result))
{
echo "Name:-".$row['fname'];
echo "<br />";
echo "E-mail:-".$row['email'];
echo "<br />";
echo "Phone:-".$row['phone'];
echo "<br />";
}
mysql_close($con);
?>
Please help me, I want to make one sync app for my college project.
And I need to complete in this 3 weeks.
I'm no WebOS expert, but first make sure that your php server side script is sending JSON. It's much clearer to handle the response: see my question here
Then it should be pretty easy.

How to send jquery $.post with alert

I have a problem with following script. It generates a list of places which are editable, deletable or you can even create a new one.
I want to send a $.post request when creating a new place to a php file which makes an entry into a database (MySQL) and then lists this entryes in html. Now why doesn't even the $.post send an alert message to notifi me that the data is been send?
The script isn't finished yet how you can see, but it would be great if you could give me a hand!
JS-Script
$(function() {
$(".edit").click(function() {
$(this).css("display","none").prevAll(".place_name").css("display","none").prevAll(".inputfield_td").css("display","block").nextAll(".cancel").css("display","block").nextAll(".save").css("display","block").prevAll(".inputfield_td").css("display","block");
});
$(".cancel").click(function() {
$(this).css("display","none").prevAll(".edit").css("display","block").prevAll(".place_name").css("display","block").prevAll(".inputfield_td").css("display","none").nextAll(".save").css("display","none");
});
$(".save").click(function() {
var myvariable1 = $(this).siblings().find("input[type=text]").val();
var myvariable2 = $(this).prevAll("td:last").attr("id");
$(this).css("display","none").prevAll(".cancel").css("display","none").prevAll(".edit").css("display","block").prevAll(".place_name").css("display","block").prevAll(".inputfield_td").css("display","none");
alert("save name: "+myvariable1+" save id: "+myvariable2);
});
$(".delete").click(function() {
var myvariable3 = $(this).prevAll("td:last").attr("id");
alert(myvariable3);
});
$(".new").click(function() {
var myvariable4 = $(this).prevAll("input[type=text]").val();
$.post("place_list.php", {action: "create", name: myvariable4}, function(data){
alert("Data Loaded: " + data);
},"html");
alert(myvariable4);
});
});
PHP-File
<?php
require_once "../../includes/constants.php";
// Connect to the database as necessary
$dbh = mysql_connect(DB_SERVER,DB_USER,DB_PASSWORD)
or die ("Unaable to connnect to MySQL");
$selected = mysql_select_db(DB_NAME,$dbh)
or die("Could not select printerweb");
echo "<table><tbody>";
$result = mysql_query("SELECT * FROM place");
while ($row = mysql_fetch_array($result)) {
echo "<tr><td id=".$row["id"]." class=inputfield_td><input class=inputfield_place type=text value=".$row["name"]." /></td><td class=place_name>".$row["name"]."</td><td class=edit>edit</td><td class=cancel>cancel</td><td class=delete>delete</td><td class=save>SAVE</td></tr> \n";
}
echo "</tbody>";
echo "</table>";
echo "<input type=text class=inputfield_visible />";
echo "<button class=new>New</button>";
?>
Have you got firefox and firebug installed?
If so you can view the net tab and see if the post request gets made to place_list.php and also what the response is. I suspect it is 404'ing as the path maybe incorrect. You can always use the .ajax method rather than .post. This allows you to specify an error method that gets called upon a failed ajax request.
e.g
$.ajax({
url : "place_list.php",
data : {action: "create", name: myvariable4},
cache : false,
error : function(XMLHttpRequest, textStatus, errorThrown){
//console.log or alert error
alert(errorThrown);
},
success: function(html){
alert("Data Loaded: " + data);
}
});

Categories