Select function in ajax - javascript

My php file
$option1 = filter_input(INPUT_POST, 'key', FILTER_SANITIZE_SPECIAL_CHARS);
if(isset($option1) && !empty(option1)) {
$sql = "SELECT * FROM fantasy WHERE os_id='$option1'";
}
My ajax
function filter(){
var str = $("#advanced-search1").val();
$.ajax({
dataType: 'html',
url: "filter.php",
type: "POST",
data: {"key": str},
success: function(response){
$('#result').html(response);
}
});
}
From the above, stated that my select function id is #advanced-search1 whereas my submit button would be onclick="filter()". But it still doesn't work for me to execute the sql command in my php file. From my url browser, it stated the required select value, but it doesn't show anything in my #result div

Add event.preventDefault(); at the beginning of filter function :
function filter(event){
event.preventDefault();
var str = $("#advanced-search1").val();
$.ajax({
dataType: 'html',
url: "filter.php",
type: "POST",
data: {"key": str},
success: function(response){
$('#result').html(response);
}
});
}
However, you need to change the call also to pass the event argument :
<button onclick="filter(event);" >..</button>
Instead of :
<button onclick="filter();" >..</button>
If does not work , you have to report your PHP log as well as your HTML skeleton.

Related

Why is my AJAX data empty, even if the output of the variable before ajax is right?

$(document).ready(function () {
$("#p").change(function () {
var p_id = $(this).val();
console.log(p_id); //<-------
$.ajax({
url: "m/a/a.class.php",
method: "POST",
data: {pId: p_id},
dataType: "text",
success: function (data) {
console.log(data); //<------
}
});
});
I want to pass the my data to PHP, but when I am trying to use it for a query it is empty, so I added the console.log before and after the AJAX script.
Before it gives me the right value ("id") of the selected product, for example "9", but the console.log in the AJAX script just returns an empty value "".
What is the problem with this? Do I miss-understand the code of AJAX?
UPDATE:
case 'linie':
if (isset($_POST['pId'])){
$t = $_POST['pId'];
}
$sql = 'SELECT l.id, l.bezeichnung as bezeichnung '
. 'FROM l "
. 'LEFT JOIN p ON p.id=l.p_id '
. 'WHERE l.p_id ="'.$t.'" AND l.deleted=0 AND p.deleted=0 '
. 'ORDER BY l.bezeichnung ';
break;
This is the relevant part of my PHP code where I try to get the previous input.
UPDATE 2:
$(document).ready(function () {
$("#p").change(function () {
var p_id = $(this).val();
console.log(p_id);
$.ajax({
method: "POST",
url: "m/a/a.class.php",
data: { pID: $('#p').val() },
async: true,
dataType: 'text', (...)
When I changed it to this it worked for me :)
I guess you are playing data data.
This data
data: {produktId: p_id},
is not same as this data
success: function (data) {
Better way of writing it will be
$("#produkt").change(function () {
var p_id = $(this).val();
console.log(p_id); //<-------
$.ajax({
url: "modules/ausschuss/ausschuss.class.php",
method: "POST",
data: {produktId: p_id},
dataType: "text",
success: function (response) {
console.log(response); //<------
}
});
});
Notice the success block parameter
So this data data: {produktId: p_id}, is detail which you pass to an ajax call.
And the ajax call may or may not return response which is returned in success block as response.
Example

How to intercept POST data with Javascript

I am using this javascript function to send data to my php script (via POST) I am then using this information to retrieve data from my database and I would like to reuse the information retrieved in my JavaScript code.
Here is my code :
$(document).on("click", "#validerChoixDeCours", function() {
jQuery.ajax({
type: "POST",
url: 'myFunctions.php',
dataType: 'json',
data: {
functionname: 'proposePA',
arguments: clickedButtons
},
success: function() {
// HERE I would like to inctercept the data that my php script put in myFunctions.php produces and use it to generate content;
}
});
});
So basically, when clicking on the button #validerChoixDeCours, my code sends some data to myFunctions.php which generates a response stored in a php variable and I want to use that response in my JS code.
Thank you in advance for your help :)
Its actually quite easy!
$(document).on("click", "#validerChoixDeCours", function() {
jQuery.ajax({
type: "POST",
url: 'myFunctions.php',
dataType: 'json',
data: {
functionname: 'proposePA',
arguments: clickedButtons
},
success: function(e) {
e contains the response from the php script
}
});
});
The first parameter of success contains the response from the request. so, in this case, the 'e' variable contains the output which you can use.
Add data variable
$(document).on("click", "#validerChoixDeCours", function() {
jQuery.ajax({
type: "POST",
url: 'myFunctions.php',
dataType: 'json',
data: {
functionname: 'proposePA',
arguments: clickedButtons
},
success: function(data) {
alert(data);
}
});
});
make sure your server side code look like this
<?php
$output = "Any String or Array";
echo json_encode($output);
?>

Getting multimple results from Ajax post

Maybe this is a duplicate but I can not understand why mo code does not work. I am trying to get multiple results via Ajax/php.
This is from my php file:
$result11 = 'test1'
$result22 = 'test2';
echo json_encode(array("data1" => $result11, "data2" => $result22));
Ajax call:
$(document.body).on('submit','#sendmessage',function() {
$.ajax({
type: "POST",
url: "/send.php",
data: {par:par,kid:kid,ha:ha,sform:sform,editors:editors},
cache: false,
dataType:'json',
success: function(datax) {
alert(datax.data1);
}
});
return false;
});
Problem:
When I submit a form, the page refreshes instead of sending ajax request.
At the same time this works but I can't get multiple results from Php file:
$(document.body).on('submit','#sendmessagex',function() {
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "/send.php",
data:str,
success: function(data) {
alert(data);
}
});
return false;
});
Add a preventDefault() call to your script
$(document.body).on('submit','#sendmessagex',function(event) {
//----------------------------------------------------^^^^^
event.preventDefault();
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "/send.php",
data:str,
success: function(data) {
alert(data);
}
});
return false;
});
You have to use preventDefault() ofcourse to prevent page refresh. Then you can use the second code without datatype json. But in that case at first you have to parse the json like this way:
success: function(data){
var datax = JSON.parse(data);
//now you have object and can access like this: datax.data1, datax.data2
}
Incase you want to use first code, in php you have to set php header to define it as proper json output.
header('Content-Type: application/json');

Get data from a different php file using JQuery

I have an JQuery function which submits data from a php form to a different php file(submitForm.php). The submission works fine and there isn't any problem whatsoever, below is the handler:
submitHandler : function(){
$.ajax({
type: "POST",
cache:false,
url: "submitForm.php",
data: $('#form').serialize(),
success: function(data) {
}
});
}
Now, I want to be able get data from the submit form (submitForm.php), and load it into a different page.
This is my submitForm.php
<?php
$name="Amanda";
$age="23";
$data = array("name"=>"$name","age"=>"$age");
header("Content-Type: application/json");
echo json_encode($data);
?>
This is how my new submitHandler looks like
submitHandler : function(){
$.ajax({
type: "POST",
cache:false,
url: "submitForm.php",
data: $('#form').serialize(),
success: function(data) {
var name= html(name);
var age=html(age);
$("#message").load("newpage.php",{name:name,age:age});
}
});
}
I think I am doing it wrong, I would be grateful if somebody could correct me or give an idea as to how to do this. Thanks
It should be like this. If you want to take your returner data you should use formal parameter of success function.
submitHandler : function(){
$.ajax({
type: "POST",
cache:false,
url: "submitForm.php",
data: $('#form').serialize(),
dataType : 'json',
success: function(data) {
var name= data.name;
var age=data.age;
$("#message").load("newpage.php",{name:name,age:age});
}
});
}
Edit: Also you need dataType: 'json' line.

How to get the PHP var after Jquery $.ajax

I use $.ajax to send some data to testajax.phpenter code here where data are processing. Result of this proces is link. How to get access to this? I think about sessions or cookies. Set in session $test and get access in another files.
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'json',
success: console.log('success');
data: { json : jsonObj }
});
In testajax.php I have someting like this
echo "PDF: <a href=images/test.pdf>$dir.pdf</a>";
$test = "PDF: <a href=images/test.pdf>$dir.pdf</a>";
How to get the $test or output the echo after call $.ajax
You can use success' function to get request from PHP.
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'html',
data: { json : jsonObj }
success: function(data) {
var request = data;
console.log(data);
$('#link_container').html(data);
}
});
Your console now holds PDF: <a href=images/test.pdf>($dir content).pdf</a>.
Also the variable request holds the same result that you can use anywhere in the script.
Result is appended to #link_container.
Use the success() method for display the result.
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'json',
success: function (data){ // <= define handler for manupulate the response
$('#result').html(data);
}
data: { json : jsonObj }
});
Use below code It may help you.
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'json',
data: { json : jsonObj },
onSuccess: successFunc,
onFailure: failureFunc
});
function successFunc(response){
alert(response);
}
function failureFunc(response){
alert("Call is failed" );
alert(response);
}

Categories

Resources