I am building a thread-messaging system. I used AJAX to send the parent_id to the php file which retrieved the thread (many messages with the same parent_id)
in the ajax, I send the parent_id
data:{
parent_id: $(this).data('id'),
ajax: 'true'
},
I use this parent_id in the php file using a query which retrieves some rows and I pass them back using this :
$ret_msg_query_result=mysql_query($retrive_query);
while ($retrieved_msg_fetched=mysql_fetch_assoc($ret_msg_query_result))
{
echo json_encode($retrieved_msg_fetched) . "\n";
}
and then back to Ajax:
$(document).ready(function() {
$(".msgsRow li.msg_subject,.msgsRow li.msg_content").click(function() {
$.ajax({
type: 'POST',
url: AJAX_URL+"front/RetrieveMsg.php",
data:{ parent_id: $(this).data('id'), ajax: 'true' },
success: function(data) {
var strLines = data.split("\n");
for (var i in strLines) {
var obj = JSON.parse(strLines[i]);
console.log(obj.id);
}
}
});
});
});
I got this way (of splitting) to convert each row into an object from a post here on Stackoverflow Sending/Parsing multiple JSON objects
The function works right retrieving the ids of messages and even retrieving the full row. But I get
"Uncaught SyntaxError: Unexpected end of input "
and it points to the line before console.log(obj.id);
I searched StackOverflow for this error and it usually appears for missing a closing parenthesis but I can'd find any.
Thanks,
You are missing a } on in this function
success: function(data){
var strLines = data.split("\n");
for (var i in strLines) {
var obj = JSON.parse(strLines[i]);
console.log(obj.id);
**}**
}
NOTE: remove the 4x*, those should not be there :)
That should fix it!
I figured out the problem ... It's because I am splitting using "/n" which makes the strLines be something like {row},{row},{row},
The comma in the end causes the unexpected end. So, I used a counter to check the number of row, if it's the last, then don't insert "/n"
$counter=1;
while ($retrieved_msg_fetched=mysql_fetch_assoc($ret_msg_query_result))
{
if ($counter==mysql_num_rows($ret_msg_query_result))
{
echo json_encode($retrieved_msg_fetched);
}
else{
echo json_encode($retrieved_msg_fetched) . "\n";
$counter++;
}
}
Thanks Limelights for your help too :)
I got this when I forgot to return something from my php-script when it worked fine. I just added something like this:
die (json_encode (array ('reponse'=>'Your script worked fine')));
at the end of my php-script, and that solved it. You can also use 'response' to check it it worked fine.
Related
This is the first time I am working with CI+AJAX+JSON.
I have a controller Admin.php inside controllers directory of Codeigniter. The controller code is as under:
public function getmylist()
{
$users_arr[] = array("sno" => "1", "myname" => "hello");
echo json_encode($users_arr);
}
Then, in views, I have a view with the following code:
<select class="form-control" name="mod_countries" id="mod_countries">
<?php
if(isset($countrylist))
foreach($countrylist as $c)
echo "<option value=" . $c->cname . ">".$c->cname;
?>
</select>
Then my target select which i need to populate from ajax is
<select class="form-control" name="mod_newlist" id="mod_newlist">
</select>
My ajax is as under:
$(document).ready(function() {
$('#mod_countries').change(function(event) {
var cname = $("select#mod_countries").val();
alert(cname);
$.ajax({
type: "post",
url: "<?php echo base_url(); ?>" + "Admin/getmylist",
dataType: "json",
data: {mcname: cname},
success: function(res){
if(res) {
var len=res.length;
$("#mod_newlist").empty();
for(var i=0; i<len; i++)
{
var sno=res[i]['sno'];
var myname=res[i]['myname'];
$("#mod_newlist").append("<option value='" + sno + "'>"+myname+"</option>");
}
}
else
{
console.log('hitting');
}
},
error: function(res, status, error) {
var err = res.responseText;
alert(res.Message);
alert(status);
alert(error);
}
});
});
});
When I select an item from the first dropdown list, I get the selected item. Now I expect the second drop downlist to get an item from the controller's code. but, my code goes into error block and alert shows following error messages for each alert line of code:
undefined
parsererror
SyntaxError: Unexpected token I in JSON at position 0
Please tell me where I am making a mistake?
Also, please help with regards to how should I return the sno->name pair from model because at lat, i want to populate the new select from database.
Remove debug/garbage data from response, like I am called. If still not work then parse JSON in success as following
var res = $.parseJOSN(res);
if(res) {
.....
You are not passing data correctly.
it should be like
data:{
"key" : value
//use " " to encapsulate string values, only in case of variable You pass value without ""
}
I am using CodeIgniter for last two months now. And earlier I had a lot of trouble working with ajax. But my friend suggested me to use AngularJs. It took me just one day to learn Angular and it turned out to be extremely helpful.
It will save a lot of time. And make your work so easy. At first, it may sound difficult but if u spend some time coding then it is going to make your life a lot better. I learned it from JavaTpoint.com and it was very well explained.
Do not try to understand everything at once and practice as you learn.
To begin with I am building a complete CRM running Ajax and there is a lot to this, so please be patient and read the whole thing.
I have an ajax script returning several json arrays. When I display the return value from my php script I get this:
[{"packages":{"id":"1","name":"Land Line"}},{"packages":{"id":"2","name":"Cellular w\/Alarm.com"}},{"packages":{"id":"3","name":"Home Automation"}}]
What I am trying to do is separate the arrays so I can make a select drop down from it. Before anyone says anything, yes I know how to do that my itself, but I am needing the form this script is populating to be a select dropdown or a complete filled in form based off of the id going into another script. It is a bit confusing, so don't ding me for it please.
Here is the PHP script alliance_form.php:
$equip = "SELECT * FROM packages WHERE brand='$brand'";
if($db->query($equip) === false) {
trigger_error('Wrong SQL: ' . $query . ' Error: ' . $db->error, E_USER_ERROR);
} else {
$result = $db->query($equip);
$array = array();
foreach($result as $r) {
$array[] = array(
"packages" => array(
"id" => $r['id'],
"name" => $r['name']
)
);
}
echo json_encode($array);
}
Here is the jquery going to the PHP form and coming back to input the information:
$.ajax({
type: "POST",
url: "/crm/alliance_form.php",
data: dataString,
success: function(msg)
{
$("#package-form").html(msg);
$.each(msg.packages, function(i, object) {
$.each(object, function(index, value) {
alert(value);
});
});
},
error: function(error)
{
$(".error").html(error);
}
});
This is part of an ordering system of a CRM, so this script is checking the database for existing orders under the id. If the id is there then it is supposed to come back with the order information and I populate the form. If not it will give a select dropdown to select a package which then populates an empty form. That is the gist of what I am on right now.
Here is the question: Why can't I get a response from JQuery on the each() loop on this. One return comes back with a regular array, and this one is a nested array.
I'm not quite clear on what you're asking, but here are my thoughts on this:
You've got .packages in the wrong place. Instead of this:
$.each(msg.packages, function(i, object) {
$.each(object, function(index, value) {
...
You should have written this:
$.each(msg, function(i, object) {
$.each(object.packages, function(index, value) {
...
Better yet, you could just get rid of packages altogether. It's an unnecessary level in the JSON structure.
Also, I don't think jQuery knows that the response is JSON. For this to work, you need either dataType: 'json' in the list of arguments to $.ajax, or something on the server to set the MIME type appropriately.
I'm also concerned about $("#package-form").html(msg);, because msg is not an HTML string.
You should try something like this (Example)
msg = $.parseJSON(msg); // parse JS to object
$.each(msg, function(i, object) {
$.each(object.packages, function(index, value) {
console.log(value);
});
});
Instead of $.each(msg.packages, function(i, object){...}) because msg is an array of objects and in your given example there are three objects right now and each object has a packages item (nested object) which contains id and name.
Update : You can also use, just one loop (Example)
msg = $.parseJSON(msg); // parse JS to object
$.each(msg, function(i, object) {
console.log(object.packages.id);
console.log(object.packages.name);
});
Sorry guys, I threw out my back and couldn't get to my code from home.
Anyways I tried both solutions you provided, and I have been looking at this for a while but neither worked. I have this updated to:
$("#brand").click(function () {
var brand = $(this).attr('rel');
$("#order-form").empty();
var contact_id = $("#contact_id").val();
var dataString = "contact_id=" + contact_id +"&brand=" + brand + "";
//alert("test");
$.ajax({
type: "POST",
url: "/crm/alliance_form.php",
data: dataString,
//dataType: "json",
success: function(msg)
{
//$("#package-form").html(msg);
$.each(msg, function(i, object) {
if(msg.packages) {
$("#package-form").append("<select>");
$.each(object.packages, function(index, value) {
$("#package-form").append('<option value="'+value+'">'+index+'</option>');
});
$("#package-form").append('</select>');
}
});
},
error: function(error)
{
$(".error").html(error);
}
});
});
This just returns nothing not even a blank select box. The $("#package-form").html(msg); is just so I can see the output how the php script is sending it back. The if statement is just to run a verification to see if the array has a nested array with packages in it. I need the return function to do a certain action if it does. Very Important!
As for the dataType: 'json', line in the ajax, it doesn't give me a return value if I have that placed in it. But when I remove it, it will display the array.
Nothing has been changed in the PHP file besides moving the query like suggested.
Ok guys. I got the answer! I have it like this:
$("#brand").click(function () {
$("#order-form").empty();
$("#package-form").empty();
var msg = '[{"packages":{"1":"Land Line"}},{"packages":{"2":"Cellular w\/Alarm.com"}},{"packages":{"3":"Home Automation"}}]';
var newData = JSON.parse(msg);
var newSelect = "<select>";
$.each(newData, function(i, ob) {
$.each(ob.packages, function(index, value) {
newSelect += '<option value="'+index+'">'+value+'</option>';
});
});
newSelect += "</select>";
$("#package-form").append(""+newSelect+"");
});
Here is the fiddle: http://jsfiddle.net/M78vE/
So this stems from a problem yesterday that quickly spiraled out of control as the errors were unusual. This problem still exists but the question was put on hold, here, and I was asked to reform a new question that now relates to the current problem. So here we go.
The problem is basic in nature. If you were helping yesterday I have switched from a $.post to an $.ajax post to deliver a variable to my PHP file. However my PHP file seems to never receive this variable stating that the index is 'undefined'.
Now this would normally mean that the variable holds no value, is named incorrectly, or was sent incorrectly. Well after a full day of messing with this (kill me) I still see no reason my PHP file should not be receiving this data. As I'm fairly new to this I'm really hoping someone can spot an obvious error or reccommend another possible solution.
Here's the code
jQuery
$('#projects').click(function (e) {
alert(aid);
$.ajax({
url:'core/functions/projects.php',
type: 'post',
data: {'aid' : aid},
done: function(data) {
// this is for testing
}
}).fail (function() {
alert('error');
}).always(function(data) {
alert(data);
$('#home_div').hide();
$('#pcd').fadeIn(1000);
$('#project_table').html(data);
});
});
PHP
<?php
include "$_SERVER[DOCUMENT_ROOT]/TrakFlex/core/init.php";
if(isset($_POST['aid'])) {
$aid = $_POST['aid'];
try {
$query_projectInfo = $db->prepare("
SELECT projects.account_id,
projects.project_name,
projects.pm,
//..irrelevant code
FROM projects
WHERE account_id = ?
");
$query_projectInfo->bindValue(1, $aid, PDO::PARAM_STR);
$query_projectInfo->execute();
$count = $query_projectInfo->rowCount();
if ($count > 0) {
echo "<table class='contentTable'>";
echo "<th class='content_th'>" . "Job #" . "</th>";
echo "<th class='content_th'>" . "Project Name" . "</th>";
//..irrelevant code
while ($row = $query_projectInfo->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>";
echo "<td class='content_td'>" . "<a href='#'>" . $row['account_id'] . "</a>" . "</td>";
echo "<td class='content_td'>" . $row['project_name'] . "</td>";
//..irrelevant code
echo "</tr>";
}
echo "</table>";
}
} catch(PDOException $e) {
die($e->getMessage());
}
} else {
echo 'could not load projects table';
}
?>
When I run this code by pressing '#projects' I get 2 alerts. This first alert says '6', which is the value of the variable 'aid' and is expected. The second alert is blank.
Now here is where I get confused. If the post is being sent with a value of 6. Isn't the $_POST['aid'] set? Also if that's true shouldn't my code execute the if portion of my conditional statement rather than my else?. Either way this strikes me as odd. Shouldn't I receive something back from my PHP file?
So in Firebug we trust, right? If I open up Firebug and go through like this
Firebug -> POST projects.php -> XHR -> POST(tab) ->
I see 6 in the 'Parameter' window and '6' in the 'Source' window. Then if I click the 'Response' and 'HTML' tabs they both hold no value.
So anyways, that wall of text is my problem. Again, I'm really hoping someone can help me out here. I would hate to waste anymore time on what should be a simple solution.
EDIT
If I change my php file to look like this
<?php
if(isset($_POST['aid'])) {
$aid = $_POST['aid'];
echo $aid;
} else {
echo 'fail';
}
The response is now '6'! Hooray! We made a breakthrough! Now why won't it load my table that results from my query?
side note
This should of been noted originally if I take away the
if(isset($_POST['aid'])){
//all my code
} else {
//response
}
and just hard code the variable $aid like this
$aid = '6';
Then run the PHP file directly the query is successful and the page loads the table its dynamically creating.
Also in response to one of the answers asking me to use
$('#projects').click(function (e) {
alert(aid);
$.ajax({
url:'core/functions/projects.php',
type: 'post',
data: aid,
success: function(data) {
// this is for testing
}
}).error (function() {
alert('error');
}).complete (function(data) {
alert(data);
$('#home_div').hide();
$('#pcd').fadeIn(1000);
$('#project_table').html(data);
});
});
I was using that, but I'm using jQuery v1.10.2 and according to this those methods are or will be deprecated. Either way it made 0 difference in the outcome.
Anyways the question is now. Why is it if I used the simple version I get echo'd back my $aid variable of '6'. However when I try and run my query with it I get nothing. Also please try to remember if I hard code the 6, the table creates.
I think this may be the error:
data: aid,
it should be
data: {'aid':aid},
That will provide the $_POST['aid'] label and value you're looking for in your php page.
EDIT:
If you're having trouble with this, I'd simplify it for testing, the main reasons for things like this not working in my experience are:
it's not reaching the file
it's reaching the file but the file's expecting something different than it's receiving and due to control structures it's not returning anything
it's reaching the file with the correct data, but there are other errors in the php file that are preventing it from ever returning it.
You can easily rule out each of these in your case.
The jQuery data parameter to the ajax method should be an object, such as {'aid': aid}. I think that's your problem. I also noticed your always method is missing a parameter for data.
If you're now posting the data correctly could the problem be in your PHP page?
The init.php include couldn't be changing the value of $_POST['aid'] could it?
I'm not sure done is suppose to behave like that, normally you use done like this:
$.ajax({
//...
})
.done(function(data){
//...
});
Just do it like this:
var fetch = true;
var url = 'someurl.php';
$.ajax(
{
// Post the variable fetch to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'aid' : aid
},
success : function(data)
{
// This happens AFTER the backend has returned an JSON array (or other object type)
var res1, res2;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
res1 = data[i].res1;
res2 = data[i].res2;
// Do something with the returned data
}
},
complete : function(data)
{
// do something, not critical.
}
});
You can add the failure part in if you want. This is, anyway, guaranteed to work. I'm just not familiar enough with done to make more comments about it.
Try
include "{$_SERVER['DOCUMENT_ROOT']}/TrakFlex/core/init.php";
instead cause $_SERVER[DOCUMENT_ROOT] witout bracket won't work. When you are using an array in a string, you need those brackets.
Since some browsers caches the ajax requests, it doesn't responds as expected. So explicitly disabling the cache for the particular ajax request helped to make it work. Refer below:
$.ajax({
type: 'POST',
data: {'data': postValue},
cache: false,
url: 'postAjaxHandling.php'
}).done(function(response){
});
Here is what I have in PHP:
$arrayresults = array();
while($popularbrushesrow = mysql_fetch_array($popularBrushes)){
$arrayresults[] = '<img class="slideImg" alt="'.$popularbrushesrow['bd_brushname'].'" title="'. $popularbrushesrow['bd_brushname'].'" src="'.$popularbrushesrow['bd_imagefilepath'].'" />';
}
echo json_encode($arrayresults);
Now, jquery:
$.ajax({
type:'GET',
url:'getDataForSlide.php',
data:"limit="+limit+"&required="+required,
dataType:"json",
cache:true,
success: function(result){
var arrayFromPHP = JSON.parse(result);
alert(arrayFromPHP);
}
})
Could someone please help me out. Whats the correct way to form an array in JSON?
The problem is likely to be this line:
var arrayFromPHP = JSON.parse(result);
Because you've specified dataType: 'json' in the ajax options, jQuery has already done the parsing for you. So doing it a second time starts out by doing toString on the array, which does a join, which results in invalid JSON.
Simply use result directly.
For example, suppose you have this JSON:
[
"Stack Overflow",
"Google"
]
Because jQuery has already done JSON.parse on it, result is an actual array. So if you then pass it into JSON.parse, the first thing that does is toString, which gives you this:
Stack Overflow,Google
...which is not, of course, valid JSON.
I would simplify your jquery....like this...
$.getJSON("getDataForSlide.php", { limit: limit, required: required}, function(json) {
console.log(json);
});
I like to use
jQuery.parseJSON(response);
And don't forget to use die(); or exit(); on php side after you echo your results, since it's a ajax call. This information can be found here: http://codex.wordpress.org/AJAX_in_Plugins
Hey everyone. This one is puzzling me. I'm using PHP and Jquery. I am making an ajax request to a PHP file containing a get url. Eg. Path/to/file/?ID=369
The request goes out fine, I've watched it in fire bug.
However in the PHP file, the ID variable doesn't exist. When I do
var_dump($_GET)
I can see that there are two arrays inside the GET array. These are JSON and action.
Can anyone explain to me what's going on here and how I can receive my ID variable?
here are my codes:
<?php
$program_price_id = $_GET['id'];
$programDepatures = getProgramDepaturesGreaterThanToday($program_price_id);
echo "[{optionValue: 0, optionDisplay: 'Select a date'}";
while ($programDepartureData = mysql_fetch_array($programDepatures)) {
echo ", {optionValue: ".
$programDepartureData['id'].", optionDisplay: '".
tidyDateEnglish($programDepartureData['departure_date'])."'}";
}
echo "]";
?>
Best wishes,
Mike
i think you need to specify the ajax method you are using.It might be a $.ajax, $.get or $.getJson.
but i use $.ajax and here is a snippet
$.ajax({
url:"event/service_ajax_handler.php",
type: "GET",
data: {action:"getTime"},
dataType : "json",
success: function(data) {
$("#cmbTimeRange").html("<option value='-1'>Please select time range</option>");
$.each(data, function(){
$("#cmbTimeRange").append("<option value='"+ this.id +"'>" + this.hours +"</option>")
});
},
error: function(){
alert("error");
}
});
pay attention to the data parameter. see also
getJSON
This may be obvious, but I noticed in the sample URL you have ID capitalized, but in your PHP code you have it lowercase. PHP is case sensitive, so it could be as simple as that.