jQuery Ajax submission problems - php

Why doesn't the following pick up the form? All it does is just to do a normal PHP post without throwing any errors...
I'm using blockUi on this as well, hence block/unblock.
$(document).ready(function(){
$("input.update").click(function(){
var str = $(this).parent().serialize();
$(this).parent().parent().block({ message: "<span class=\"loading\"><img src=\"<?php echo $siteUrl ?>/admin/template/images/loading.gif\" alt=\"loading...\" /><p>Updating...</p></span>" });
$.ajax({
type: "POST",
url: "forms/update.php",
data: str,
success: function(){
$("div.edit_box").unblock();
$("div.edit_box").append("<span class=\"success\">This has been updated!</span>");
}
});
return false;
});
});
This is my first attempt at using jQuery's Ajax functionality so please bear with me.

("input.update").click(function(){
should be
$("input.update").click(function(){

Since it seems you're only using the 'success' callback of post you could use the .post method, which is a bit easier on the eyes. Also you can put those block calls inside ajaxStart and ajaxStop. To me it's neater.
The $(this).parent().parent().block seemed wrong to me, I changed it to reference the same element that is used for unblocking. I'd also be checking the output of the PHP script, to make sure that whatever you are 'updating' actually is updated (just echo XML from PHP and you'll see it on your console log).
$(function() {
// Apply click handlers to anchors
$("input.update").click(function(e){
// Stop normal link click
e.preventDefault();
var str = $(this).parent().serialize();
// Send request
var action = "forms/update.php";
$.post(action, {data:str}, function(xml) {
console.log(xml);
$("div.edit_box").append("<span class=\"success\">This has been updated!</span>");
})
});
// Adds a wait indicator to any Ajax requests
$(document.body).ajaxStart(function() {
$("div.edit_box").block({ message: "<span class=\"loading\"><img src=\"<?php echo $siteUrl ?>/admin/template/images/loading.gif\" alt=\"loading...\" /><p>Updating...</p></span>" });
}).ajaxStop(function() {
$("div.edit_box").unblock();
$("div.edit_box").append("<span class=\"success\">This has been updated!</span>");
});
});

Related

Refresh php embedded in html [duplicate]

What i want to do is, to show a message based on certain condition.
So, i will read the database after a given time continuously, and accordingly, show the message to the user.
But i want the message, to be updated only on a part of the page(lets say a DIV).
Any help would be appreciated !
Thanks !
This is possible using setInterval() and jQuery.load()
The below example will refresh a div with ID result with the content of another file every 5 seconds:
setInterval(function(){
$('#result').load('test.html');
}, 5000);
You need a ajax solution if you want to load data from your database and show it on your currently loaded page without page loading.
<script type="text/javascript" language="javascript" src=" JQUERY LIBRARY FILE PATH"></script>
<script type="text/javascript" language="javascript">
var init;
$(document).ready(function(){
init = window.setInterval('call()',5000);// 5000 is milisecond
});
function call(){
$.ajax({
url:'your server file name',
type:'post',
dataType:'html',
success:function(msg){
$('div#xyz').html(msg);// #xyz id of your div in which you want place result
},
error:function(){
alert('Error in loading...');
}
});
}
</script>
You can use setInterval if you want to make the request for content periodically and update the contents of your DIV with the AJAX response e.g.
setInterval(makeRequestAndPopulateDiv, "5000"); // 5 seconds
The setInterval() method will continue calling the function until clearInterval() is called.
If you are using a JS library you can update the DIV very easily e.g. in Prototype you can use replace on your div e.g.
$('yourDiv').replace('your new content');
I'm not suggesting that my method is the best, but what I generally do to deal with dynamic stuff that needs access to the database is the following method :
1- A server-side script that gets a message according to a given context, let's call it "contextmsg.php".
<?php
$ctx = intval($_POST["ctx"]);
$msg = getMessageFromDatabase($ctx); // get the message according to $ctx number
echo $msg;
?>
2- in your client-side page, with jquery :
var DIV_ID = "div-message";
var INTERVAL_IN_SECONDS = 5;
setInterval(function() {
updateMessage(currentContext)
}, INTERVAL_IN_SECONDS*1000);
function updateMessage(ctx) {
_e(DIV_ID).innerHTML = getMessage(ctx);
}
function getMessage(ctx) {
var msg = null;
$.ajax({
type: "post",
url: "contextmsg.php",
data: {
"ctx": ctx
},
success: function(data) {
msg = data.responseText;
},
dataType: "json"
});
return msg;
}
function _e(id) {
return document.getElementById(id);
}
Hope this helps :)

Ajax/ Jquery in Zend framework

I’m using Zend framework (php) and I’m trying to submit a from using ajax/jquery.
Here’s the .phtml:
<form id="find">
<input type="text" name="name">
<input type="submit" id="submit" value="Submit">
</form>
Here’s the ajax/jquery part:
$(document).ready(function() {
$("#submit").click(function(){
$.ajax({
type:'POST',
url: "<?php echo SITE_URL;?>Training/test",
data:$('#find').val(),
success: function(response) {
alert (response);
}
});
});
});
Here, “Training” is the controller and “test” is the action inside the controller. The action has just 1 line of code which is echo “hello”. After the user types a number in the box and clicks on “submit”, the control has to go to the controller thus displaying “hello” on success. However, nothing happens when I click on it. Please help me. Thanks in advance.
You didn't name parametr in Ajax call
data:$('#find').val(),
change it to
data:{'param': $('#find').val()},
About Zend it doesn't matter if it's zend or not. You can handle request just providing proper URL. You can access param value in Zend via $this->getParam('param') method.
Also you don't prevent default submit action. Change your function to:
$("#submit").click(function(ev){
ev.preventDefault();
or use in the end of function return false;
I did not test your jQuery. But note you need the instruction event.preventDefault to ensure you haven't the normal form submit action.
The main problem is at your zend Controller because you need a
special response. I suppose you have a controller to perform the request logics. I'll name it AjaxController and I'll name the action ajaxrecuestAction to illustrate how to send a proper response.
<?php
// Filename: yourProject/module/ModuleName/src/Controller/AjaxController.php
namespace ModuleName\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class AjaxController extends AbstractActionController {
public function ajaxrecuestAction(){
// This function is called by zend to procces your ayax request
// you must test if it's an xmlHttpRequest
$request = $this->getRequest();
$is_xmlHttpRequest = ($request->isXmlHttpRequest()) ? 1 : 0;
if(!$is_xmlHttpRequest){
// If not you must return a normal page, a message page
// perhaps a forgiven message page, etc. It depends on your site
// logics
}else{
// The solution's KEY
// You must disable the zend's normal output
$viewmodel = new ViewModel();
$viewmodel->setTerminal($is_xmlhttprequest);
// Proccess the input and prepare your output
$output = CallTheLogicsToPrepareIt($request->getContent());
// send your response
$response = $this->getResponse();
$response->setContent($output);
return $response;
}
}
**EDIT: Just noted that, in your HTML, you didn't give an ID attribute to the "find" field. Therefore $('#find').val() will give you an error, something like "cannot find method val() of undefined. Add the id=find tag to your and it should work.
** Other Edit: Sorry about the confusion. Your form has id=find but what you want to send to the server (I believe), is the value of the fields. So give an ID=name to your input then use:
var data = {find: $('#name').val()};
You should start by using your console to see if the event is triggered. Something like:
<script>
$(document).ready(function() {
$("#submit").click(function(e){
e.preventDefault ? e.preventDefault() : e.returnValue = false; //This will prevent the regular submit
console.log('Hello');
});
});
</script>
(You do use Fire bug or the Chrome dev tools, right) ? If not, look at the end of this post.
If you can see the Hello in your console, you're on the right path. Then try to set your url in a variable and try to check it in your console:
<script>
var url = "<?php echo SITE_URL;?>Training/test";
$(document).ready(function() {
$("#submit").click(function(e){
e.preventDefault ? e.preventDefault() : e.returnValue = false; //This will prevent the regular submit
console.log(url);
});
});
</script>
Then you should see the url in the console, meaning you're still doing good.
If that works, try to set the data and check the output in the same way:
<script>
var url = "<?php echo SITE_URL;?>Training/test";
var data = {
find: $('#find').val()
};
$(document).ready(function() {
$("#submit").click(function(e){
e.preventDefault ? e.preventDefault() : e.returnValue = false; //This will prevent the regular submit
console.log(data);
});
});
</script>
Hoping everything still works (you saw the data), then try the actual full code and see if you have an error or something. Also, be sure to include an error function to your ajax call so you will have a response if something went wrong on the server.
<script>
var url = "<?php echo SITE_URL;?>Training/test";
$(document).ready(function() {
$("#submit").click(function(e){
e.preventDefault ? e.preventDefault() : e.returnValue = false; //This will prevent the regular submit
var url = "<?php echo SITE_URL;?>Training/test";
var data = {
find: $('#find').val()
};
$.ajax({
type:'POST',
url: url,
data: data,
success: function(response) {
alert (response);
},
error: function(resp) {
alert(resp.responseText);
}
});
});
});
</script>
Some tools to help you out:
If you are using FireFox, use FireBug for your debugging: https://addons.mozilla.org/fr/firefox/addon/firebug/
If you are using Chrome (my personal favorite), learn a bit more about Chrome Developer Tools: https://developers.google.com/chrome-developer-tools/?hl=fr
If you are using IE, please switch to something else for development purposes, then try it in IE to make sure you code is compatible (most likely won't be but it will be easier to find out why it doesn't work afterwards).
As for the line e.preventDefault......, look into this SO post for more details: https://stackoverflow.com/a/15913969/1483513
Hope this helps !

Posting to a PHP script with Ajax (Jquery)

I have an application that I'm writing that, in one aspect of it, you click on a checkmark to complete a task, a popup window is displayed (using bootstrap), you enter your hours, and then that is sent to a PHP page to update the database. I'm using FF (firebug) to view the post. It's coming up red but not giving me an error. The only thing I'm doing is echoing out "sup" on the PHP page, and it's still showing errors, and I can't figure out why.
This is my initial click function:
$('.complete').on('click', function(event) {
var id = $(this).attr('data-id');
var tr = $(this).parent().parent();
var span = $(tr).children('td.task-name');
var r = (confirm('Are you sure you want to complete this task?'));
if (r){
addHours(id);
} else {
return false;
} // end else
});
That works fine, and it fires my next function which actually fires the bootstrap modal:
function addHours(id) {
var url = 'load/hours.php?id='+id;
$.get(url, function(data) {
$('<div class="modal hide fade in" id="completeTask">' + data + '</div>').modal()
.on('shown', function() {
pendingTask(id);
}); // end callback
}).success(function() {
$('input:text:visible:first').focus();
});
} // end function
This is also working, and the modal is displayed just fine. However, whenever I post the form to my logic page, it fails for no reason. This is the function to post the form to the logic page:
function pendingTask(id) {
$('.addHours').on('click', function(event) {
var formData = $('form#CompleteTask').serializeObject();
$.ajax({
url:'logic/complete-with-hours.php',
type: 'POST',
dataType: 'json',
data: formData,
success: function(data) {
if (data.status == 'error') {
$(this).attr('checked', false);
//location.reload();
} // end if
else {
$(this).attr('checked', true);
//location.reload();
} // end else
},
dataType: 'json'
});
}); // end click
} // end function
When this is fired, I see this in my Firebug console:
I know this is a lot of information, but I wanted to provide as much information as I could. Every other post function in the application is working fine. It's just this one. Any help would be appreciated.
Thanks in advance.
The jQuery.ajax data parameter takes a simple object of key value pairs. The problem could be that the object created by serializeObject() is too complex. If that's the case, you could either process the formData object to simplify it or try data: JSON.stringify(formData)
Does serializeObject() even exist in jQuery? is that a function you wrote yourself? Can you use jQuery functions like serialize() or serializeArray() to serialize the form data and see how it goes.
Usually the red indicates a 404 response error. We can't tell in this screen shot. Check your php code by directly calling the requested page and getting a proper response.
Also make sure your dataType is application/json which is the proper mime type header (though I don't think this is causing the error). You also should only have dataType once (you have it again at the bottom)
I figured it out. I changed the post type from the structure I entered above to a standard post:
$("#CompleteTask").validate({
submitHandler: function(form) {
var hours = $('#hours').val();
$.post('logic/complete-with-hours.php', {'hours': hours, 'id':id},
function(data){
if (data.status == 'success') {
$(checkmark).attr('checked', false);
$('.message').html(data.message).addClass('success').show();
} // end if
if (data.status == 'error') {
$('.message').html(data.message).addClass('error').show();
} // end else
},
"json"
); //end POST
} // end submit handler
}); // end validate
That seemed to do the trick

jquery code snippet on load

I'm working with this code snippet plugin : http://www.steamdev.com/snippet/ for my blog
but the plugin doesn't work on page load.
It only works at first page refresh.
I load my content in a specific div with jquery.ajax request and i'm trying this :
$(window).on("load", function(){
$("pre.cplus").snippet("cpp",{style:"acid"});
$("pre.php").snippet("php",{style:"acid"});
});
I also tried to trigger the load event but i don't know if it is correct..
Another question : i build my html with php string like this example:
$string = '<pre class="cplus">
#include <iostream>
int main()
{
//c++ code
}
</pre>
<pre class="php">
<?php
function foo()
{
// PHP code
}
?>
</pre>';
echo $string; // ajax -> success
but the PHP snippet shows empty (the c++ is ok). Any other way (or plugin) to show php code snippet on my page?
Thank you.
SOLVED:
The problem isn't the plugin or Iserni suggestions.. i had a problem in page load (ajax)..
This is how i load the pages:
function pageload(hash) {
if(hash == '' || hash == '#php')
{
getHomePage();
}
if(hash)
{
getPage();
}
}
function getHomePage() {
var hdata = 'page=' + encodeURIComponent("#php");
//alert(hdata);
$.ajax({
url: "homeloader.php",
type: "GET",
data: hdata,
cache: false,
success: function (hhtml) {
$('.loading').hide();
$('#content').html(hhtml);
$('#body').fadeIn('slow');
}
});
}
function getPage() {
var data = 'page=' + encodeURIComponent(document.location.hash);
//alert(data);
$.ajax({
url: "loader.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
$('.loading').hide();
$('#content').html(html);
$('#body').fadeIn('slow');
}
});
}
$(document).ready(function() {
// content
$.history.init(pageload);
$('a[href=' + window.location.hash + ']').addClass('selected');
$('a[rel=ajax]').click(function () {
var hash = this.href;
hash = hash.replace(/^.*#/, '');
$.history.load(hash);
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
$('#body').hide();
$('.loading').show();
getPage();
return false;
});
// ..... other code for menus, tooltips,etc.
I know this is experimental , i have made a mix of various tutorials but now it works..
comments are much appreciated..
Thanks to all.
The PHP snippet seems empty because the browser believes it's a sort of HTML tag.
Instead of
$string = '<pre class="php">
<?php
function foo()
{
// PHP code
}
?>
</pre>';
you need to do:
// CODE ONLY
$string = '<?php
function foo()
{
// PHP code
}
?>';
// HTMLIZE CODE
$string = '<pre class="php">'.HTMLEntities($string).'</pre>';
As for the jQuery, it is probably due to where you put the jQuery code: try putting it at the bottom of the page, like this:
....
<!-- The page ended here -->
<!-- You need jQuery included before, of course -->
<script type="text/javascript">
(function($){ // This wraps jQuery in a safe private scope
$(document).ready(function(){ // This delays until DOM is ready
// Here, the snippets must be already loaded. If they are not,
// $("pre.cplus") will return an empty wrapper and nothing will happen.
// So, here we should invoke whatever function it is that loads the snippets,
// e.g. $("#reloadbutton").click();
$("pre.cplus").snippet("cpp",{style:"acid"});
$("pre.php").snippet("php",{style:"acid"});
});
})(jQuery); // This way, the code works anywhere. But it's faster at BODY end
</script>
</body>
Update
I think you could save and simplify some code by merging the two page loading functions (it's called the DRY principle - Don't Repeat Yourself):
function getAnyPage(url, what) {
$('.loading').show(); // I think it makes more sense here
$.ajax({
url: url,
type: "GET",
data: 'page=' + encodeURIComponent(what),
cache: false,
success: function (html) {
$('.loading').hide();
$('#content').html(hhtml);
$('#body').fadeIn('slow');
}
// Here you ought to allow for the case of an error (hiding .loading, etc.)
});
}
You can then change the calls to getPage, or reimplement them as wrappers:
function getHomePage(){ return getAnyPage('homeloader.php', "#php"); }
function getPage() { return getAnyPage('loader.php', document.location.hash); }
ok for the first issue I would suggest to
see what your JS error console saying
ensure correspondent js plugin file is loaded
and use the following code when you are using ajax (the key thing is "success" event function):
$.ajax({
url: 'your_url',
success: function(data) {
$("pre.cplus").snippet("cpp",{style:"acid"});
$("pre.php").snippet("php",{style:"acid"});
}
});
for the second issue lserni answered clearly
you need to use to jquery on load function like so:
$(function(){
RunMeOnLoad();
});

Jquery POST to refresh a div

I want to use $.post function of jquery to do a div refresh, only if the content returned in the json data from the php script is modified. I know that ajax calls with $.post are never cached. Please help me with $.post, or $.ajax if it is not possible with $.postor any other method with which this is possible.
Thanks
Why don't you cache the response of the call?
var cacheData;
$.post({.....
success: function(data){
if (data !== cacheData){
//data has changed (or it's the first call), save new cache data and update div
cacheData = data;
$('#yourdiv').html(data);
}else{
//do nothing, data hasan't changed
This is just an example, you should adapt it to suit your needs (and the structure of data returned)
var result;
$.post({
url: 'post.php'
data: {new:'data'}
success: function(r){
if (result && result != r){
//changed
}
result = r;
}
});
Your question isn't exactly clear, but how about something like this...
<script type="text/javascript">
$(document).ready(function(){
$("#refresh").click(function(){
info = "";
$.getJSON('<URL TO JSON SOURCE>', function(data){
if(info!=data){
info = data;
$("#content").html(data);
}
});
});
});
</script>
<div id="content"></div>
<input id="refresh" type="submit" value="Refresh" />
I think you should use .getJSON() like I used it there, it's compact, and offers all the functionality you need.
var div = $('my_div_selector');
function refreshDiv(data){
// refresh the div and populate it with some data passed as arg
div.data('content',data);
// do whatever you want here
}
function shouldRefreshDiv(callback){
// determines if the data from the php script is modified
// and executes a callback function if it is changed
$.post('my_php_script',function(data){
if(data != div.data('content'))
callback(data);
});
}
then you can call shouldRefreshDiv(refreshDiv) on an interval or you can attach it to an event-handler

Categories