I'm trying to do GET request onclick using jQuery AJAX function, but the problem is that I dont see the parameters in the URL:
Here is the code:
<a href="#" class="md-list-content" data-invoice-id=<?php echo $invoiceId; ?> onclick="myFunction('<?php echo $invoiceId; ?>')">
Here the Javascript code:
function myFunction(id) {
var invoice_detailsid = id;
//alert(id);
$.ajax({
url:"invoice_details", //the page containing php script
type: "GET", //request type
data: ({invoice_detailsid: invoice_detailsid}),
success:function(data){
console.log("success);
}
});
}
After I do submit, I want the URL to look like this:
http://localhost/project/page_invoices/a0yO01t8ZUIAY
I need to do it this was without refreshing the page, and at the same time, I want to see the params when I do GET request.
Please help!
Thanks.
When making a ajax request the url of the current page is not changing. The request it's not related to current page. That's the advantage of ajax request that you stay in current page and you make a request in background.
If you want to change the url of the current page without leaving it (or refresh) you will have to use history library from js.
Here you can find more information about history: https://developer.mozilla.org/en-US/docs/Web/API/History_API
data takes in a string and not an object.
Try something like this
data: "paramName="+paramValue
Related
I basically don't seem to understand sending a variable to another page.
I've tried PHP sessions, javascript cookies and ajax POST and GET.
I'm trying to send the innerHTML of a div, with the data created by a jQuery call,
a variable called savedartists. It displays correctly in the console.log on the sending page but the $_POST['savedArtists']
is undefined in the receiving page. I have spent hours looking at different posts on this site but I haven't been able to get it to work.
Any help is appreciated.
<input class="et_pb_button et_pb_button_0 et_pb_bg_layout_light" onClick="savequote();" type="button" id="savedchoices" value="Commander la prestation" >
<script>
function savequote() {
var savedartists = document.getElementById('selectedList').innerHTML;
console.log(savedartists);
$.ajax({
type: "POST",
url: 'example.com/artiste/mise-en-relation/',
data: { savedArtists : savedartists },
success: function(data) {
console.log("success!");
location.href = "example.com/artiste/mise-en-relation/";
}
});
}
</script>
On the receiving page (example.com/artiste/mise-en-relation/)
<?php
if(isset($_POST['savedArtists']))
{
$uid = $_POST['savedArtists'];
echo $uid;
} else {
echo 'zit!';
}
?>
Thanks for your time
Capturing as an answer for future readers...
Fundamentally what's happening here is that two requests are being made to the target page. The first one is the AJAX request:
$.ajax({
type: "POST",
url: 'example.com/artiste/mise-en-relation/',
data: { savedArtists : savedartists },
success: function(data) {
//...
}
});
This is a POST request which contains the data you expect, and works just fine. However, the result of this request is being ignored. That result is available in the success callback, but the code doesn't do anything with it:
console.log("success!");
location.href = "example.com/artiste/mise-en-relation/";
Instead, what the code is doing is performing a redirect. This creates a second request to that same page (though it's essentially irrelevant that it's the same page). This is a GET request and contains no data to send to the server.
At its simplest, you should either use AJAX or redirect the user. Currently you're mixing both.
I want to redirect to the other page.
In that case AJAX is the wrong tool for the job. You may not even need JavaScript at all, unless you want to modify the elements/values of a form before submitting that form. But if all you want is to POST data to another page while directing the user to that page, a plain old HTML form does exactly that. For example:
<form method="POST" action="example.com/artiste/mise-en-relation/">
<input type="text" name="savedArtists">
<button type="submit">Submit</button>
</form>
In this case whatever value the user enters into the <input> will be included in the POST request to example.com/artiste/mise-en-relation/ when the user submits the form.
I run a wordpress website. There is a button on the homepage that pushes a new state:
<button onclick="javascript:window.history.pushState('test','','?id=123')"
class="modalopen" </button>
After I click the button a modal contact form opens that needs to use the id parameter to decide who the email recipient will be in PHP.
I am trying to get the parameter:id from:
http://example.com/?id=452
Using the $_GET function.
I understand that pushState is client-side and that the URL has not updated server-side. How would I go about updating the url server-side without reloading the page.
I assume it would involve ajax. Unfortunately, I have no knowledge on it.
Alternatively, perhaps there is another way to retrieve the id.
For obtaining the email recipient the contact form uses this code:
$post_id = $_GET['id'];
$val = get_post_meta($post_id, $key, true);
Thank you in advance!
Using history.pushState() changes the referrer that gets used in the HTTP header, this will cause the URL bar to display http://example.com/?id=452, but won't cause the browser to load the url, so you cannot access to $_GET['id'], since the page is not actually requested to the server with that parameter.
If you want to use the id after it is created and without reloading the page you definitely need an ajax call.
Doing it is simpler than what you might think, you can try to do it using jQuery.
a sample call is
$.ajax({
type: "POST",
url: "doSomething.php",
data: {id:id},
cache: false,
success: function(result){
// do something with the data returned by the doSomething.php script
}
});
Google jQuery ajax for more details.
This can be a useful starting point http://www.tutorialspoint.com/jquery/jquery-ajax.htm
I'm trying to program a custom contact content manager in HTML/CSS with PHP/mySQL/Jquery to make it dynamic.
I have my login form which send the $_REQUEST to my connection.php, when the auth is correct, I return json to my Jquery and when it is good, I use window.location.replace to redirect the user to the control panel.
When I'm on the index.php of the control panel, I want to check if the user's session_id is into my sql database and if it exceeded the expiration time.
I have my functions which check this and return the good value but I want to execute it and send the result to my jquery without using GET or POST method.
If I remember, you have
$.ajax({
type: "POST", //or GET method
dataType: "json",
url: $(this).attr('action'),
data: $(this).serialize(),
success: function({
}),
error: function({
})
});
But you must specify the element "data" no? can I use it without data and put "file.php" as url without POST or GET method?
I want to get into my success method the result of my php functions :
if the json return false, the user can access the page.
if the json return true, I will logout the user and redirect him to the login.php
I'm doing this system because I don't want anybody can access the control panel by writing the correct url or after 4 days.. I put an expiration time to one hour (for the moment) for anybody who login into the control panel and I check on all page that the expiration time isn't exceeded.
I saw that using 'window.location.replace' doesn't allow to return to the previous page.. has anyone a solution? I don't want to have an event to redirect the user, only redirect him to another url (my file.php) after a condition.
Currently, I use it to execute php without POST, GET method with $.ajax..
$(document).ready(function(){
$(function(){
var ticket = '<? echo $tickets; ?>';
console.log(ticket);
if ( ticket === '' )
$(".new_ticket h2").after('<p>Aucun nouveau ticket.</p>');
else
{
console.log('else');
$(".new_ticket h2").after('<p>Il y a un ticket.</p>');
}
});
});
I have a last question, when I write :
$(document).ready(function(){
$(function(){
}
Is it directly executed by jquery when the DOM is ready? can I write mutliple '$(function(){}' in a file ?
Thanks for the help!
What is the problem with using POST or GET? It works perfectly fine.
Here foobar.php returns a json object with status in it. Change it to whatever your script return.
$.post('foobar.php', function(data) {
if( data.status === false) {
//All good
}else {
//Redirect
window.location.href = "http://newpagehere.com/file.php";
}
});
With window.location.href you will be able to use the back and forward buttons.
And yes, when using $(document).ready(function() { }); it runs when the DOM is ready.
http://api.jquery.com/ready/
One last thing is that I would not rely on Javascript here, I would do all checking with PHP instead when the user changes page. I would also handle the redirection there.
I have a jQuery script that sends POST data via AJAX to a php file that then creates a table. I have used firebug to check the console and everything gets created properly. On the success: I reload the window and the table isn't displayed.
I know the table html was created properly from the php file because I commented out the reload so I could see exactly what it created) I have lots of things displayed on my page and would like the table in a particular spot. How can I get the table to actually display where I want it to?
<script>
$(document).ready(function () {
$("#stayinfobutton").click(function () {
var id = $('#id').val();
var dataString = {
id: id
};
console.log(dataString);
$.ajax({
type: "POST",
url: "classes/table_auto_guests.php",
data: dataString,
cache: false,
/*success: function(html)
{
window.location.reload(true);
}*/
});
});
});
</script>
The window.location call will reload a new page in the browser window, this will loose the data returned to the ajax call by the server.
Usually the response to Ajax calls is loaded directly into your page, something like:
success: function(html)
{
$('#guestsTable').html(html);
$('userForm').hide();
}
I made up the guestsTable div and userForm names, ;).
The return data may need some coercing to make it into html (I'm assuming your using JQuery), hopefully the php script will set it to html/text in the header, also dataType: html can be passed in the $.ajax({...}) call.
Alternatively, if the classes/table_auto_guests.php returns a full page which you want to load in the browser, Ajax may not be what you are looking for. This post contains code on how to submit the data as a form, and load the result as a new page.
Here's the thing: I have an array which I must send to another page... not using an AJAX request. I'm trying to redirect my user to this new page, or maybe to open a popup with the new page, but this new page must receive the array data on a POST request.
How do I do this in javascript? I have no problem JSON encoding my array before sending it, I just don't know how to redirect my user to a new page with the data "attached", in javascript.
I'm using ExtJS4, so if there's anything on Ext.util, I have no problem using it.
Thanks.
You can do this (using javascript)
make a new FORM
set the action as the new page
set the method as POST
add a hidden field
set the value of the field to this Value you want to send
Pragmatically submit the form
You can Ajax POST to the target page's url:
Ext.Ajax.request({
url:'/target/url/', async:false, method:'POST',
jsonData: {
jsonArray: yourJsonArray
}
success: function() {
console.log('posted successfully');
}
});
async:false loses the asynchronous functionality; simply remove it if you don't need your POST to be synchronous.