Ajax response from Zend frameword - php

Recently, I've been trying to create an online CRM using jquery/php/xml-rpc and I've had an issue that I just can't seem to find the solution to.
I currently have an ajax request sending an element id to a php document that when opened on its own (as a direct url to the document) returns a response from the API server (either a Boolean or some error like 'wrong data').
However this doesn't come out to my page at all and I am not sure the data I am sending is even getting through to the php document.
This is my jquery code:
$('#SomeElement').on('click', function(){
var id = $('#ELEMENTID').attr('value');
$.ajax ({
type:'POST',
url: 'PHPfile.php',
dataType: 'json',
data: {id:id},
success: function(data) {
if(data.indexOf('YES') === -1){
$('.alert-success').show();
$('.alert-success').html(data);
/*setTimeout(function() {
$('.alert-success').fadeOut('slow');
location.reload();
}, 2000);*/
} else {
$('.alert-danger').show();
$('.alert-danger').html(data);
/*setTimeout(function() {
$('.alert-danger').fadeOut('slow');
location.reload();
}, 2000);*/
}
}
});
});
And this is my PHP code:
require 'init_autoloader.php';
Zend\Mvc\Application::init(require 'config/application.config.php')->run();
$q = mysqli_query($conn, "SELECT * FROM some db WHERE somekey = '$_POST[id]'");
$main = mysqli_fetch_assoc($q);
if($main['someentry'] !== '0') {
echo 'This is FALSE';
} else {
$r = mysqli_query($conn, "SELECT * FROM side_db WHERE side_id = '$_POST[id]'");
$p = mysqli_query($conn, "SELECT * FROM ext_db WHERE ext_id = '$_POST[id]'");
$m = mysqli_query($conn, "SELECT * FROM img_db WHERE img_id = '$_POST[id]'");
$side = mysqli_fetch_assoc($r);
$ext = mysqli_fetch_assoc($p);
if((int)$ext['gt'] === '0' || (int)$ext['gt'] === '1') {
$g = 'yes';
} else {
$g = 'no';
}
foreach($ext as $key => $value) {
if($key === 'somestring') {
continue;
}else if($value === '0' || $value === '1') {
$ext[$key] = 'no';
} else if($value === '2'){
$ext[$key] = 'yes';
}
}
foreach($main as $k => $v) {
if($v === '0' || $v === '1') {
$main[$k] = 'no';
} else if($v === '2'){
$main[$k] = 'yes';
}
}
require 'init_autoloader.php';
Zend\Mvc\Application::init(require 'config/application.config.php')->run();
$appkey = 'appkey';
$someid = id;
$something = 'something';
$else = 'else';
$divarray = Array
(
'HEAL' = Array(
[0] = "WARLOCK",
[1] = "PRIEST",
[2] = "ROGUE",
[3] = "WARRIOR",
[4] = "MAGE"
),
"someENTRY" = 'YES'
);
$oxClient = new \Zend\XmlRpc\Client('http://link-to-server.php');
$somenewrequest = $oxClient->call('class.OfAPI',array($appkey,$someid,$something,$else,$divarray));
$res = $oxClient->getLastResponse();
echo $res;
$client = new \Zend\XmlRpc\Client('http://link-to-server.php');
if($m !== FALSE) {
$j = 1;
while($img = mysqli_fetch_assoc($m)) {
$pather = str_replace('../',"",$img['img_path']);
$url = str_replace('www.', "", $_SERVER['HTTP_HOST']);
$imagedata = file_get_contents('OUR/FILE/PATH/OF/SERVER'.$url.'/'.$pather);
$base64 = base64_encode($imagedata);
$SOMEID = $res;
$image = $base64;
$client->call('CLASS.IMAGESOMETHING',array($appkey,$usr,$psw,$res,$image));
$j++;
}
}
$fin = mysqli_query($conn, "UPDATE our_db SET avalue = '1' WHERE somefield = '$_POST[id]'");
echo 'You succeeded in doing w/e';
}
Excluding all the small errors I might have done due to having to rewrite half of the code to protect sensitive information, I want to know what I can change so that I can see the responses pop up on the page where the ajax is run.
I tried JSON.encode on the $res but that didn't seem to solve anything. Is there something I am missing or something I can do differently to get the responses I need or even see if the ajax variable is getting through to the php document.
Either way I would be happy to know what I am doing wrong so I can improve and not have to run into the problem in the future.
Thanks in advance!

In your $.(ajax) please put id in quotes to make sure it is interpreted as field name:
data: {'id':id},
Use developer-tools of google chrome to inspect your POST-request going to the server. Here a very good intro:
https://blog.versionone.com/spy-on-browser-http-requests/

Related

Reload or Refresh Page after comment successfully submitted in Ajax

I am trying to reload the page after the comment is successfully submitted
Comment submitted through Ajax
After this line
// Save the comment
$state = $comment->store();
If i am trying to use location.reload(); as
// Save the comment
$state = $comment->store();
location.reload();
then its not working and comment not even submitting
Below is complete code
Can any one help - how to refresh and load page when comment is successfully submitted and stored in backend
<?php
defined('_JEXEC') or die('Unauthorized Access');
require_once(JPATH_COMPONENT . '/views/views.php');
class EasyBlogViewComments extends EasyBlogView
{
/**
* Processes comment saving
*
* #since 4.0
* #access public
* #param string
* #return
*/
public function save()
{
// Check for request forgeries
EB::checkToken();
// Test if user is really allowed to post comments
if (!$this->acl->get('allow_comment')) {
return $ajax->reject(JText::_('COM_EASYBLOG_NO_PERMISSION_TO_POST_COMMENT'));
}
// Default values
$moderated = false;
$parentId = $this->input->get('parentId', 0, 'int');
$depth = $this->input->get('depth', 0, 'int');
$subscribe = $this->input->get('subscribe', false, 'bool');
$email = $this->input->get('email', '', 'email');
$message = $this->input->get('comment', '', 'default');
$name = $this->input->get('name', '', 'default');
$username = $this->input->get('username', '', 'default');
$password = $this->input->get('password', '', 'default');
$title = $this->input->get('title', '', 'default');
$terms = $this->input->get('terms', false, 'bool');
$blogId = $this->input->get('blogId', 0, 'int');
$isCB = $this->input->get('iscb', 0, 'int');
// If there is no name, and the current user is logged in, use their name instead
if (!$name && $this->my->id) {
$user = EB::user($this->my->id);
$name = $user->getName();
}
// Validate the email
$data = array('post_id' => $blogId, 'comment' => $message, 'title' => $title, 'email' => $email, 'name' => $name, 'username' => $username, 'terms' => $terms);
// Load up comment table
$comment = EB::table('Comment');
$state = $comment->validatePost($data);
if (!$state) {
return $this->ajax->reject($comment->getError());
}
// Bind the data on the comment table now
$comment->bindPost($data);
// Check for spams
if ($comment->isSpam()) {
return $this->ajax->reject(JText::_('COM_EASYBLOG_SPAM_DETECTED_IN_COMMENT'));
}
$captchaResponse = EB::captcha()->verify();
// Perform captcha verification
if (isset($captchaResponse->success) && $captchaResponse->success == false) {
return $this->ajax->reject($captchaResponse->errorCodes);
}
// Get current date
$date = EB::date();
// Set other attributes for the comment
$comment->created = $date->toSql();
$comment->modified = $date->toSql();
$comment->published = true;
$comment->parent_id = $parentId;
$comment->created_by = $this->my->id;
// Process user registrations via comment
$register = $this->input->get('register', '', 'bool');
if ($register && $this->my->guest) {
if (empty($password) || empty($username) || empty($email)) {
return $this->ajax->reject('COM_EASYBLOG_COMMENT_REGISTRATION_FIELD_EMPTY');
}
$userModel = EB::model('Users');
$id = $userModel->createUser($username, $email, $name, $password);
if (!is_numeric($id)) {
return $this->ajax->reject($id);
}
$comment->created_by = $id;
}
$totalComments = $this->input->get('totalComment', 0, 'int');
// Determines if comment moderation is enabled
if ($this->config->get('comment_moderatecomment') == 1 || ($this->my->guest && $this->config->get('comment_moderateguestcomment'))) {
$comment->published = EBLOG_COMMENT_STATUS_MODERATED;
}
// Load up the blog table
$blog = EB::table('Blog');
$blog->load($comment->post_id);
// If moderation for author is disabled, ensure that the comment is also published automatically.
if ((!$this->config->get('comment_moderateauthorcomment') && $blog->created_by == $this->my->id) || EB::isSiteAdmin()) {
$comment->published = true;
}
// Update the ordering of the comment before storing
$comment->updateOrdering();
// Save the comment
$state = $comment->store();
if (!$state) {
return $this->ajax->reject($comment->getError());
}
$resultMessage = JText::_('COM_EASYBLOG_COMMENTS_POSTED_SUCCESS');
$resultState = 'success';
// If user registered as well, display a proper message
if ($register) {
$resultMessage = JText::_('COM_EASYBLOG_COMMENTS_SUCCESS_AND_REGISTERED');
}
if ($comment->isModerated()) {
$resultMessage = JText::_('COM_EASYBLOG_COMMENT_POSTED_UNDER_MODERATION');
$resultState = 'info';
}
// Process comment subscription
if ($subscribe && $this->config->get('main_subscription') && $blog->subscription) {
$subscribeModel = EB::model('Subscription');
$subscribeModel->subscribe('blog', $blog->id, $email, $name, $this->my->id);
}
// Process comment notifications
$comment->processEmails($comment->isModerated(), $blog);
// Set the comment depth
$comment->depth = $this->input->get('depth', 0, 'int');
// Update the sent flag
$comment->updateSent();
// Format the comments
$result = EB::comment()->format(array($comment));
$comment = $result[0];
$language = JFactory::getLanguage();
$rtl = $language->isRTL();
$theme = EB::template();
$theme->set('comment', $comment);
$theme->set('rtl', $rtl);
$output = '';
if ($isCB) {
// if the is saving from CB plugin, then we need to display the output using different template.
$output = $theme->output('site/comments/cb.item');
} else {
$output = $theme->output('site/comments/default.item');
}
return $this->ajax->resolve($output, $resultMessage, $resultState);
}
public function reloadCaptcha()
{
$ajax = EB::ajax();
// Get the previous captcha id.
$id = $this->input->get('previousId', 0, 'int');
$captcha = EB::table('Captcha');
$state = $captcha->load($id);
if ($state) {
$captcha->delete();
}
// Generate a new captcha
$captcha = EB::table('Captcha');
$captcha->created = EB::date()->toSql();
$captcha->store();
$image = EB::_('index.php?option=com_easyblog&task=captcha.generate&tmpl=component&no_html=1&id=' . $captcha->id, false);
return $ajax->resolve($image, $captcha->id);
}
2nd File
EasyBlog.module('comments/form', function($) {
var module = this;
EasyBlog.require()
.script('comments/captcha', 'comments/list')
.library('markitup')
.done(function($) {
EasyBlog.Controller('Comments.Form', {
defaultOptions: {
"{formWrapper}": "[data-comment-form-wrapper]",
"{form}": "[data-comment-form]",
"{title}": "[data-comment-title]",
"{name}": "[data-comment-name]",
"{username}": "[data-comment-username]",
"{password}": "[data-comment-password]",
"{email}": "[data-comment-email]",
"{register}": "[data-comment-register]",
"{website}": "[data-comment-website]",
"{counter}": "[data-comment-counter]",
"{subscribe}" : "[data-comment-subscribe]",
"{terms}": "[data-comment-terms]",
"{tncLink}": "[data-comment-tnc]",
"{parentId}" : "[data-comment-parent-id]",
"{commentDepth}": "[data-comment-depth]",
"{blogId}" : "[data-comment-blog-id]",
"{depth}": "[data-comment-depth]",
"{notice}": "[data-comment-notice]",
"{editor}": "[data-comment-editor]",
"{submit}": "[data-comment-submit]",
"{formToken}": "[data-comment-token]",
"{recaptcha}": "[data-recaptcha-item]"
}
}, function(self, opts, base) {
return {
init: function() {
self.initEditor();
self.list = self.addPlugin('list');
// If recaptcha is enabled, we should skip the normal captcha
var recaptcha = self.recaptcha.inside(self.element).length;
if (recaptcha < 1) {
self.captcha = self.addPlugin('captcha');
}
},
initEditor: function() {
if (self.editor().data('comment-bbcode') == 1) {
self.editor().markItUp(window.EasyBlogBBCodeSettings);
}
},
setNotice: function(message, type) {
var className = '';
if (type == 'error') {
className = 'alert-danger';
}
if (type == 'success') {
className = 'alert-success';
}
if (type == 'info') {
className = 'alert-info';
}
self.notice()
.removeClass('hide')
.addClass('alert ' + className)
.html(message);
},
resetForm: function() {
// If the comment form has a parent id, we need to reposition the comment form back.
var parentId = self.parentId().val();
if (parentId != 0) {
self.form().appendTo(self.formWrapper());
}
// Reset the form
self.username().val('');
self.password().val('');
self.subscribe().attr('checked', false);
self.editor().val('');
self.website().val('');
self.name().val('');
self.depth().val(0);
self.parentId().val(0);
self.trigger('resetForm');
// Determine if recaptcha is available
var recaptcha = self.recaptcha.inside(self.element);
// Get recaptcha's response
if (recaptcha.length > 0) {
grecaptcha.reset();
}
},
resetNotice: function() {
self.notice()
.removeClass('info error')
.html('');
},
"{self} replyComment": function(el, event, commentItem, commentId, commentDepth) {
// Hide notices in the reply form
self.notice().addClass('hide');
// When user tries to reply to an existing comment, move the form next to the level of the comment item
commentItem.after(self.form());
self.depth().val(commentDepth);
// Set the new parent id to the comment's id
self.parentId().val(commentId);
},
"{self} cancelReply": function(el, event, commentItem, commentId) {
// Set the parent id to 0
self.parentId().val(0);
// Reset the comment depth back to 0
self.depth().val(0);
// Relocate the form back to it's origin
self.formWrapper().html(self.form());
},
"{self} commentAdded": function()
{
// Increment the counter
var count = self.counter().html();
count = parseInt(count) + 1;
self.counter().html(count.toString());
self.resetForm();
},
getValues: function() {
var data = {
title: self.title().val(),
name: self.name().val(),
email: self.email().val(),
username: self.username().val(),
password: self.password().val(),
website: self.website().val(),
subscribe: self.subscribe().is(':checked') ? 1 : 0,
register: self.register().is(':checked') ? 1 : 0,
comment: self.editor().val(),
terms: self.terms().is(':checked') ? 1 : 0,
depth: self.depth().val(),
parentId: self.parentId().val(),
blogId: self.blogId().val()
};
// token
// data[self.formToken().attr('name')] = 1;
// Determine if recaptcha is available
var recaptcha = self.recaptcha.inside(self.element);
// Get recaptcha's response
if (recaptcha.length > 0) {
data.recaptcha = grecaptcha.getResponse();
}
self.trigger('submitComment', [data]);
return data;
},
"{tncLink} click": function() {
EasyBlog.dialog({
content: EasyBlog.ajax('site/views/comments/terms')
})
},
"{submit} click" : function(el, event) {
event.preventDefault();
// Reset notices
self.resetNotice();
// Add loading indicator on the button
$(el).attr('disabled', true);
var tmp = $(el).html();
$(el).html('<i class="fa fa-repeat fa-spin"></i>');
// Get the form values
var data = self.getValues();
// Perform an ajax call to submit the comment
EasyBlog.ajax('site/views/comments/save', data)
.done(function(output, message, state) {
self.setNotice(message, state);
self.trigger('commentAdded',[output, data]);
})
.fail(function(message) {
self.setNotice(message, 'error');
})
.always(function(){
$(el).removeAttr('disabled');
$(el).html(tmp);
self.trigger('reloadCaptcha');
});
return false;
}
}
});
module.resolve();
});
});
I would hazard a guess that the place to add the location.reload() would be within this snippet:
"{self} commentAdded": function()
{
// Increment the counter
var count = self.counter().html();
count = parseInt(count) + 1;
self.counter().html(count.toString());
self.resetForm();
},
So perhaps like:
"{self} commentAdded": function()
{
// Increment the counter
var count = self.counter().html();
count = parseInt(count) + 1;
self.counter().html(count.toString());
self.resetForm();
/* reload */
location.reload();
},
Or, you could add it to the .done method within EasyBlog.ajax .... pretty much the same thing I think by looking at the code though

long polling ajax is not keeping realtime updates

i was doing long polling , but it can see in my network chrome my long polling in status pending that means is waiting for new data and changes the database , but when I try to insert one item to my database then , but when I try to insert one value show keep that long polling in real time i cant see real time updatings .. how can I fix it?
pusher controller codeigiter
public function pusher() {
header('Content-Type: application/json');
$user_id = $this->session->log['id'];
set_time_limit(0);
while (true) {
$firstCall = false;
if (isset($_GET['timestamp'])) {
$last_ajax_call = $_GET['timestamp'];
} else {
$last_ajax_call = time();
$firstCall = true;
}
clearstatcache();
$notificationsCount = $this->notification->checkForNotifications($last_ajax_call, $user_id);
$newData = (int) $notificationsCount > 0 ? true : false;
$notifications = [];
if ($newData) {
$dataSet = $this->notification->getNotifications($user_id, $last_ajax_call);
foreach($dataSet as $data) {
$notifications[] = $data;
$finalNotificationTime = $data['timestamp'];
}
$result = array('notifications' => $notifications, 'timestamp' => $finalNotificationTime);
$json = json_encode($result);
echo $json;
break;
} else {
if ($firstCall) {
$dataSet = $this->notification->getUnreadNotifications($user_id);
foreach($dataSet as $data) {
$notifications[] = $data;
}
$result = array('notifications' => $notifications, 'timestamp' => $last_ajax_call);
$json = json_encode($result);
echo $json;
break;
}
sleep(1);
session_write_close();
continue;
}
}
exit();
}
ajax
function check_notifications(timestamp) {
var queryString = {
'timestamp': timestamp
};
$.ajax({
type: 'GET',
url: URL_GET_NOTIFICATION,
data: queryString,
success: function (data) {
// put result data into "obj"
for (var i in data.notifications) {
notify(data.notifications[i].message, data.notifications[i].type, data.notifications[i].timestamp);
}
check_notifications(data.timestamp);
}
});
}
check_notifications();

php file reading displaying unwanted content

I am working on some code and i have scraped together the following some from stackoverflow and some from my old code. Any way, I am trying to just have the file parsed and processed without actually displaying its content untell a later stage.
There is the PHP:
$c = 0;
if($fp = fopen($newname,"r"))
{
while (($line = fgets($fp)) !== false)
{
//CHECK STRING TO SEE IF IT CONTAINS AN EMAIL
$checkResult = $this->checkCSVContentForEmail($line,$c);//$content
if(!empty($checkResult))
{
if($checkResult == TRUE && is_bool($checkResult) == true)
{
$this->contactsAddedCounter += 1;
}
elseif(is_string($checkResult))
{
$errLine .= '
<p> CheckResult: '.$checkResult.' Line number: '.$c.' does not have an email</p>';
array_push($this->LogError_contactsUpload, $errLine);
}
}
else
{
$errLine = "<p>Line number: ".$c." contain's an empty string</p><br>\n";
array_push($this->LogError_contactsUpload, $errLine);
}
$c++;
}
}
fclose($fp);
I have spend the whole day yesterday coding through all the involved code - functions and all but nothing should be doing any displaying but i still get the follwing displayed,
The unwanted output:
Array ( [0] => " [1] => [2] => [3] => [4] => Normal"" [5] => ""False"" [6] => [7] => [8] => ""Normal""";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; )
of-course this is displayed repeatedly for each line read.
Any help on what may be causing this?
The rest of the code involved in processing:
//Check line for Email Method
public function checkCSVContentForEmail($csvLine, $lineNum)
{
if(!empty($csvLine))
{
$partedCSV = explode(',',$csvLine);
if(!empty($partedCSV[57]))
{
$csvEmail = $partedCSV[57];
if(!empty($csvEmail))
{
if($Result = $this->checkEmail($csvEmail, $lineNum))
{
//convert csv line into sql statement
$csv2sqlInsertMultiLine = '(';
$csvTosql = '';
foreach($partedCSV as $csvContent)
{
$str = strip_tags($csvContent);
$letters = array('"', "'");
$Quotes = array('', ' ');
$strN = str_replace($letters, $Quotes, $str);
$letters = array('(', ")");
$Quotes = array('', '');
$c2s_str = str_replace($letters, $Quotes, $strN);
$csvTosql[] .= $c2s_str;
}
//(4,5,6);
$theSQL = implode(',',$csvTosql);
$csv2sqlInsertMultiLine .= $theSQL;
$csv2sqlInsertMultiLine .= '),';
array_push($this->csv2sqlInsertMultiLine, $csv2sqlInsertMultiLine);
return $Result;
}
}
}
else
{
$show = 'No Entry for Email address field - WILL NOT BE ADDED TO DATABASE! '.print_r($partedCSV);
return $show;
}
}
else
{
$show = 'This line is empty';
return $show;
}
}
//Validate Email Method
public function checkEmail($email, $row)
{
if(!empty($email))
{
$str = strip_tags($email);
$letters = array('"', "'");
$Quotes = array('', ' ');
$em = str_replace($letters, $Quotes, $str);
if(!empty($em) or $em !=' ')
{
$check = preg_match('/^\S+#[\w\d.-]{2,}\.[\w]{2,6}$/iU', $em) ? TRUE : FALSE;
if($check == TRUE)
{
$this->contactEmail[$row] = $em;//array_push();
return TRUE;
}
}
else
{
$msg = 'There is no email passed in: '.$em.' <br>Our check resulted in: '.$check;
return $msg;
}
}
else
{
$msg = 'There is no email passed in: '.$email.' <br>Our check resulted in: '.$check;
return $msg;
}
}
The JQuery
// Upload Contacts
function uploadContacts()
{
var obj = '#upImprtFile';
var file_data = $k('#ContactsImprt').prop('files')[0];
var form_data = new FormData();
form_data.append("action", "uploadContacts");
form_data.append("upImprtFile", "submit");
form_data.append("ContactsImprt", file_data);
$k.ajax({
url: 'inc/runUtilities.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data)
{
$k('#doUpload').html(data).fadeIn('slow');
}
});
}
See the following lines inside checkCSVContentForEmail method.
else
{
$show = 'No Entry for Email address field - WILL NOT BE ADDED TO DATABASE! '.print_r($partedCSV);
return $show;
}
Use of print_r must be causing the output.

How to use eager loading here, i mean just by using one variable instead of two. So i don't need to run two separate queries

1) How can use eager loading here, i mean just by using $SponceringUser instead of $ProfileUser. so i don't need to run two separate queries.
if i exchange my $profileUser variable with $SponceringUser where in the code i should save it to get the right output
here is the Post_edit method for more details please refer gist here : https://gist.github.com/gupta2205/b33dcf762876e5df34d9
public function post_edit($id = null)
{
if ($id)
{
$Petition = Petition::find($id);
if (!$Petition)
{
//oh noes! invalid petition specified!
Alert::error("That petition no longer exists");
return Redirect::action('AdminPetitionsController#index');
}
}
else
{
$Petition = new Petition;
}
$PetitionCreationForm = new AdminPetitionCreationForm;
$errors = array();
if ($PetitionCreationForm->passes())
{
$Petition->call_to_action = Input::get('call_to_action');
if (empty($Petition->id))
{
$Petition->slug = Str::slug($Petition->call_to_action);
}
$Petition->recipient = Input::get('recipient');
if (Input::get('feature_type') == '1')
{
$Petition->featured_sort_order = Input::get('featured_sort_order') + 1;
$Petition->flag_featured = 1;
}
else if(Input::get('feature_type') == '0')
{
$Petition->featured_sort_order=null;
$Petition->flag_featured = 0;
}
//$selected_position = Input::get('dropdown_menu_list');
$Petition->description_md = Input::get('description_md');
$Petition->description = Petition::parseMD($Petition->description_md);
$Petition->letter_md = Input::get('letter_md');
$Petition->letter = Petition::parseMD($Petition->letter_md);
$Petition->target_signatures = Input::get('target_signatures', 50000);
$Petition->flag_published = Input::get('flag_published');
$Petition->media_type = Input::get('media_type', null);
if (Input::get('media_type') == 'img' && Input::hasFile('petition_image'))
{
$Petition->media_url = Petition::uploadFile(Input::file('petition_image'));
}
else if (Input::get('media_type') == 'youtube' && Input::get('media_url_youtube'))
{
$Petition->media_url = Input::get('media_url_youtube');
}
// how to fix this part .... gurrrrrrrrrrrr=======================
$ProfileUser= $Petition->User;
if (Input::get('profile_type') == 'image' && Input::hasFile('profile_image'))
{
$ProfileUser->profile_img_url = Petition::uploadFile(Input::file('profile_image'));
}
else if (Input::get('profile_type') == 'url' && Input::get('profile_url'))
{
$ProfileUser->profile_img_url = Input::get('profile_url');
}
//$Petition->sponsor_user_id = $SponsoringUser->id;
$ProfileUser->save();
//====================================================
try {
try {
$SponsoringUser = User::where('email', Input::get('user.email'))->firstOrFail();
}
catch (Exception $e)
{
$PetitionSponsorForm = new AdminPetitionSponsorForm(Input::get('user'));
if ($PetitionSponsorForm->passes())
{
$SponsoringUser = new User;
$SponsoringUser->email = Input::get('user.email');
$SponsoringUser->first_name = Input::get('user.first_name');
$SponsoringUser->last_name = Input::get('user.last_name');
$SponsoringUser->populateLocation(Input::get('user.zip'));
$SponsoringUser->save();
}
else
{
throw new Exception();
}
}
$Petition->save();
1) How can use eager loading here, i mean just by using $SponceringUser instead of $ProfileUser. so i don't need to run two separate queries.
i got it :)
if (Input::get('profile_type') == 'image' && Input::hasFile('profile_image'))
{
$SponsoringUser->profile_img_url = Petition::uploadFile(Input::file('profile_image'));
}
else if (Input::get('profile_type') == 'url' && Input::get('profile_url'))
{
$$SponsoringUser->profile_img_url = Input::get('profile_url');
}
$SponsoringUser->save();

Execution of mySQL query in jQuery.Post method

I have created a javascript file that contains js to trigger an event onchange of a drop down list. The JS is below:
// /public/js/custom.js
jQuery(function($) {
$("#parent").change(function(event){
event.preventDefault();
var parentID = $('#parent').val();
var id = $('#id').val();
$.post("/menu/GetMenuChildren", {pID: parentID, thisID: id },
function(data){
if(data.response === true){
var $el = $("#Position");
$el.empty(); // remove old options
$.each(data.newOptions, function(key, value) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
} else {
// print error message
alert("something went wrong in Post");
}
}, 'json');
alert("After Post");
});
});
In my Controller.php I have an function GetMenuChildrenAction as shown below:
public function GetMenuChildrenAction()
{
$request = $this->getRequest();
$response = $this->getResponse();
if ($request->isPost())
{
$post_data = $request->getPost();
$parent_id = $post_data['pID'];
$id = $post_data['thisID'];
//$this->form->get('Position')->SetOptionValues(
$newOptions = $this->getMenuTable()->GetPositionsByID($parent_id, $id);
if(isset($newOptions))
{
$response->setContent(\Zend\Json\Json::encode(array('response' => true, 'newOptions' => $newOptions)));
}
else
{
$response->setContent(\Zend\Json\Json::encode(array('response' => false)));
}
}
return $response;
}
In the MenuTable.php there is a Method GetPositionsByID as shown below:
public function GetPositionsByID($parentID, $id)
{
if($parentID == 0)
{
$menu = $this->getMenu($this->id);
$parentID = $menu->parent_id;
}
if(isset($parentID))
{
$sql = "Select ID,Label from Menu Where parent_ID = " . $parentID . " and id > 1 and id <> " . $id . " Order by Position,Label";
try
{
$statement = $this->adapter->query($sql);
}
catch(Exception $e) {
console.log('Caught exception: ', $e->getMessage(), "\n");
}
$res = $statement->execute();
$rows = array();
$i = 0;
foreach ($res as $row) {
$i = $i + 1;
$rows[$i] = array (
$i => $row['Label']
);
}
return $rows;
}
return array();
}
It all seems to be hooked up correctly, when I debug the code, I get the this line:
$statement = $this->adapter->query($sql);
and then nothing happens. If I replace all the code in the GetPositionsByID method, and simply return an array like the following:
return array('1' => 'one', '2' => 'two');
it works great, however i want to get the data from the DB. Does anyone know why the execute would fail on this line?
$statement = $this->adapter->query($sql);
Thanks in advance
The issue was that the adapter was null.

Categories