I have a issue while run my controller in angularjs using Chrome - php

I am battling with this code run on crome then it has been throw the following error.but everything is working fine in firefox
1)Uncaught SyntaxError: Unexpected token }
2)Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.28/$injector/modulerr?p0=lens_admin&p1=Erro…gleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.28%2Fangular.min.js%3A18%3A170)
inside my Controller:
angular.module('lens_admin.controllers', ['angularFileUpload']).
.controller('adminController', function($scope,$http,$location,$upload) {
$scope.brand_edit_submit = function(bid) {
var brand_type_editObj=new Object();
brand_type_editObj.edit_mode='brand';
brand_type_editObj.bid=bid;
brand_type_editObj.brand_type_edit=$scope.brand_type_edit;
$http.post("ajax/frame_list_update.php",{brand_type_editObj}). //first error focus here.am i correct to passing Object to server side..
success(function(data, status, headers, config) {
alert(data);
$scope.brand_type_tables();
$scope.lens_brand_table();
$('.modal').modal('hide');
}).
error(function(data, status, headers, config) {
alert("Please Try Again..!");
});
}
});
i have embedded files for "angularFileUpload" module that included in my "admin.controllers".what is wrong with my code.this issue occured only in crome..any one can give me some ideas..
Thanks Advance..

This is the error line:
$http.post("ajax/frame_list_update.php",{brand_type_editObj})
This is because
{brand_type_editObj}
Isn't a proper object.
It needs to be
{ someName: brand_type_editObj }
Where I have introduced a key someName. JavaScript objects are key/value pairs. So there always needs to be a Key and there always needs to be a Value.
2)Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.28/$injector/modulerr?p0=lens_admin&p1=Erro…gleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.28%2Fangular.min.js%3A18%3A170)
This occured because it probably couldn't find ['angularFileUpload']. But with out seeing the main script its hard to know for sure

Here is the correct code
Few errors like double "." b/w module and controller
second:- Key is not assigned to object in $http call.
angular.module('lens_admin.controllers', ['angularFileUpload'])
.controller('adminController', function($scope, $http, $location, $upload) {
$scope.brand_edit_submit = function(bid) {
var brand_type_editObj = new Object();
brand_type_editObj.edit_mode = 'brand';
brand_type_editObj.bid = bid;
brand_type_editObj.brand_type_edit = $scope.brand_type_edit;
$http.post("ajax/frame_list_update.php",{"data":brand_type_editObj}).
success(function(data, status, headers, config) {
alert(data);
$scope.brand_type_tables();
$scope.lens_brand_table();
$('.modal').modal('hide');
}).
error(function(data, status, headers, config) {
alert("Please Try Again..!");
});
}
});

Related

AngularJS to php to json working inconsistently

I used AngularJS to make an app for grading students. It works perfectly 90% of the time, but every now and then, it doesn't record the data. The grade given or other change made will be reflected in the DOM, but disappears when the page is refreshed.
I use an angular service to send data to a PHP file which sends it to a JSON file.
The service is set up like this:
app.factory('studentList', function($http) {
var studentService = {};
studentService.getInfo = function() {
var promise = $http.get('../data/studentList.json').then(function(response) {
return response.data;
});
return promise;
};
studentService.sendData = function(data) {
$http.post('../data/studentData.php', data)
.success(function (data, status, headers, config) {
console.log(status);
})
.error(function (data, status, headers, config) {
console.log(status);
});
};
return studentService;
});
When I give a grade or change student info, I call the sendData() function defined in the service. This sends it to the PHP file which looks like this:
<?php
$data = file_get_contents("php://input");
$file = "studentList.json";
file_put_contents($file, $data);
?>
I've used this PHP code before, and it seems to work fine in everything else I've done. Any insights?
Thank you.

$_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/.

jQuery param() chokes on object with functions in it

In the .error() of a ajax call, I'm getting an object back, with functions, inside it. It looks like it's the ajax() object itself...
abort(),always(),complete(), etc etc.
if I do
var qstring = jQuery.param(data);
I get syntax error and everything crashes.
I tried:
var qstring = jQuery.param(jQuery.makeArray( data ))
and i just get 'undefined'
What I am trying to do is send the result of the error, along with the original arguments that I ajax'd, to my error.php:
here is my ajax call:
$.ajax(ajaxargs).done(function (data) {
//success, do things with data
}).error(function (data) {
console.log(data);//this is an object with functions
$.fn.crMap.ajaxFail(data, 'mycall', ajaxargs);
});
and my failure function:
$.fn.crMap.ajaxFail = function (data, call, ajaxargs) {
var out = {
call: call,
ajaxFail: 'complete',
ajaxargs: ajaxargs
returned: data
}
document.location = '/error.php?'+ jQuery.param(out) ;
};
which works, if I dont try to pass in the data. Any attempt to .param(data) causes syntax error, or actually, a TypeError: a is undefined, deep in jquery.js

CodeIgniter + jQuery Ajax runs successfully but error callback is called

I have a pretty simple CodeIgniter project that does some simple database work. Currently I have a controller method that deletes an item in the database. In my view, the code uses the jQuery ajax object to reference that controller, then displays either success or failure through its callbacks.
The problem is, although the controller works fine (deletes the item in the DB as expected), the ajax "error" callback is being called, instead of "success".
I'm sure I'm missing something super basic here...
Here is my controller method:
public function delete_note()
{
$this->load->helper('url');
$this->load->model('auth/user', 'User');
$this->load->database();
$note_id = $this->input->post('id');
$this->db->delete('admin_notes', array('id' => $note_id));
$this->db->query();
$this->output->set_status_header('200'); // Attempting to force the issue
}
And here is the code within the view:
$('.delete_note').each(function(){
var current = this;
this.onclick = function(event)
{
var note_id = this.title;
$.ajax({
type: "POST",
url: "/admin/delete_note",
data: { id: note_id },
success: function(data) { alert('I never see this!');},
error: function () { alert('I *always* see this!');}
});
}
});
Any answer attempts are appreciated. Any correct answers are doubly appreciated ;)
Thanks!
Just because the database logic is working, you may be receiving issues related to something else (cross-browser perhaps?). To see the error, change your error function to be like this:
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
alert(errorThrown);
}
I'd like to thank WojtekT for reminding me to check my responses in Firebug. I was actually receiving back a 500 status code for PHP errors. My extraneous $this->db->query(); call needed to be removed.
Everything works great now.
Thanks!

jQuery Ajax request returns error and status 0

I use this pseudo-class to make Ajax request to server:
function RequestManager(url, params, success, error){
//Save this Ajax configuration
this._ajaxCall = null;
this._url= url;
this._type = params.type;
this._success = function(){
alert("ok");
};
this._error = function(){
alert("ko");
};
}
RequestManager.prototype = {
require : function(text){
var self = this;
this._ajaxCall = $.ajax({
url: this._url,
type: this._type,
data: text,
success: function(xmlResponse){
var responseArray = [];
var response = _extractElements(xmlResponse, arrayResponse);
self._success(response);
},
error: self._error,
complete : function(xhr, statusText){
alert(xhr.status);
return null;
}
});
}
This is PHP that will be loaded:
<?php
header('Content-type: text/xml');
//Do something
$done = true;
$response = buildXML($done);
$xmlString = $response->saveXML();
echo $xmlString;
function buildXML ($done){
$response = new SimpleXMLElement("<response></response>");
if($done){
$response->addChild('outcome','ok');
}
else {
$response->addChild('outcome', 'ko');
}
return $response;
}
When I instantiate a new object, and I use it to load a request, it always return to me error, and status code is 0. The server correctly generates an XML document. Why I can't get a correct 200 code back?
If this happens on your second call to require, it's because the call to abort() results in your callback being called with a status code of 0. You should later get the correct result for the second request.
In jQuery 1.4 there's also a bug where your success callback is called after an aborted request. See my answer to Request periodically coming back empty under race conditions.
Unrelated to this issue, there are variables in your code (timer and ajaxCall) that seem to be referenced both with and without a leading underscore.

Categories