Sorry if this is a silly question but I'm completely new to AJAX and I'm wondering why my code is not working like I want..
I have the following:
an Ajax Call looking like that:
$.ajax({
type: "POST",
url: "/newnote.php",
data: {
content: content
},
success: function() {
}
});
and on the beginning of the page newnote.php (which is exactly the one, where the ajax-call is on, I have the following PHP:
if(!empty($_POST)){
header("Location:index.php");
}
But the php on the beginning of the page is not executed, of course, because the site seems not to be reloaded, but, when looking in developer tools under "network", i see that there is a post request on newnote.php with the values I want. But the question is: How can I access them? So for example, if I post the following data: content: "test", that I can write in PHP sth. like <?=$_POST['content'];?>... So how can I access the $_POST-Data from AJAX? Do I need to refresh the page or how does this work?
Thanks for your help
after exchanging I now got the question:
to access to your code you must use the callback of your ajax call
success: function(result){
$("#div1").html(result); // here you put the content that echoes your php inside your div1 on the actual page without reload
}
On the php side where the content is posted you must echo something that will be caught by this ajax call
Related
I have a form, running through jquery validation which then submits via ajax to a PHP script to handle backend functions. Ajax collects form values through serializeArray() and looks to do the job. Script fires and data is sent through(I think) to PHP. I've tried probably close to 100 combinations to receive the data at the PHP side but with no luck. I'm convinced this must be simple, something I've overlooked. Code for the ajax is below, along with a screenshot of developer tools showing what's being sent.
No matter what I try on the PHP side, I either get an empty array, NULL through $_POST/$_GET. I've tried json_decode, parsing the string, var_dump etc.
var data=$(form).serializeArray();
$.ajax({
cache: false,
type: "POST",
dataType: "JSON",
url: "process/create_site.php",
data: data,
success: function(response) {
console.log(response);
//$(form).html("<div id='message'></div>");
//$('#message').html("<h2>Your request is on the way!</h2>")
// .append("<p>someone</p>")
// .hide()
// .fadeIn(1500, function() {
// $('#message').append("<img id='checkmark' src='images/ok.png' />");
// });
}
});
I managed to get to the bottom of this, after an embarrassing amount of time. I'd like to post the simple reason here to help others.
The entire JS block was wrapped in $(document).ready(function(){
which was causing the values to be stripped when posting to the PHP.
I can't find any documentation or answer to a question with a similar scenario - so here it is!
I know this question has been asked before several times on this forum, but I think I am missing something. Or maybe it is because I don't know JSON/AJAX that well.
Here is the thing.
I got some javascript/JQuery code on a page, say on index.php, (not yet in a seperate JS file) which let you put any number in an array from 1 to 10. If it's already in it, it will be removed if clicked again.
Now I want to pass that JS array to PHP, so I can create tables with it.
Here's what I have done.
$(".Go").click(function() {
var enc = JSON.stringify(tableChoice);
$.ajax({
method: 'POST',
url: 'calc.php',
data: {
elements: enc
},
success: function(data) {
console.log(enc);
}
});
});
And in my calc.php I got this to get the values to PHP.
<?php
$data = json_decode($_POST['elements'],true);
echo $data;
?>
Now here comes the noob question:
If I click my (.Go) button, what really happens?
Because the console.log let's me see the correct values, but how do I access it? The page (index.php) doesn't automatically go to the calc.php.
When I use a <form> tag it will take me there, but it shows this error:
Undefined index: elements
I am sure I am looking at this the wrong way, interpreting it wrong.
Can someone please help me understand what it is I should be doing to continue with the JS array in PHP.
With a XHR request you don't do a page reload. With your $.ajax method you post data to the server and receive information back. Since you can see information in your console, the success method is triggered.
You might want to take a look at your DevTools in for example Chrome. When you open your Network tab and filter on XHR you see what happens. You can inspect your XHR further by looking into the data you've send and received.
So my question to you is: what do you want to happen onSuccess()? What should happen with the data you receive from your backend?
In JavaScript:
$(".Go").click(function() {
var enc = JSON.stringify(tableChoice);
$.ajax({
method: 'POST',
url: 'calc.php',
data: {
"elements="+enc;
},
success: function(data) {
console.log(data);// You can use the value of data to anywhere.
}
});
});
In PHP:
<?php
if(isSet($_POST[elements]))
{
$data = json_decode($_POST['elements'],true);
echo $data;
}
else
{
echo "Elements not set";
}
?>
I've started working with ajax a little lately, but I'm having trouble with something I feel is incredibly simple: storing a JS variable in PHP.
Say I want to store a zip code (assigned with Javascript) and pass that to a PHP variable via AJAX: Why doesn't this work?
Keeping it simple for demonstration purposes, but this is the functionality I desire..
zipCode.js:
$(document).ready(function() {
var zip = '123456';
$.ajax({
url: 'zip.php',
data: {zip_code:zip},
type: 'POST'
});
});
zip.php:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="zipcode.js"></script>
</head>
<body>
<?php
echo $_POST['zip_code'];
?>
</body>
</html>
An error: "Notice: Undefined index: zip_code" is all that is returned. Shouldn't "123456" be echo'd out?
You are supposed to put this:
<?php
// query database before echoing an associative array of `json_encode()`ed data if a response is needed
echo json_encode(array('zip_code' => $_POST['zip_code']);
?>
on a separate page, that is not an HTML page. AJAX just sends to that page, so you can use it and echo it out, making database queries before that, or what have you. Upon success you will see the result of your echo as the argument passed to the success method in this case if you used data as the argument the result for zip_code would be held in data.zip_code. Also, set your dataType:'JSON' in $.ajax({/*here*/}).
Here:
var zip = '123456';
$.ajax({
url: 'zip.php',
data: {zip_code:zip},
type: 'POST',
dataType: 'JSON',
success: function(data){
// in here is where you do stuff to your page
console.log(data.zip_code);
}
});
When you load the page, a call is being made to the server for zip.php, however that request is in no way linked to the page you're currently viewing.
If you look at the response to your ajax request - you'll see a copy of the page with the correct zip code echo'd
The actual answer then depends on what exactly you're trying to do (and a less simplified version of the code) to give you the best option.
The current setup you have doesn't make sense in practice
That is not how AJAX works. Thake a look at the example below. It will make an AJAX post to handle_zip.php and alert the results (Received ZIP code 123456)
start_page.html:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="zipcode.js"></script>
</head>
<body>
This is just a static page.
</body>
</html>
zipcode.js:
$(document).ready(function() {
var zip = '123456';
$.ajax({
url: 'handle_post.php',
data: {zip_code:zip},
type: 'POST',
success: handleData
});
});
}
function handleData(data) {
alert(data);
}
handle_post.php:
<?php
die ('Received ZIP code ' . $_POST['zip_code']);
As others have mentioned, it sounds like you're expecting the two bits of code to run at the same time. The reality is that:
zip.php will be parsed on the server (and resulting in the error)
Server will then serve up the HTML to the browser (which will have a blank body due to the $_POST not existing when the PHP was parsed)
browser will see the javascript .ready() and run that code
server will handle the POST request to zip.php, and generate the HTML you're expecting. It'll be returned in the AJAX response, but as you're not handling the response, nothing is shown in the current session. (you can see the POST response using any of the common web developer tools)
Remember, PHP runs on the server, then any javascript runs on the client. You're also missing the step of handling the response from the request you made in your javascript.
try this to give you better idea of what's happening.
$.ajax({
url: 'zip.php',
data: {zip_code:zip},
type: 'POST'
});.done(function(data ) {
console.log(data)
});
In your code, the server is creating the page first, so no javascript is run yet, therefore it creates an error because $_POST['zip_code'] doesn't exist. Then it sends this page to your browser and you can see that. At this point is when your browser executes the javascript, it sends the request again, now with POST data, the server should return the response of the request and you should be able to see it in the console.
You could make this 2 separate pages, one for viewing the page, and anotherone for processing the ajax request, or if for your application you want to do it in the same page, you would need an if statement to get rid of that error, something like
if(isset($_POST['zip_code'])){
echo $_POST['zip_code];
}
First the code below works, but truth be told i don't know why :) it just worked after many trial and errors
I need the $_POST data submitted through the #filter-form, for loading the page as action1 function will require $_POST data.
If i remove +data or .html(data) it doesn't work anymore.
Also if i change url:"..." it does not work anymore either and i don't understand why as i don't need to to anything here, all i need is to load this page.php page and pass the $_POST so that it can output properly.
My QUESTION is, WHY does it work ? (i want to understand why putting +data or html(data) is so important to make sure $_POST is passed) and how can i make it more proper ?
Thanks for your help
<script type="text/javascript">
$("#filter-form").submit(function(event) {
$.ajax({
type: "POST",
url: "includes/page.php?action=action1",
//Specify the datatype of response if necessary
data: $("#filter-form").serialize(),
success: function(data){
alert("succeess");
$("#tableresult").load("includes/page.php?action=action1"+data).html(data);
}
});
event.preventDefault();
return false;
});
</script>';
You don't need to use .load() at all. It should be:
success: function(data) {
alert("success");
$("#tableresult").html(data);
}
This takes the response that the AJAX server returned, which should be HTML code, and puts it into the tableresult element.
The way you had it written, you're calling the server twice, which doesn't seem right.
I am working on an instant search thing and when I submit the form search-form it is going to make an ajax post to PHP. It sends and everything but then the PHP page says that the variable has no value but the data is clearly being posted.
$('#search-form').submit(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "Search.php",
cache: false,
data: $("#search-form").serialize(),
success: function(data) {
alert($("#search-form").serialize());
$("#searched").fadeIn("fast");
$("#results").empty();
$("#results").append(data);
}
});
return false;
});
Make sure you have a console opened up in your browser, Firefox: bugzilla, Chrome and IE have a built-in. It shows you what is happening in asynchronous requests.
in your php file at the top do this:
var_dump($_POST);
//OR DO THIS:
// print_r($_POST);
Then look at your browser console to see what the response is. It should spit out an array. and you can see what the name of your data is. This is the quickest way to debug any ajax request.
Also, don't forget that you serialized the data with .serialize();