Phonegap - Send array from mvc controller to Javascript using Ajax - javascript

I'm using phonegap and I'm trying to send an array encoded as json from a controller to view.
In my controller (server side):
$users = Model_Users::find(1);
$a=$users->to_array();
return json_encode($a);
In my view (into smartphone application using phonegap):
$(document).ready(function() {
$.ajax({
url: 'my/url...',
method: 'POST',
data: {
},
success: function(data) {
alert(data);
}
});
});
This working fine, infact in the view I get this alert:
data = {"name":"Jhon","surname":"Larry","age":"25"}
This work because the result of the query is only one row.
Instead when I try to get more than one query result, example:
$users = Model_Users::find('all');
$a=array();
foreach ($users as $user){
array_push($a,$user->to_array());
}
return json_encode($a);
In this case an empty response comes up, in fact I get this alert:
data = []
What is the problem?
Thanks in advance

I will try to build an answer with some tips based on what we already know thanks to the comments.
First of all now we are sure that the JSON is valid (jsonlint.com for example).
So,now, we are completely sure that the problem resides on the PHP / server-side.
My solutions:
Pay attention to not echo/return something before the value you need;
Change return with echo;
Add an exit; statement after the echoed value to be sure that no other characters will be included in the server answer;
Not exactly needed, but you can even think to set the header('Content-Type: application/json');
Debug looking at the console and using console.log instead of alert() (there are a lot of threads explaining the difference
Hope this will help!

Related

Why does my jquery ajax post succeed but the $_POST array is still empty?

This is my first question on here, please bear with me:
My ajax request is:
<script>
$.ajax({
type:"POST",
url:"http://localhost/folder/something.php",
data: { BuildingName:'Jacaranda'},
success: function(data){alert("It worked")},
error: function(data){alert("It failed")},
});
</script>
In my something.php file I have:
$Building= $_POST['BuildingName']; //Error Occurs Here
I get an error on this line stating:
Notice: Undefined index: BuildingName.
When I do VAR_DUMP it returns the $_POST array as empty.
I have checked and rechecked. Looked at different answers here and cannot seem to find the problem. I hope it is not staring me in the face.
I appreciate any help, thank you.
SOLUTION: Instead of simply trying to pass data between pages solely which I do not think is possible(correct me if I'm wrong), there has to be an intermediary. I passed my data into MySQL and had my webpage "listen" to the DB and do something based on the most recent entry.
SOLUTION USING SESSIONS per the advice of Lukas1 (you're right this is more efficient.)
<?php
$_SESSION['Building']= 'something';
$Building= $_SESSION['Building'];
echo "<script> $('#Jacaranda').click(function(){
var id = $(this).attr('id');
$Building= id;
}) </script>";
?>
And my call on the next page is:
<?php echo $Building ?>
Works perfectly without using database as intermediary.
Just change your data attribute to
"BuildingName=Jacaranda"
and it should work all fine.

PHP $_GET and underlines

I have a very short piece of PHP that I use to make HTTP requests from JavaScript.
<?php echo file_get_contents($_GET['url']); ?>
I have used it successfully in a few projects, but am running into a problem with making requests in my current project. Based on my searching, I believe it may be caused by the underscore in the request, though through my searching and not knowing PHP, I have not been able to confirm that.
Below is an example of what I am doing from JavaScript:
$.get("grabber.php?url=" + "http://tidesandcurrents.noaa.gov/api/datagetter?station=8573364&begin_date=20160202&end_date=20160203&product=predictions&units=english&time_zone=gmt&format=json&application=poseidonweathercom+&datum=MLLW", function(forecast) {
console.log(forecast);
});
If I copy the url and put in it in a browser, I get back the JSON that I requested. When I use the code above, I end up getting an error message from NOAA:
Wrong Product : Product cannot be null or empty Wrong Time zone: Time zone cannot be null or empty Wrong Unit:Unit cannot be null or empty Wrong Format: Format cannot be null or empty Wrong Date: The beginDate cannot be null or empty
Do I need to use a regex for the underscore in PHP? Is there some other issue that I do not understand?
Thanks.
You need to send it encoded, which will convert all the underscores/spaces/ampersands etc. with their encoded equivalents:
var url = "http://tidesandcurrents.noaa.gov/api/datagetter?station=8573364&begin_date=20160202&end_date=20160203&product=predictions&units=english&time_zone=gmt&format=json&application=poseidonweathercom+&datum=MLLW";
$.get("grabber.php?url=" + encodeURIComponent(url), function(forecast){
console.log(forecast);
}
Using encodeURIComponent() on that URL shows:
http%3A%2F%2Ftidesandcurrents.noaa.gov%2Fapi%2Fdatagetter%3Fstation%3D8573364%26begin_date%3D20160202%26end_date%3D20160203%26product%3Dpredictions%26units%3Denglish%26time_zone%3Dgmt%26format%3Djson%26application%3Dposeidonweathercom%2B%26datum%3DMLLW
Alternatively, if you just want to access the JSON data and handle it within the JavaScript function, you can retrieve the data via the URL directly, without having to encode the URL:
$.get("http://tidesandcurrents.noaa.gov/api/datagetter?station=8573364&begin_date=20160202&end_date=20160203&product=predictions&units=english&time_zone=gmt&format=json&application=poseidonweathercom+&datum=MLLW", function(forecast) {
console.log(forecast);
});
Um why do you even need your php code ... the code below will work just fine and eliminate your server overhead.
$.get("http://tidesandcurrents.noaa.gov/api/datagetter?station=8573364&begin_date=20160202&end_date=20160203&product=predictions&units=english&time_zone=gmt&format=json&application=poseidonweathercom+&datum=MLLW", function(forecast) {
console.log(forecast);
});

Mysql UPDATE using PHP and AJAX, can't update database

After following several examples from this website I think I'm about to do it but still can't.
I have this code:
HTML
...
Pay
...
AJAX
function update_it(n_id){
$.ajax({
type: 'POST',
url: 'update_yes.php',
data: {idd: n_id},
success: function(output)
{
alert('Updated, server says '+n_id);
}, error: function()
{
alert('Wrong!');
}
});
}
PHP
<?php
$link = mysqli_connect("localhost", "root", "****", "****");
$sql = "DELETE FROM stuff WHERE id = " .$_POST["idd"];
mysqli_query($link,$sql) or die(mysql_error());
?>
And everything works but the PHP (I think). I say this because I can see how the HTML works properly and how the AJAX function return the success message, but still nothing happens in the database.
I tried different structures in the data field of the AJAX function like data: 'idd': n_id, or data: 'idd=' n_id, but nothing seems to work.
What am I doing wrong? Any tip or advice? Thank you in advance.
I am using apache MySQL and php on Winodws. And I has the same issue.
I have in my update-script which was called by AJAX
an UPDATE SQL statement
query it from DB MySQL
try to update the record without changes, (I mean simple updating a
row with the same data)
then... I got nothing to be updated because it is bug in AJAX query which call UPDATE statement in your server-side script. But it will work if you before any saving (updating) data make some changes to it.
I am using REPLACE statement instead of UPDATE.
I looked for this solution a lot of time, really too much. And I can't understand why it happens, because when I debug entire script with own params right on the server and all works fine, but when Ajax then only help REPLACE.
you should add exit; statement at the end of php code. echo some success statement. Then You should alert the output variable in javascript. So that you can make sure that php code is called.
Ok, finally I found a solution.
The code is pretty fine, it is an apache ownerships and rights problem.
This helped a lot.
Thank you guys for all you comments.

Yii redirect from controller action after ajax call not working

I use the following buttons in my view file (don't pay attention to second one, but I just wanted to show you why I'm not using a normal form submit):
<?php echo CHtml::Button('Search Symptom(s)', array('id'=>'search')); ?>
<?php echo CHtml::Button('Add Another Symptom to Search', array('id'=>'addSymptom')); ?>
When the user clicks the buttons this javascript runs (it's inside a document.ready function)
$('#search').click(function()
{
//create new symptom in javascript
var newSymptom =
{
symptomCode: $('#symptomToBeSearchedCode').val(),
dateSymptomFirstSeen: $('#dateSymptomSeen').val(),
symptomTitle: $('#symptomToBeSearchedTitle').val()
};
//pass new symptom into symptomsList array
symptomsList.push(newSymptom);
//make ajax call to server
$.ajax({
type:'POST',
url: '/mysymptomsbook/index.php?r=symptomhistory/search',
data:{symptomsList: symptomsList} ,
dataType:'html'
});
});
symptomsList is an array with JS objects
This is the code in my controller action:
if(isset($_POST['symptomsList']))
{
foreach($_POST['symptomsList'] as $symptom)
{
//populate symptom search model attributes with user id, current date, and form input
$newSymptom = new Symptomhistory;
$newSymptom->setAttributes(array(
'user_id'=>Yii::app()->user->id,
'dateSearched'=>date('Y-m-d'),
'symptomCode'=>$symptom['symptomCode'],
'dateSymptomFirstSeen'=>$symptom['dateSymptomFirstSeen'],
'symptomTitle'=>$symptom['symptomTitle'],
));
//save search history
$newSymptom->save();
//add into the searched for symptoms code the latest code
array_push($symptomCodes, strval($symptom['symptomCode']));
}
$this->redirect(array('disease/index'));
}
I was planning on using redirect to send the $symptomCodes array to the other controlleraction (DiseasesController and actionIndex), but even without passing anything the redirect doesn't work. The models get saved to my database normally.
Anyone have any idea what is wrong? I'm thinking it has to do with Ajax since it's waiting for a response, but I want my controller to redirect instead. Any help as always, is greatly appreciated :)
I had similar problem, recommend you to look at this topic at official forum:
redirect not working when called via Ajax-Request
See the last answer in topic.

return a PHP object to an ajax call

I'm learning PHP OOP, and getting used to all of these objects.
When I create an object in a PHP file called via an $.ajax function, I want to deliver the answer back. But how am I supposed to send back the object to my ajax call ? Before OOP, I was putting everything into an array, then json_encode() the array, and everything worked perfectly. How to adapt this using OOP?
Thanks a lot for your answers
Romain
Example:
On the client side
$.ajax(
{
url:"test.php",
type:"POST",
dataType:"json",
success:function(json)
{
// json into template
}
});
On the server side: test.php
require_once("bdd.php");
function loadClass($class)
{
require $class.".class.php";
}
spl_autoload_register('loadClass');
$PersonneM = new PersonneManager($db);
$perso = $PersonneM->get("123456");
$perso = serialize($perso); // ????????????
header('Content-type: application/json');
echo json_encode(array("result",$perso));
either use serialize or __toString to create a JSON-representation of your data that you can send down the tube. You will not be needing an extra array around your object.
However, there is an error in some JSON parsers/interpreters that can mess with your data when not wrapped in an array. But I haven't heared anything of this issue since a couple of years so you should be safe

Categories

Resources