So I am working on a project in which I have to pass some form data to a database without reloading the page using Ajax. But the $_POST variable in the PHP file is always empty. I do know that I am actually getting the data from the form since I can print and it looks okay in the javascript code:
$(document).ready(function () {
$('form').on('submit', function (event) {
// prevent page from refreshing
event.preventDefault();
$.ajax({
url: 'post.php',
type: 'POST',
data: {name: 'tony'},
dataType: 'json',
success: function (response) {
$('#message').html(response);
}
});
//return false;
});
});
And this is the php code:
<?php
//var_dump($_POST);
if (isset($_POST['name'])) {
$name = $_POST['name'];
echo $name;
} else {
echo "error";
}
?>
Use this code instead, you won't need to manually define the parameters to be sent because it will be automatically set by FormData():
$('#form').submit(function(event) {
event.preventDefault();
var data = new FormData(this);
$.ajax({
url: "post.php",
type: "POST",
data: data,
contentType: false,
processData: false,
success: function(result) {
console.log(result);
}
});
});
So, turns out I am just stupid.. It was actually working properly after all but I was checking if it works the wrong way. I was actually navigating to the php file by entering the url expecting to see my data printed on the php page. Finally, I checked the response of the POST request and it was working just fine.Thank you for your answers and I apologize for wasting your time.
try this,
$('form').on('submit', function (event) {
// prevent page from refreshing
event.preventDefault();
$.ajax({
url: 'post.php',
method: 'POST',
data: {name: 'tony'},
success: function (response) {
$('#message').html(response);
}
});
});
Related
I am trying to get my search bar working, however I am having issues with an ajax post.
For whatever reason, none of the data is being appended to the URL. I have tried various things with no success. I am attempting to send the data to the same page (index.php).
Here is my jquery:
$(function(){
$(document).on({
click: function () {
var tables = document.getElementsByTagName("TABLE");
for (var i = tables.length-1; i >= 0; i-= 1) {
if (tables[i]) tables[i].parentNode.removeChild(tables[i]);
}
var text = $('#searchBar').val();
var postData = JSON.stringify({ searchTerm: text });
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: postData,
success: function() {
alert("Test");
}
});
}
}, "#searchButton");
});
And here is the php which I have with index.php:
<?php
require('course.php');
if(isset($_POST['searchTerm'])) {
echo $_POST['searchTerm'];
}
?>
No matter what I try, I am unable to get anything to post. I have checked the network tab in chrome, and I'm not seeing anything that indicates it's working correctly.
Any ideas?
EDIT:
I've changed my code to this, and it seems I'm getting closer:
$(document).on({
click: function () {
$("TABLE").remove()
var text = $('#searchBar').val();
$.ajax({
type: 'GET',
url: 'index.php',
dataType: 'text',
data: { searchTerm: text },
success: function() {
alert("Test");
}
});
}
}, "#searchButton");
And:
<?php
require('course.php');
if(isset($_GET['searchTerm'])) {
echo $_GET['searchTerm'];
}
?>
Now I am getting ?searchTerm=theTextIEnter as expected, however it's still not being echoed in index.php.
Do not use JSON.stringify() to convert object to string. data passed to $.ajax must be an object and not JSON.
For whatever reason, none of the data is being appended to the URL.
You are making a POST request. POST data is sent in the request body, not in the query string component of the URL.
If you change it to a GET request (and inspect it in the correct place, i.e. the Network tab of your browser's developer tools and not the address bar for the browser) then you would see the data in the query string.
This will work for you use data: { postData } on place of data:postData and you will receive your data in $_POST['postData']
$(function(){
$(document).on({
click: function () {
var tables = document.getElementsByTagName("TABLE");
for (var i = tables.length-1; i >= 0; i-= 1) {
if (tables[i]) tables[i].parentNode.removeChild(tables[i]);
}
var text = $('#searchBar').val();
var postData = JSON.stringify({ 'searchTerm' : text });
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: { postData },
success: function(data) {
alert(data.searchTerm);
}
});
}
}, "#searchButton");
});
In index.php
<?php
if(isset($_POST['postData'])) {
echo $_POST['postData'];
die;
}
?>
If you want to send data via the URL you have to use a GET request. To do this, change the type of the request to GET and give the object directly to the data parameter in your jQuery, and use $_GET instead of $_POST in your PHP.
Finally note that you're not returning JSON - you're returning text. If you want to return JSON, use json_encode and get the value in the parameter of the success handler function.
Try this:
$(document).on({
click: function () {
$('table').remove();
$.ajax({
type: 'GET',
url: 'index.php',
dataType: 'json',
data: { searchTerm: $('#searchBar').val() },
success: function(response) {
console.log(response.searchTerm);
}
});
}
}, "#searchButton");
<?php
require('course.php');
if(isset($_GET['searchTerm'])) {
echo json_encode(array('searchTerm' => $_GET['searchTerm']));
}
?>
Remove dataType: 'json', from your AJAX. That is all.
Your response type is not JSON, yet by setting dataType: 'json' you're implying that it is. So when no JSON is detected in the response, nothing gets sent back to the method handler. By removing dataType it allows the API to make an educated decision on what the response type is going to be, based on the data you're returning in the response. Otherwise, you can set dataType to 'text' or 'html' and it will work.
From the manual:
dataType: The type of data that you're expecting back from the server.
This is NOT the type of data you're sending/posting, it's what you're expecting back. And in your index.php file you're not sending back any JSON. This is why the success() method is not satisfying. Always set the dataType to the type of data you're expecting back in the response.
With POST Request:
Please comment below line in your code:
//var postData = JSON.stringify({ searchTerm: text });
And use below ajax code to get the post-data:
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: { searchTerm: text },
success: function() {
alert("Test");
}
});
With GET Request:
You can convert your data to query string parameters and pass them along to the server that way.
$.ajax({
type: 'GET',
url: 'index.php?searchTerm='+text,
dataType: 'json',
success: function(response) {
alert(response);
}
});
In response, You can get the data with alert, so you may get idea about the same.
I am using ajax for sending to the server that a checkbox is checked and now other inputs fields need to be required:
EDIT: ok i will change the question to be more clarified.
i have this code:
$(document).ready(function() {
$('#button_ajax').click(function() {
var request = jQuery.ajax({
type: 'get',
url: 'http://orenmizrah.git/nir1.php',
data: {'id1': $('#input_text').val()},
async: true,
success: function(){
console.log("sent");
}
});
});
and now i check that i got the info in $_GET['id1'] with php code and if $_GET['id1'] is set, echo something to the browser.
the problem is that $_GET['id1'] is set but there is no output to the browser.
what i should do?
No output is shown in the browser because nothing is done to show it.
$(document).ready(function() {
$('#button_ajax').click(function() {
var request = jQuery.ajax({
type: 'get',
url: 'http://orenmizrah.git/nir1.php',
data: {'id1': $('#input_text').val()},
async: true,
success: function(data){
console.log(data); // outputs the returned data to the console
}
});
});
I am having problem with response data. I want to use response data in my php file. I want to assign them to a php variable.
here is the ajax code in insert.php file.
function change(){
var tp=$('#choose').val();
var country_val=$('#country_filter').val();
//alert(country_val);
//var country_val=$('#country_filter').val();
$.ajax({
type: "POST",
url: "filter.php",
data: { name: tp, country:"test"},
success:function( data ) {
alert(data);
}
});
}
here is php code in filter.php
if($_REQUEST["name"]){
$lvl = $_REQUEST["name"];
//global $lvl;
echo $lvl;
}
Now I want to use the response data to be assigned to a php variable in insert.php file. How may I do that?
Please help.
Send the data to insert.php file using ajax, instead of alerting it.
change success function to
$.ajax({
type: "POST",
url: "filter.php",
data: { name: tp, country:"test"},
success:function(response) {
var res = response;
$.ajax({
type: "POST",
url: "insert.php",
data: { res: res },
success:function(data){
alert(data);
}
});
});
In insert.php,
use this to get the variable.
$var = $_POST['res'];
If insert.php calls filter.php with ajax and then returns a value. you cannot apply that javascript var to a php var in the insert.php. That is because the Php script runs on the server when the page is loaded, and the javascript runs locally on the users computer. To apply anything to a php variable you will have to reload the page.
I have a AJAX script which sends value to PHP script and to retrieve the value from the PHP script. The part where the script sends the value is working fine. Its the problem with the retrieving values. I am not able to figure out what is wrong.
AJAX code:
$(document).ready(function() {
$("#raaagh").click(function() {
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data) {
console.log(data);
$.ajax({
url:'ajax.php',
data: data,
dataType:'json',
success:function(data1) {
var y1=data1;
console.log(data1);
}
});
}
});
});
});
PHP code:
<?php
$userAnswer = $_POST['name'];
echo json_encode($userAnswer);
?>
Please check whether "name" is posted before assigning the value to $userAnswer.
Both ajax scripts are sending to "ajax.php". In first ajax request "name" is posted, but in 2nd ajax request "name" is not posted.
To see warnings and errors, enable error reporting in php.
<?php
//To enable error reporting
ini_set('display_errors',true);
error_reporting(E_ALL);
data: {name: 145}
try this hope this will work.
Your nested AJAX call does not have the request type specified. The default is GET but your ajax.php is trying to find a POST.
$(document).ready(function() {
$("#raaagh").click(function() {
$.ajax({
url: 'ajax.php',
type: "POST",
data: ({name: 145}),
success: function(data) {
console.log(data);
$.ajax({
url:'ajax.php',
type: "POST", //<-- added here
data: {name:data}, //<-- also required for POST
dataType:'json',
success:function(data1) {
var y1=data1;
console.log(data1);
}
});
}
});
});
});
Set type:'POST' inside the second ajax call and try to use data1[0]. Also remember that you are sending a json string (that comes from the first ajax) with the second request. Basically you are encoding an encoded value,so when you receive the post value you should json_decode the post value
I was wondering if this was making an asynchronous request...write now Im using:
<script type='text/javascript'>
$(document).ready(function() {
var ktitle = $('.hiddentwo').text();
$('div#tab2').load('morefour.php?title=' + encodeURIComponent(ktitle));
});
</script>
what Im doing though is adding text in the first, into the database, on the current php file (addtext.php). Im passing the Id of the current document to the morefour.php and that is loading the added text on the second tab...the thing is, Im having to refresh to see the content again. Im running on localhost btw.
For more clarity, Im running another jquery script that on clicks, retrieves this data to send it to a php file to enter into a database
$(".button").click(function() {
var content = $(this).siblings().outerHTML();
$.ajax({
async: false,
type: "POST",
url: "tosqltwo.php",
data: {
content: content
}
});
});
$(function(){ //shorthand of $(document).ready
$('div#tab2').html($.ajax({
type: "GET", //if you are doin $_GET['title'] in morefour.php
url: "morefour.php",
data : {title:ktitle},
dataType: 'html', //i am not sure about this part
async: false
}).responseText)
});
or you can try
$(function(){
$.ajax({
url : 'morefour.php',
data : {title:ktitle},
type:'GET',
dataType:'html',
success: function(data) {
$('div#tab2').html(data);
}
});
});
you can use $.ajax function with async to false.
$.ajax({
async: false,
url : 'morefour.php',
data : 'title=' + encodeURIComponent(ktitle),
success: function(data) {
$('div#tab2').html(data);
}
});