jQuery Ajax send to the same page - php

I want to figure out how jQuery Ajax work when I don't define url for it. So it should send the data to the same page where is the ajax also. How can I get for example the 'GET' data after the ajax has been completed?
<script type="text/javascript">
$(document).ready(function() {
$(".idoszak").change(function() {
var idoszak=$(this).val();
var dataString = 'idoszak='+ idoszak;
$.ajax({
type: "GET", // or POST
url: "statisztika.php", //The page where is also this script
data: dataString,
cache: false,
success: function(html) {
???
}
});
});
});
Now the php:
<select name="idoszak" class="idoszak">
<option value="felev">Félév</option>
<option value="evvege">Évvége</option>
</select>
<div id="statisztika">
.
.
.
<?
$katlag = mysqli_query ($link, "SELECT jegy FROM jegyek WHERE `jegyek`.`osztaly` = '$osztaly' AND `jegyek`.`piros` = '0' AND datum = '$idoszak'");
$katlagok = mysqli_num_rows($katlag);
?>
.
.
.
</div>

This is what is happening:
You type a URL into the address bar (or follow a link or something like that)
Your browser makes a request to that URL
The server sends a response back to the browser
The browser renders the page
You trigger some JavaScript
The JavaScript gets the browser to make an Ajax request to the same URL (well, almost the same URL: you've changed the query string)
The server sends a response back to the browser
The browser makes the response available to JavaScript
You appear to be expecting step 8 to be the browser replaces the page rendered at step 4 with one based on the data from step 7. That doesn't happen.
All that happens is that the response is made available to JavaScript.
The body of that response will be in the html variable of the success function.
If you want to change what the user is seeing in the page, then you will have to write JavaScript to manipulate the DOM of the page (which can use the data from the html variable).

Related

Event.prevent() default ajax not sending data from form to php

I already checked around for this answer but all are different problems just same title (to prevent random duplicate marks).
Here is an ajax call to the click of the filter button that should send the data inserted in the form formmatcat to the php file formfilt.php and should load the result in a div with id resultins
<script>
$(function () {
$('#filter').on('click', function(event){
event.preventDefault();
$.ajax({
type: 'post',
url: 'formfilt.php',
data: $('#formmatcat').serialize(),
success: function () {
$("#resultins").load('formfilt.php');
}
});
});
});
</script>
I set the preventdefault to load only in the div without redirecting to the php file and this works but if I put the preventDefault it echoes the string I build by concatenating values sent from the form with those empty values. The strange thing is that if I remove preventDefault of course it redirects and loads the php file but with the correct values:
Moral of the story, data in the form with the ajax call goes correctly to the php file but looks like preventDefault don't let this. Thanks in advance
Here's the structure of the html part with the form
<form id="formmatcat" method="post" action="formfilt.php">
.
.
various textboxes
.
.
</form>
What you're doing is sending an AJAX request toformfilt.php, when this call happens and it returns a response it will be stored as a parameter within the success or $.done function as I'll mention later, that is where your echo'd content will be.
What you're doing here is when the call is successful, you simple send a GET request to the same page. Since that GET request differs from the AJAX POST request and has no POST parameters you'll not get the correct output.
By simply submitting the form and letting it go to the page rather than cancelling the request you're getting the right values as you're directly posting to the page with the correct values, when you call the load function you're doing a seperate AJAX get request.
What load actually is, is a rough equivelant to $.get which is shorthand for $.ajax.
Looking at jQuery AJAX docs
jqXHR.done(function( data, textStatus, jqXHR ) {});
An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details.
Basically, a $.ajax() call returns a promise object that you can chain callbacks on when it is finished. Also note that data here will be the actual content within your PHP file, thus if you rewrite your AJAX call like so:
<script type="text/javascript">
$(function() {
$('#filter').on('click', function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'formfilt.php',
data: $('#formmatcat').serialize()
}).done(function(data) {
$('#resultins').html(data);
});
});
});
</script>
It will then continue to load the output of formfilt.php into the div with ID resultins.
dont use form, use input without form, and use button tag use onclick to run function, if you use form, it will submit and redirect,
i'm not good with ajax on jQuery
but if i were to use javascript/XHR
var CB=document.getElementById("filter").value; //get input/filter value
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200)
document.getElementById('contain').innerHTML=xhttp.responseText;
};
var url="formfilt.php?filter="+CB;
xhttp.open("GET", url, true);
xhttp.send();
if you want to use post :
xhttp.open("POST", "formfilt.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send('filter='+CB);
sorry, i'm also learning, and new to this, just learning a week ago,

Unable to fill input value with PHP variable

I have two files, landing.php and test.php. Landing.php has a form that is submitted via ajax using the post method to test.php. If the ajax call is successful, the browser loads test.php, at which point I am having an issue. I cannot figure out what I am doing wrong in my attempts to display the value of the post data that is sent to test.php.
The following is the ajax call from landing.php. I am reasonably sure that this is working correctly from having looked at the post data in Firebug.
$('#searchForm').submit(function(e) {
e.preventDefault();
var data1 = $('#checkBoxDiv input').serialize() + '&' + 'barcodeID=' + $('#barcodeID').val();
$.ajax({
url: 'test.php',
data: data1,
type: 'POST',
success: function() {
window.location.href = "test.php";
}
});
});
Here are the contents of test.php.
<?php
$bar = $_POST['barcodeID'];
echo "<html>";
echo "<body>";
echo "<p>*" . $bar . "*</p>";
echo "</body>";
echo "</html>";
?>
If I were to take the asteriks out of the line with the <p> from test.php, I would be presented with a completely blank screen when I arrived at test.php in my browser. With them there, however, I am presented with "**" on my screen. The most confusing part is, however, that if I include
echo $bar;
in test.php, I see the value of $bar (00-00102 - exactly as it should be) in Firebug's response tab on the post data viewer.
After some research, I read that post was the method of choice for when you do not want to display query strings in the URL bar, as well as the method to use when you have a large amount of data to send (which will be the case for me, it'll end up being around five to six hundred characters when all is said and done). I've looked at other stackoverflow posts and articles, attempted to replicate what was recommended, and still cannot get this right.
Am I doing something completely wrong or attempting to use these methods in a way in which they are not intended to be used?
Don't change the window location in the success of your ajax call. The call is posting the data to test.php and you are getting your response back there. Then you are redirecting to the page with a blank post which results in just the asterisks.
If you only want to display the results from test.php change your $.ajax call to the following:
$.ajax({
url: 'test.php',
data: data1,
type: 'POST',
success: function(response) {
$('html').replaceWith(response);
}
});
Or if you do want to change the page, forget about the ajax and just post the form to test.php
You are reloading the window after the AJAX succeeds, there is no POST information at that point.
You can do something like this though:
$('#searchForm').submit(function(e) {
e.preventDefault();
var data1 = $('#checkBoxDiv input').serialize() + '&' + 'barcodeID=' + $('#barcodeID').val();
$.ajax({
url: 'test.php', // <-- POST exists during this call
data: data1,
type: 'POST',
dataType: 'html',
success: function(data) {
$('html').replaceWith(data);
}
});
});
The AJAX POST will be finished in one turn. That means, the values you had posted to test.php
through ajax will be present only through that request. What you are doing is, you are redirecting to test.php upon receiving response from test.php. This is a fresh request, and it does not have any POST values. Hence, there is nothing in $_POST['barcodeID'];
Also, in your code, you are having $('#barcodeID').val() twice. Try removing the last one.:
var data1 = $('#checkBoxDiv input').serialize() + '&' + 'barcodeID=' +
$('#barcodeID').val();
$('#barcodeID').val();
If you are trying to use AJAX to replace the content of the page with the result of the form submission to test.php then you would need to change the AJAX call in landing.php to:
$.ajax({
url: 'test.php',
data: data1,
type: 'POST',
success: function(response) {
$('html').replaceWith(response);
}
});
Otherwise I would suggest not using AJAX and just do a regular form submission using HTML by setting the action attribute of your form as such:
<form method="post" action="test.php">
You are passing the variables to the test.php file as a POST request, which means that the test.php file will get that data and act on it. Then after that request is successfully completed you are redirecting to test.php without passing any variables.
If you really want to submit a form (with the redirect that comes with it), do that using html:
<form action="test.php" method="post">
<input type="text" name="barcodeID" />
</form>
If you don't need the redirect, do what others have suggested and show the output on the same page instead (someDiv is the html element where you would like to display the response from test.php):
$('#searchForm').submit(function(e) {
e.preventDefault();
var data = $('#checkBoxDiv input').serialize() + '&' + 'barcodeID=' + $('#barcodeID').val();
$.post('test.php', data, function(response) {
$('someDiv').html(response);
});
});
If you must do it using JavaScript and a redirect, append a hidden dummy form to the page and submit it:
$('<form action="test.php" method="post">' +
'<input type="hidden" name="barcodeID" value="123456789" />' +
'</form>')
.appendTo('body')
.submit();

Get Ajax Previous Request with Browser Back Button

I’m facing a situation with Ajax request on back button.
I created a form which posts values and returns results via ajax request according the given filters and loads on a specific div. When I click on any of the link on page, it opens the new url as expected. On clicking on browser back button it opens the previous form page with default values. How can I enable browser state functionality so that I have results with last posted values with browser back button. Note that type of ajax is POST.
One solution I got is that to modify this form type to GET instead of POST, but this would take much time to do changes in server side code.
var page_url = $(this).attr('href');
page_url = page_url.split(':');
var page = page_url['1'];
$form = $('#form);
$.ajax({
type: 'POST',
data: $form.serialize(),
url: webroot + 'controller /action/page:'+page
}).done(function (result){
})
I want to know the possible solution.
You should set cache to false:
$.ajax({
dataType: "json",
url: url,
cache: false,
success: function (json) {...}
});
Source https://stackoverflow.com/a/25230377
you can use Jquery .unload() function or try cookies you could read it from here How do I set/unset cookie with jQuery?
Once you submitting that time dont go for new page, just hide the form elements and display new content in other div. Once you click on back button just show previously hidden div and hide current showing div

Using ajax for form submission with multiple forms generated by php on page

I have a page with multiple forms that do the same thing, acting as a like button for each post in the page, and right next to it the number of likes inside a div named "likes".$id, so I can identify where to write the likes count after the ajax call. I was trying to use jQuery ajax function, but I couldn't set what div to write the results of the function.
$.ajax({
type:'POST',
url: 'likepost.php',
data:$('#like').serialize(),
success: function(response) {
$('#like').find('#likediv').html(response);
}
});
And how would I access the data on likepost.php? I am terrible with javascript, so I hope someone could help me and explain how the jQuery function really works, because I've been copying and pasting it without really knowing what I was doing.
Would this work?
$(function () {
$("#likebutton").click(function () {
var id = $('input[name=id]'); // this is me trying to get a form value
$.ajax({
type: "POST",
url: "likepost.php",
data: $("#like"+id).serialize(), // the form is called like+id e.g. like12
success: function(data){
$("#likes"+id).html(data); // write results to e.g. <div id='likes12'>
}
});
});
});
I put this in the code but when the button is clicked, the usual post refreshing page is done. Why is that?
Making a mini-form, serializing it, and POSTing it seems like a lot of heavy lifting when all you really want to do is send the ID to the likepost.php script.
Why not just retrieve the ID and post it to the script?
First let's break down your function:Type is the type of the request we're making, you specified POST here. This means in your PHP file you'll access the data we're sending using $_POST. Next up is URL which is just the url of where you're sending the data, your php file in this case.
After that is data, that is the data we're sending to the url (likepost.php). You're serializing whatever has a ID of "like" and sending it to the php file. Finally success is a function to run once the request is successful, we get a response back from the PHP and use it in the function to output the response.
As for the multiple forms I'd recommend doing something like:
http://www.kavoir.com/2009/01/php-checkbox-array-in-form-handling-multiple-checkbox-values-in-an-array.html
Here's documentation on the stuff we talked about, if you're every confused about jquery just break it down and search each part.
http://api.jquery.com/serialize/
http://api.jquery.com/jQuery.ajax/
you can try :
function submitform(id) {
var jqxhr = $.post('./likepost.php',$("#"+id).serialize(), function(data) {
$("#"+id).find('#likediv').html(data);
}, "json")
return false;
}
in form:
<form method="post" id="likeForm" onsubmit="return submitform(this.id);">
<input..... />
<input type="submit" value="Submit" />
</form>
in likepost.php add first line:
if ($_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest") {
header("location: " . $_SERVER['HTTP_REFERER']);
exit();
}
you can see more : http://api.jquery.com/serialize/
working for me.

Load dynamic content from php on submitting a form

I have created a page "index.php" with a lot of divs and I need to refresh only one of the divs when the form is submitted.
This div loads the content from chat_window.php which is as follows:
<div id="chatbox">
<?php echo $res; ?>
</div>
<!-- Chat user input form-->
<?php echo $formchat; ?>
chat_window.php uses dynamic content - $res and $formchat from chat.php.
Everytime I post the form the content of $res and $formchat is modified and I need to reflect the same in my page which loads chat_window.php.
I used AJAX and jQuery to do the same as follows:
$(document).ready(function() {
$("#submit").click(function() {
var name = $("input#chat").val();
var dataString = "chat="+ name;
$.ajax({
type: "POST",
url: "programo/bot/chat.php",
data: dataString,
success: function() {
}
});
$("#chatwrapper").load(chat_window.php);
return false;
});
});
The index.php has a div to show the chat_window as follows:
<!-- Chat window-->
<div id="chatwrapper">
<?php include ("chat_window.php"); ?>
</div>
As per my analysis, when I post the form, $res and $formchat are getting updated in the php. But when I load the chat_window.php, it doesnot loads the modified values. It rather loads the initial static values.
(Please dont suggest setInterval() as I dont want to refresh the page automatically).
Javascript is non-blocking, so it means that the interpreter does not wait for jobs to complete before processing the next one.
In your code, $("#chatwrapper").load('chat_window.php'); is being called pretty much before the ajax request above it completes. You will need to use the ajax success event to call the reload.
Try:
$.ajax({
type: "POST",
url: "programo/bot/chat.php",
data: dataString,
success: function() {
$("#chatwrapper").load('chat_window.php');
}
});
Try moving the .load() statement into the ajax success handler:
$.ajax({
type: "POST",
url: "programo/bot/chat.php",
data: dataString,
success: function() {
$("#chatwrapper").load("chat_window.php");
}
});
The $.ajax() call is asynchronous, which means that execution does not pause waiting for the response, rather, it moves on directly to the .load() call. (Which is also asynchronous, so really you've no guarantee about the order the response from each call will come in unless you don't make the second call until the first one finishes.)
I got my work done. Though I used another way of doing it.
What I have understood after few days of R&D is that, when we submit the form to a php, the request is sent with input params. When your php file processes this request, it might be updating some global variables. It completes processing the request and returns the control back to the calling index.php page.
The important thing to notice is:
The variable updates made while processing the form submit request do not persist after the control is returned. The global php variables will only get updated when the page gets refreshed.
So, if there is a strict requirement to avoid page refresh, collect the processed data from the php in some output string and pass it back to index.php like this:
$responseString = $res . "|" . $formchat;
echo $responseString;
The success parameter of .ajax will receive this output and accordingly you can update your chat window or any other form.

Categories