Zend 2: problems with Ajax - javascript

I created a small function to test Zend-Ajax interaction.
In my view I set following code
<script type="text/javascript">
var urlform = '<?php echo $this->url('inbox/default', array('controller'=>'messages', 'action'=>'addmessage')); ?>';
</script>
<div onclick="ajaxtest();">Click</div>
Then, I created following function within file custom.js, already associated to the layout
function ajaxtest() {
$.post(urlform, null, function(data) {
if (data.success) {
alert('Ok');
} else {
alert('Failed');
}
}, 'json');
}
And finally, this is the code of my addMessageAction
public function addMessageAction()
{
$request = $this->getRequest();
$response = $this->getResponse();
$response->setContent(\Zend\Json\Json::encode(array('success'=>1)));
return $response;
}
When I click on the div associated to the javascript function, nothing happens, no alert is displayed.
Where am I wrong? Does it depend on particular zend settings?

I solved the problem by ridefining function in the following way:
var ajaxpost = $.post(urlform2).fail(function() {
alert("Failed");
})
ajaxpost.done(function(data) {
var parsed = jQuery.parseJSON(data);
if (parsed.success == 1) {
alert('Ok');
}
});

Related

jQuery().append is working but .html is not working on ajax call

I'm using WordPress. After getting response I'm using jQuery().append(response) .Its working fine. Problem is that it is generating multiple div .That's why I need to use html or innerHtml .But it is not working. Though I'm getting response back from server.
function get_chat_history() {
//var doc = document.getElementById("show-chat-div-text");
document.getElementById("show-chat-div-text").lastElementChild;
var id_of_incoming_chat_user=document.getElementById("show-chat-div-[![enter image description here][1]][1]text").lastElementChild;
var id_incoming_chat_user;
if (id_of_incoming_chat_user!=null) {
id_incoming_chat_user= id_of_incoming_chat_user.getAttribute('class');
}
else (id_of_incoming_chat_user===null)
{
id_incoming_chat_user=document.getElementById("show-chat-div-text").getElementsByTagName("Div")[0].getAttribute('class');
}
if(id_incoming_chat_user==="user-hide")
{
id_incoming_chat_user=document.getElementById("show-chat-div-text").getElementsByTagName("Div")[1].getAttribute('class');
}
cur_user = '<?php echo get_current_user_id() ;?>';
var message = document.getElementById("myInput").value;
var listitem="";
var postdata = {action: "navid_history_ajax_call",
param_user_to_chat: id_incoming_chat_user,
param_main_user:cur_user,
message:message
};
jQuery.post(ajaxurl, postdata, function (response) {
//jQuery("#show-chat-div-text").html=response;//not working
// jQuery("#show-chat-div-text").append(response);//Working
console.log(response);
chatBox.scrollTop = chatBox.scrollHeight;
});
}
setInterval(get_chat_history, 5000);
You should wrap the response within brackets.
Ex:
jQuery("#show-chat-div-text").html(response);

Ajax not getting only json output data (it print whole loaded view code.).? codeigntier

Here is my little script code I want to get data from codeingiter controller. I get json data from controller to view ajax, but It print with html page code.
any one can help me here, How can I solve this.
I only want to get json data ans a variable data to my page.
this is output that I am getting but this is comming with html code and I don't want html code.
[{"id":"1","p_name":"t_t11","p_type":"t_t1","paid_type":"0"},{"id":"2","p_name":"t_t12","p_type":"t_t1","paid_type":"1"},{"id":"3","p_name":"t_t1","p_type":"t_t1","paid_type":"0"}]
I have follow some question answers but can't et success, because that question's answers not related to me.
Link 1
Link 2 and many more...
<script>
$("a.tablinks").on('click',function(e){
e.preventDefault();
var p_name = $(this).attr('value');
alert(p_name);
$.ajax({
url:"<?php echo base_url(); ?>teq/gettabdata",
dataType:'text',
type: "POST",
data:{p_name : p_name},
success : function(data){
alert(data);
if(data !=""){
var obj = JSON.parse(data);
alert(obj.id);
/*$.each(obj, function(key,val){
console.log(key);
console.log(val); //depending on your data, you might call val.url or whatever you may have
});*/
}else{
alert(data+ '1');
}
},
error : function(data){
//var da = JSON.parse(data);
alert(data+ '2');
//alert(da+ '2 da ');
}
});
});
</script>
Here is controller code.
public function gettabdata(){
$p_name = $this->input->post('p_name');
//echo $p_name." this is paper name.!";
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
//$p_name = $data;
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
echo json_encode($query['res']);
$this->load->view('teq', $tabs_data);
}
You added view at the end of your function that return view's code.
Remove line:
$this->load->view('teq', $tabs_data);
You can either use
if ($this->input->is_ajax_request()) {
echo json_encode($data_set);
}else{
//Procced with your load view
}
Or if you're avoiding ajax request check then please pass any extra paramter from your ajax call then then check for its existence at your controller and on behalf of it proceed your conditional statement . it will solve your problem
Change your controller method like this:
public function gettabdata(){
$p_name = $this->input->post('p_name');
//echo $p_name." this is paper name.!";
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
//$p_name = $data;
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
// if ajax request
if ($this->input->is_ajax_request()) {
echo json_encode($query['res']);
return; // exit function
}
$this->load->view('teq', $tabs_data);
}
In your ajax code chage dataType: to json
$.ajax({
url:"<?php echo base_url(); ?>teq/gettabdata",
dataType:'json',
type: "POST",
data:{p_name : p_name},
success : function(res)
{
if(res !=""){
alert(res.id);
}else{
alert(res+ '1');
}
}
});
And in your controller
public function gettabdata()
{
if($this->input->post('p_name'))
{
$p_name = $this->input->post('p_name');
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
if($query['res'])
{
$resp = $query['res'];
}
else
{
$resp = array('status' => FALSE,'msg' => 'Failed');
}
echo json_encode($resp);
}
else
{
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
$this->load->view('teq', $tabs_data);
}
}
Hope this helps :)

jQuery AJAX with PHP to upload contents to MYSQL DB

I am looking for a jQuery AJAX script alongside a PHP script that allows for the storage of information on a button click. The function defined within the jQuery should take three variables, all of which are defined pre-method call. I have the basis of operation complete but at the end of all operations - after the button is clicked and some time has passed - no data is added to the appropriate mysql database.
Here is my jQuery function "store"
<script type="text/javascript">
function store(ud, ld, tp) {
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: 'ud='+ud+'&ld='+ld+'&tp='+tp
success : function() {
alert("WORKED!");
},
error : function() {
alert("DIDN'T WORK!");
},
complete : function() {
}
});
}
</script>
Here is the store.php file (very basic I know, I have also yet to secure this script via sanitizing user input)
<?php
require ('../mysqli_connect.php');
$errors = 0;
if(isset($_POST['ud']) && is_numeric($_POST['ud'])) {
$ud = $_POST['ud'];
} else {
++$errors;
}
if(isset($_POST['ld']) && is_numeric($_POST['ld'])) {
$ld = $_POST['ld'];
} else {
++$errors;
}
if(isset($_POST['tp'])) {
$tp = strip_tags(stripslashes($_POST['tp']));
} else {
++$errors;
}
if($errors == 0) {
$q = "INSERT INTO table_name (column_1, column_2, column_3, column_4) VALUES ('$ld', '$ud', NOW(), '$tp')";
mysqli_query($mysqli, $q);
} else {
echo 'There was a problem!';
}
?>
Assume that I have onclick="store(3, 3, A)" as an attribute for a certain element. How can I fix this? If I remove the onclick attribute how do I pass the necessary parameters to the jQuery function? I appreciate any and all help!
<-- EDIT -->
New jQuery & AJAX Script ...
<script type="text/javascript">
function store(ud, ld, tp) {
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: 'ud='+ud+'&ld='+ld+'&tp='+tp,
error : function() {
alert("error");
},
success : function(data) {
alert(data);
},
complete : function() {
alert("complete");
}
});
}
$(function () {
$("a.rec").on("click", function () {
var $this = $(this),
ud = $this.data("ud"),
ld = $this.data("ld"),
tp = $this.data("tp");
store(ud, ld, tp);
});
});
</script>
Revised PHP
<?php
if($_SERVER['REQUEST_METHOD'] === "POST"){
require ('../mysqli_connect.php');
$errors = 0;
if(isset($_POST['ud'])) {
$ud = $_POST['ud'];
} else {
++$errors;
}
if(isset($_POST['ld'])) {
$ld = $_POST['ld'];
} else {
++$errors;
}
if(isset($_POST['tp'])) {
$tp = $_POST['tp'];
} else {
++$errors;
}
if($errors == 0) {
$q = "INSERT INTO table_name (column_1, column_2, column_3, column_4) VALUES ('$ld', '$ud', NOW(), '$tp')";
mysqli_query($mysqli, $q);
} else {
echo 'There was a problem!';
}
} else {
$url = 'http://www.exampledomain.com/error.php';
ob_end_clean();
header("Location: $url");
exit();
}
?>
Now for my HTML
<li>
<div class="sample classes">
<a class="rec" data-ud="13" data-ld="10" data-tp="SCI">
<input type="submit" title="Something" value="Something" />
</a>
</div>
</li>
However, when this button is clicked, it still does not do anything!
As you said onclick is something you are going to want to avoid. This is how you do it.
$(function () { //This function will be ran when the page loads
$(".button-class").on("click", function () { //This will run when any button is clicked
var $this = $(this),
ud = $this.data("ud"),
ld = $this.data("ld"),
tp = $this.data("tp");
store(ud, ld, tp);
});
});
HTML
<input type="button" class="button-class" data-ud="3" data-ld="3" data-tp="A"/>
I find it easier to use JSON and pass variables in an object to the server:
<script>
(function(){
var store = function (ud, lrid, type) {
var data = {
ud:ud,
lrid:lrid,
type:type
};
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: data,
success : function(data) {
alert(data);
},
error : function() {
alert("DIDN'T WORK!");
},
complete : function() {
}
});
};
$('#btn').on('click', function(){
store(1,2,3);
});
}());
</script>
Use this script to test you are getting the variables on the server side:
<?php
# Put this in http://www.exampledomain.com/folder/store.php to test it works
if($_SERVER['REQUEST_METHOD'] === "POST"){
if(
isset($_POST['ud']) &&
isset($_POST['lrid']) &&
isset($_POST['type'])
)
{
$var = $_POST['ud'] . ", ".$_POST['ud'] . ", ".$_POST['type'] ." passed successfully via ajax!";
echo json_encode($var);
}
}
?>

json array not being posted to PHP using Javascript post method

In the view:
function updateData(that){
f = new test();
for (var i = 0; i < dataContext.length; i++)
{
f.test.push(new Person(dataContext[i].test, dataContext[i].test1, dataContext[i].Line1, dataContext[i].Id));
}
$.post("<?php echo $base_url;?>index.php/controller/function/<?php echo $details['Id'];?>", { data: JSON.stringify(f) }, function (res) {
});
}
Now within the php function, function:
function () {
print_r($_POST);
}
returns an empty array.
The data is basically within a javascript wizard. It seems like when I click "finish", the page does not refresh itself. $_POST is only called when the page first loads.
I am quite new to javascript and not sure what I am doing wrong, cheers.
Try JSON.stringify(that) in place of JSON.stringify(f) like,
function updateData(that){
var url="<?php echo $base_url;?>index.php/controller/function/<?php echo $details['Id'];?>";
$.post(url, { data: JSON.stringify(that) },function (res) {
alert(res);
});
}
Updated if f is defined then try it like,
function updateData(that){
var url="<?php echo $base_url;?>index.php/controller/function/<?php echo $details['Id'];?>";
$.post(url, { data: JSON.stringify(f) },function (res) {
alert(res);
});
}
Give some name to your php function or call form jquery like,
// call updateData function in your controller
var url="<?php echo $base_url;?>index.php/controller/updateData/<?php echo $details['Id'];?>";
Create a function updateData in your controller like,
function updateData($id=''){
print_r($_POST);
}

Page Refresh Only After Page Is Validated

Hi I wonder whether someone may be able to help me please.
I've put together this page which has working 'client' and 'server' side validation.
What I'm now trying to do is add a page refresh and 'scroll to top', once the page has passed validation.
To the script used in the first link I've added the following code to try and invoke this functionality:
setTimeout(function() {
$('body').fadeOut(400, function() {
location.reload();
setTimeout(function() {
$('body').fadeIn(400);
}, 500);
window.scrollTo(x - coord, y - coord);
});
}, 2000);
The problem I'm having, is that irrespective of whether the the form passes validation, the page refreshes as can be seen in this page. So the full JavaScript code looks like this:
Post Update - Through working with #rahul, I've now have a working solution as below. NB I only needed to change the JavaScript code
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#addlocation").validationEngine();
$("#addlocation").bind("jqv.field.result", function(event, field, errorFound, prompText){ console.log(errorFound) })
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#addlocation').submit(function(){
//check the form is not currently submitting
if($(this).data('formstatus') !== 'submitting'){
//setup variables
var form = $(this),
formData = form.serialize(),
formUrl = form.attr('action'),
formMethod = form.attr('method'),
responseMsg = $('#saverecordresponse');
//add status data to form
form.data('formstatus','submitting');
//show response message - waiting
responseMsg.hide()
.addClass('response-waiting')
.text('Please Wait...')
.fadeIn(200);
//send data to server for validation
$.ajax({
url: formUrl,
type: formMethod,
data: formData,
success:function(data){
//setup variables
var responseData = jQuery.parseJSON(data),
klass = '';
//response conditional
switch(responseData.status){
case 'error':
klass = 'response-error';
break;
case 'success':
klass = 'response-success';
break;
}
//show reponse message
responseMsg.fadeOut(200,function(){
$(this).removeClass('response-waiting')
.addClass(klass)
.text(responseData.message)
.fadeIn(200,function(){
//set timeout to hide response message
setTimeout(function(){
responseMsg.fadeOut(200,function(){
$(this).removeClass(klass);
form.data('formstatus','idle');
});
},3000)
if (klass=='response-success')
{
setTimeout(function () {
$('body').fadeOut(400, function () {
location.reload();
setTimeout(function () {
$('body').fadeIn(400);
}, 500);
window.scrollTo(x - coord, y - coord);
});
}, 2000);
}
});
});
}
});
}
//prevent form from submitting
return false;
});
});
</script>
and this is a cut down version (I've deleted most of the validation rules for preview purposes) the PHP code which works in conjunction with the JavaScript and saves the record to a MySQL database.
<?php
//sanitize data
$userid = mysql_real_escape_string($_POST['userid']);
$locationname = mysql_real_escape_string($_POST['locationname']);
$returnedaddress = mysql_real_escape_string($_POST['returnedaddress']);
if(empty($locationname)){
$status = "error";
$message = "You need to enter a name for this location!";
}
else{
$query = mysql_query("INSERT INTO `table` (userid, locationname, returnedaddress) VALUES ('$userid', '$locationname', '$returnedaddress')");
if($query){ //if insert is successful
$status = "success";
$message = "Location Saved!";
}
else { //if insert fails
$status = "error";
$message = "I'm sorry, there has been a technical error!";
}
}
//return json response
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
exit;
?>
I must admit, I'm not sure where the problem lies, but I'm the first to admit I'm a little new to JavaScript and jQuery.
I just wondered whether someone may be able to look at this please and let me know where I'm going wrong, or even perhaps suggest a better alternative to make the page refresh once the form passes validation.
you can easily get it done using return false
check if validation not passed return false
if(Yourvalidation!=true)
{
return false;
}
after this section
//response conditional
switch(responseData.status){
case 'error':
klass = 'response-error';
break;
case 'success':
klass = 'response-success';
break;
}
check value of klass like this
responseMsg.fadeOut(200, function () {
$(this).removeClass('response-waiting')
.addClass(klass)
.text(responseData.message)
.fadeIn(200, function () {
//set timeout to hide response message
setTimeout(function () {
responseMsg.fadeOut(200, function () {
$(this).removeClass(klass);
form.data('formstatus', 'idle');
});
}, 3000)
if (klass=='response-success')
{
setTimeout(function () {
$('body').fadeOut(400, function () {
location.reload();
setTimeout(function () {
$('body').fadeIn(400);
}, 500);
window.scrollTo(x - coord, y - coord);
});
}, 2000);
}
else
{
return false; //use return false in else condition
}
});
});
You can check the client and server side validation by using this
if(Page_ClientValidate())
return true;
else
return false;

Categories

Resources