I have a form rendered in the view which action is setted to the same page /index. <form action="" name="formRegistro" id="formRegistro"> and a JQuery function which is called when the form is submitted
$('#formRegistro').submit(function() {
// Retrevies data from the form
data = $('#someInput').val()
//Execute AJAX
$.get(
'http://localhost/myproject/',
{ data },
function(data){
$('#divStatus').html(data);
}
);
//Prevent page loading
return false;
});
I'm using and if statement in the IndexController to change between normal view and post view if ($this->_request->isGet()) { and I'd like to output a message in the #divStatus but with I don't know how to do it
Ok, first off. A normal HTTP request is always a GET request, so your condition would always be true (isGet())
what do you mean you want to output a message in the #divStatus ? That seems to be what you're doing with the callback function.
Are you using Firebug? It's a Very NECESSARY tool for working with ajax requests.
Download and install it for firefox, then do the following:
Press the new firebug button at the bottom of the screen
reload your page
try submitting the form
watch the console as your ajax request gets displayed down there
find out what's happening by using Firebug
I recommend using the $.ajax() function with jquery instead of the $.get() function. You'll have more control.
If you want to display a message from the ajax request in your script when it loads, you could parse the data output of the success callback function - or you could make the function return a json object.
I hope this helps. Good luck :)
With ZF there is a very cool way to manage AJAX & "normal" requests within the same Controller class.
It is based on the fact that most JS framework send the X-Requested-With: XmlHttpRequest HTTP header.
Take a look at AjaxContext and ContextSwitch in Zend Controller Action Helpers
If you want to use jQuery to show this message, you can inject text/html into another html element with the appendTo() function, like this:
$('My Message').appendTo('#divStatus');
Related
I'm displaying data from DB like this:
<?php foreach ($r as $k => $v):?>
<div data-role="collapsible" data-mini="true" class="collapsible">
Name: <?=$v['name']?>
</div>
<?php endforeach; ?>
Now when I add new data to DB and the form is submitted, my script redirects back to this page. How do I show the new data immediately without manually refreshing the browser? I usually don't have this issue if I'm not using Jquery Mobile.
You could send the form with jquery ajax
$('form[name="myform"]').submit(function(evt){
evt.preventDefault();
$.post('/my_form_handler.php', $(this).serialize())
.done(function(data){
//Populate dom elements here with new data
}).fail(function(data){
//Handle failed ajax post.
});
});
And then on successful post change the content of the dom-elements.
Not 100% sure i got the right syntax for it but i think it should give you a general idea on how to do it.
The problem here is that the data is hard coded into the page's HTML. After your form submission it's jQueryMobile that's changing the page/view, and no refresh of the page takes place so you're still seeing the same data.
You should refactor to create the loop with JSON data (loaded via AJAX). If the data is cached in a local variable, you can either add to it with the form's data, or make a fresh AJAX call to the server (recommended if you need sorting or filtering).
After reloading the data, the rendering code can be called, showing the new list.
it is easy.
you can send the request to the server using ajax.
and on the server side, you have to make the function to return the data added.
the ajax function will get the success or fail function.
the success function will run if it works.
on the success function , you have to add the content using javascript jquery with the returned data.
Thanks
If I want to do some PHP on an event(e.g. onchange) should I use jQuery ajax like:
$("#elm").on("change", function(){
//ajax code
}
, should I use the PHP in the HTML attribute like:
<element onchange="<?php //stuff to do ?>"></element>
You seem to be conflating two different issues.
JS bound events vs intrinsic event attributes.
Bind your event handlers with JS.
Follow the principles of Progressive Enhancement and Unobtrusive JavaScript.
Ajax vs Putting PHP in a JS function
If you put PHP in a JS function then it will run when the PHP outputs the JS function to the browser, not when the JS function is called.
If you want to run PHP in response to an event, then you have to make an HTTP request to the server to run the PHP.
If you want to insert content from the load of page and leave it static, you should use only PHP.
If you want to insert content dynamically (changing with users interactions) you should use AJAX.
I can't found out what are you trying to achieve with your example, so not very sure what you should do there.
taking your code it would give this :
$("#elm").on("change", function(){
//ajax code
$.get('url', {data:'tosend'}, function(data){
// here you have the response of the php script in the data object
// it can be json for exemple
});
}
You must realise two things, your php code will be render when the page is loaded in the
browser so the second code you gave us
means that your "onchange" event is already present in your page.
If you want to request something (data, html, etc) to server from a loaded page, then do an ajax.
In that case below code is correct.
$("#elm").on("change", function(){
//ajax code
}
You cannot execute a piece of php code from client side. But you can assign values from php to javascript and then do operations on client side.
Currently I have a button:
<ul>
<li><button onclick="display('1')">1</button></li>
<li><button onclick="display('2')">2</button></li>
<li><button onclick="display('3')">3</button></li>
</ul>
That when pressed, calls a javascript function, and displays PHP based on which button is pressed using AJAX. I figured this out all on my own. The AJAX gets a PHP file with a postgres query that outputs a table of data to a div.
Now I want to be able to add, via form, new data and have it refresh (without reloading the page, yannknow?). I've tried a couple of things, and have hit roadblocks every time.
My initial idea was to have the form submit the data using a javascript function and AJAX, then call my "display()" function after the query to reload the content. I just can't figure it out using GoogleFu.
Based on my current idea, I'd like help with the following:
How do I pass the form data to a javascript function.
How do I use POST to pass that data to PHP using AJAX?
I'm super new to javascript and AJAX. I've looked into jquery as it seems like that's the way to go, but I can't figure it out. If there's a better way to do this, I'm open to suggestions. Please forgive any misuse of nomenclature.
EDIT: Once I solve this problem..., I'll have all the tools needed to finish the project preliminarily.
This example is copied directly from the jQuery API docs for $.post. When in doubt, first place to look is in the API
http://api.jquery.com/jQuery.post/
Example: send form data using ajax requests
$.post("test.php", $("#testform").serialize(), function(data){
/* success- do something with returned data*/
});
Now extend the concept further and wrap the post in a submit handler for the form
$("#testform").submit(function(){
/* code from above, changing form selector to "this" */
$.post("test.php", $(this).serialize(), function(data){
/* success- do something with returned data*/
});
/* prevent browser default submit*/
return false;
})
Refer to jQuery.post method. It does what you want (sends AJAX request with POST data).
To grab values from inputs, use val() method for nodes that have value (textarea, input, .. )
I want to make a form that uses jQuery's ajax function to submit the data, but to be functional when javascript is disabled. So I need a way to know, in the server-side script (PHP), weather the request came from ajax or from simply submiting the form.
HTML:
<form id="form_1" method="post" action="process.php">
jQuery:
$.ajax({
type: "POST",
url: "process.php",
data: $("#form_1").serialize(),
cache: false,
success: function(msg){alert(msg)}
});
So I would like to check in process.php if it was called from jQuery or from submiting the form. Note that I serialize the data, I don't want to use an URL parameter, like '&ajax=1'. Thanks!
Automatically, requests made with XMLHTTPRequest (like those made with jQuery's AJAX suite) have the X-Requested-With header set to XMLHTTPRequest. You can check for the presence of this header.
if (
isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
($_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHTTPRequest')
) {
// request is AJAX
}
You can check for the presence of $_SERVER['HTTP_X_REQUESTED_WITH']. jQuery will send this header with AJAX calls.
The jQuery serialize() method won't serialize (and therefore provide a value for) any submit buttons contained within the form, but submitting the form using one of these will do so. You can check for the existence of that value using PHP and handle appropriately.
I know you don't want to use a url parameter, but it might be the only way you can determine where the call came from.
You can construct data manually and add an AJAX only parameter, and then check for it in PHP.
I would suggest you add a field to your form when it is submited via ajax just before the ajax call. So you can serialize your form and send it as the data containing your ajax=1 for example
The server has no guaranteed way to know what mechanism the client used to make a request. Any request that you can make via JQuery or any other kind of page load can be spoofed by another client to look exactly the same; the server would have no clue.
A client that isn't trying to spoof the result will generally send some clues to the server, in the form of the UserAgent string, and so on, but none of these clues will tell the server anything about whether it's being called via Ajax or not.
Therefore the only route you have to tell the server where the request is coming from is in the URL, and the easiest way to do that is to add an extra parameter. I know you don't want to do this, but it is the best answer to your question.
The alternative option is to have a different action URL for the form if it is called via Javascript. You can toggle the URL easily in JQuery when the page is loaded, and because it is done in Javascript, if JS is disabled then the form will post to the default URL, and you'll be able to generate you non-JS page load.
The final solution is not to do anything different on the server; render the page exactly the same whichever route the user comes in via, and instead have the JQuery code accept the that page code and extract the relevant parts of it for use in the Ajax context.
I hope that helps.
There is a much simpler way to achieve this. Use something similar for jQuery:
$("form").submit(function(){
/*ajax request*/
return false;
}
The return false; does the "magic". If you have JS enabled, then the submit button won't submit the regular way; you can process data via jQuery and send it with AJAX. If you have JS disabled, therefore this function is not called and the form is submitted as usual.
Is there a way to send data to database when click on a link without page refresh?
I use php/mysql...
I will give you an example using jQuery.
Let's say that we have a link with an attribute id="button_id" (you have to learn the jQuery selectors ).
$("#button_id").click(function(){
var var_data = 5;
$.ajax({
url: "my_script.php",
data: { var_PHP_data: var_data };
success: function(data) {
// do something;
alert(data);
},
});
});
Explanation: you will send the variable var_data with the name var_PHP_data to a my_script.php without page refresh using an ajax call (using GET method).
This is very simple example of what you have to write on your PHP script.
<?php
$var_name = $_GET['var_PHP_data'];
echo 'This is what you have send'.$var_name;
?>
Because the default method to send variables in the ajax function in jQuery is GET.
We have to use the $_GET function in PHP.
This php script will print a message and this message will be handled in the success: function in the Ajax call and just for example we will alert this message returned from PHP.
You'd have to use JavaScript. When a user clicks a link, if you don't use JavaScript, then you need to go user -> server -> user and they get a whole new page.
HTTP is stateless.
It's not possible without a page refresh but this is the classic use-case for AJAX requests. If you're not familiar with AJAX then there are various methods of doing this using all the popular JavaScript frameworks such as Prototype and jQuery
You can't send data directly to a database, but you can use AJAX to send data to a php page that will save them to the database, without reloading the page or following the link in the browser..
Have a look at http://api.jquery.com/jQuery.post/
Not using PHP because it is server side - you need JavaScript / AJAX for this.
Check out frameworks like dojo (http://www.dojotoolkit.org/) , mootools (http://mootools.net/) or jQuery ( http://jquery.com/ ).
Yes, you can use AJAX.
This is a very big topic, but I'd recommend you do some research on AJAX and jquery (javascript).
Here are some tutorials:
http://www.ajaxf1.com/tutorial/ajax-php.html
http://www.talkphp.com/vbarticles.php?do=article&articleid=58&title=simple-ajax-with-jquery
Do a search in google for more info.