Ajax post not appending data to URL - php

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.

Related

How to redirect with jquery ajax and php response

I have the following ajax and php. I want to redirect the user to a another page depending on the result i output with a php script. Php successfully returns the json to browser, but i am somehow not able to get the response url back into the js ajax to make the redirection. It always redirects me to /undefined. What is wrong with my code?
jQuery.ajax({
type: "POST",
url: "../custom_scripts/anmeldung_zurueckziehen.php",
data: { anmeldung_id: anmeldung_id },
success: function(response){
//alert (response.redirect);
if (response.redirect) {
window.location.href = response.redirect;
}else {
// Process the expected results...
}
}
})
This is the php.
$arr = array ('redirect'=>true,'redirect_url'=>'https://mypage.de/no-
access/');
echo json_encode($arr);
Wish this helps:
jQuery.ajax({
type: "POST",
url: "../custom_scripts/anmeldung_zurueckziehen.php",
data: { anmeldung_id: anmeldung_id },
success: function(response){
response = JSON.parse(response);
if (response.redirect) {
window.location.href = response.redirect_url;
}else {
// Process the expected results...
}
}
})
You are missing dataType property for ajax to decode the response:
jQuery.ajax({
type: "POST",
dataType: "json",
url: "../custom_scripts/anmeldung_zurueckziehen.php",
data: { anmeldung_id: anmeldung_id },
success: function(response) {
//console.log(response.redirect);
if (response.redirect) {
window.location.href = response.redirect_url;
} else {
// Process the expected results...
}
}
})
Two ways to do this
First way is - Either use JSON headers in Php like below
header('Content-Type: application/json');
Above will return JSON string with json headers and jquery will automatically parse it for you and your callback function will have proper object.
Second Way is - in javascript use JSON.parse like below
JSON.parse(response);
Above will basically parse your json string into Javascript object
Make sure you don't parse when you have set JSON headers from backend.

php returns empty variables on ajax post

I am trying to get the hang of php and ajax post. I am posting simple user input via text box to a php page. The php page takes the user input, counts words and sends it back as response. However it can't receive the data, comes back saying. Why is this how do I fix it?
This is my jQuery ajax post code
var dataString = name;
$.ajax({
type: "POST",
url: "test_get.php",
data: dataString,
success: function(response) {
alert(response);
}
});
return false;
});
});
This is my PHP code
// if data are received via POST, with index of 'dataString'
if (isset($_POST['dataString'])) {
$str = $_POST['dataString']; // get data
echo "The string: '<i>".$str."</i>' contains ". strlen($str). ' characters and '. str_word_count($str, 0). ' words.';
}
else echo 'There is no data!';
Your data argument is incorrect.
var dataString = name;
$.ajax({
type: "POST",
url: "test_get.php",
data: {"dataString" : dataString },
success: function(response) {
alert(response);
}
});
Read the jQuery $.ajax docs for more info.
You probably need to change:
data: dataString,
To
data: "dataString="+dataString,
Because a HTTP POST still runs off of key/value pairs.

How to decode a json object sent through jquery ajax method in php file?

This is the jquery ajax part in which i have sent json data to the php file.
$(function () {
$('form').submit(function () {
var fields = $(this).serializeArray();
var ans_json = JSON.stringify(fields);
console.log(ans_json);
$.ajax({
url: "results.php",
type: "POST",
data: ans_json,
dataType: "json",
success: function (result) {
console.log(result);
}
});
return false;
});
});
Now i want to use this json data sent to the php page.How can i do it? I have done it this way but it returns null.
<?php
echo json_decode('ans_json');
?>
I have a set of 10 questions which need to be answered. 3 questions were answered so got the below result.This is what i got in my console.
[{"name":"answer_9","value":"a"},{"name":"answer_10","value":"a"}] quizzes.php:14
null
You don't need to decode any JSON string at server-side if you encode properly your parameters.
You can use .serialize() to do the form serialization for you, and it's ready to send.
$(function () {
$('form').submit(function () {
var serialized = $(this).serialize();
$.ajax({
url: "results.php",
type: "POST",
data: serialized,
...
});
return false;
});
});
Your parameters will be available in your $_POST as in any normal POST request. For example,
$ninth_answer = $_POST["answer_9"];
You need to decode the POST variable. Currently you're decoding just a string which even isn't valid JSON.
<?php
$json_arr = json_decode($_POST['my_json'], true);
var_dump($json_arr);
echo "First name in json is:". $json_arr[0]['name'];
?>
and edit your javascript to reflect following:
This posts my_json parameter with your json as an value. This makes it easy for PHP to recieve it using $_POST.
$.ajax({
url: "results.php",
type: "POST",
data: {"my_json": ans_json},
dataType: "json",
success: function (result) {
console.log(result);
}
});
I suggest to read a little about those things:
http://api.jquery.com/jQuery.ajax/
http://ee1.php.net/manual/en/function.json-decode.php

Jquery AJAX response not working

For some reason this jQuery function is not working properly. Here's my code... the response div is not updating with my response.
WHEN AJAX FUNCTION IS CALLED
if ($action == 'sort') {
echo 'getting a response';
return 0;
}
JQuery FUNCTION
function sort() {
$.ajax({
type: "POST",
url: "contributor_panel.php?action=sort",
data:"sort_by=" + document.getElementById("sort_by").value +
"&view_batch=" + document.getElementById("view_batch").value,
success: function(html){
$("#ajaxPhotographSortResponse").html(html);
}
});
}
DIV TO REPLACE
<div id="ajaxPhotographSortResponse"></div>
Move the action=sort into the data property of the $.ajax function. You're making a POST request, but appending data onto your query string like a GET request. Data only appends to the query string if it's a GET request.
Example:
$.ajax({
type: "POST",
url: "contributor_panel.php",
data: {action:'sort', sort_by: $('#sort_by').val(), view_batch: $('#view_batch').val()},
success: function(html){
$("#ajaxPhotographSortResponse").html(html);
}
});
http://api.jquery.com/jQuery.ajax/
Instead of concatenating the arguments you are passing to your server side script I would recommend you using the following syntax. Also if you already use jQuery you no longer need the document.getElementById function:
$.ajax({
type: "POST",
url: "contributor_panel.php?action=sort",
data: { sort_by: $("#sort_by").val(), view_batch: $("#view_batch").val() },
success: function(html){
$("#ajaxPhotographSortResponse").html(html);
}
});
or even shorter using the .load() function:
$('#ajaxPhotographSortResponse').load('contributor_panel.php?action=sort',
{ sort_by: $("#sort_by").val(), view_batch: $("#view_batch").val() });

Can a Jquery Ajax Call Accept an Object on Succes from PHP?

I'm writing a simple ajax function and looking to populate two text input fields with the 'success' results. I'm wondering what my php syntax has to be to return an object.
Here is my Javascript function
function editModule(a){
data = {moduleNum:a}
$.ajax({
type: 'POST',
data: data,
url: 'includes/ajaxCalls.php',
success: function(data) {
alert(data['title']); // <-- This is where I'm not sure what to return from php
}
});
}
Here is my php doc (so far, this is where I need to know how to return an object)...
<?php
$data = array('title'=>'this');
echo json_encode($data);
When I run the function I just get the alert "undefined".
Suggestions?
Thanks,
-J
Try this. You can specify that you're expecting a JSON object and then you can interpret data accordingly.
function editModule(a){
data = {moduleNum:a}
$.ajax({
type: 'POST',
data: data,
dataType: 'json',
url: 'includes/ajaxCalls.php',
success: function(data) {
alert(data.title);
}
});
}
I have returned JSON data from the server via a jQuery Ajax call, not in PHP but it should be the same. As long as you set the content-type of your response to application/json jQuery should consider the responseText as a JSON string. Alternatively you can also set dataType: "JSON" in your Ajax call which tells jQuery that you expect JSON.
Your php page returns: {"title":"this"} in this case.
So you can reference the result with:
alert(data.title);
You may need to specify the data type:
function editModule(a){
data = {moduleNum:a}
$.ajax({
type: 'POST',
data: data,
url: 'includes/ajaxCalls.php',
dataType: 'json',
success: function(data) {
alert(data['title']); // <-- This is where I'm not sure what to return from php
}
});
}

Categories