Jquery Ajax call return Parsererror? - javascript

I have written Jquery Ajax call but i got Parsererror.. in following js code i have checked which select element is changed in dynamic_slct. and i have checked generic or Company and then call GnrtTemp() with pass selected Element value.. if I select generic my follwing Code(function GnrtTemp and ajax call) is working.. if i select company i got Error parsererror.. my doubt is same ajax call working Generic and is not working as company.. what is the problem? How to fix that problem i have attached my js code and also PHP code .. If i did any mistake pls correct me.. suggest to solution.?
JS
$('#dynmic_slct').on("change", "#master ,select[name='company'], select[name='generic']", function(element){
if(element.target.name == 'generic' || element.target.name == 'company') {
GnrtTemp(element.target.value);
}
});
function GnrtTemp(id){
$.ajax({
method: "POST",
url: "ajaxRequest.php",
dataType: "JSON",
data: {fn: "getTemp", id: id},
success: function(reqResult){},
complete: function (jqXHR, textStatus) {
alert(textStatus);
}
});
}
ajaxRequest.php
<?php
$finalRes = array();
if($_POST['fn'] == 'getTemp'){
$template_src = getTemp($_POST['id']);
$finalRes['result'] = $template_src;
echo json_encode($finalRes);
}
function getTemp($id){
$db = new DB();
$Query = "SELECT template_src
FROM master
WHERE refid =$id";
$qryRes = $db->query($Query);
return $qryRes;
}
?>

Related

Updating an input field with PHP vale in JavaScript

I want to update the value of an input field when I receive some information from an api. I tried using:
$('#txtFirstName').val($_SESSION['jUser']['first_name']);
But an error occurs due to the PHP not being able to run in a js file. How can I make this update otherwise? Is there a way in js to update the entire form and input fields without submitting?
I can't reload the entire window, because it will eliminate other information that the user of the website has put in.
1) put value into #txtFirstName from php script
// script.php code
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo $_SESSION['jUser']['first_name'];
}
// javascript code
function func(){
$.ajax({
type: "POST",
url: "script.php",
success: function (response) {
$('#txtFirstName').val(response);
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
2) put value into $_SESSION['jUser']['first_name'] from javascript
// javascript code
function func(){
var your_value = "some_value";
$.ajax({
type: "POST",
url: "script.php",
data: { va: your_value },
success: function (response) {
console.log("value setted to session successfully");
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
// script.php code
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['va'] !='') {
$_SESSION['jUser']['first_name'] = $_POST['va'];
echo "ok";
}
Why don't you just echo the value from php script and make an AJAX request from javascript to get the value ? This should be the recommended approach.
However, it can also be accomplished with the approach you've taken:
let first_name = <?php echo $_SESSION['jUser']['first_name']; ?>:
$('#txtFirstName').val(first_name);
For further reading, you can visit How do I embed PHP code in JavaScript?
.

Can´t send post wirth javascript to another page

I´m trying to send the variable idValue to a class called cambio_prenda.php with the following code
function reply_click(clicked_id)
{
var idValue = clicked_id;
$.ajax({
type: "POST",
url: 'cambio_prenda.php',
data:{"cambio" :idValue},
success: function(response)
{
alert("exito");
}
});
}
This code works when i use it in the same class, but when I try to call it from the another class with this code it doesn´t work
<?php
if(isset($_POST['cambio'])){
$item = $POST['cambio'];
echo($item);
}
?>

How to call php class method using ajax

I'm new to ajax. I'm trying to call get_mother method through ajax in my form textbox change event. I want to show results in datalist. below is the code i have used.
class ChildApplication extends Application{
function __construct(){
$this->login_required();
}
function get_mother(){
$mother = $_POST['mother_name'];
$mother = '%'.$mother.'%';
$db=$this->get_dbo();
$sql = "SELECT * FROM tbl_mother WHERE `mother_fname` LIKE ? ";
$results = $db->load_result($sql,array($mother));
return $results;
}
function get_child($mother){
//statements
}
}
My script is:
$(document).ready(function(){
$("#mother_name").keyup(function(event){
event.preventDefault();
var mother = $("#mother_name").val();
$.ajax({
type: 'POST',
url: 'applications/child/child.php',
data: dataString,
dataType: 'json',
success: function(){
alert("pass");
},
error: function(){
alert("error");
}
});
});
});
none of alerts are displayed. please help me to solve the problem
I guess that "dataString" variable is not defined.
I think that you should replace the value of "data" like this:
data: {mother_name: mother},
Also make sure that the function get_mother() is called in "applications/child/child.php"
$ChildApplication = new ChildApplication;
$ChildApplication->get_mother();

Jquery Ajax get not passing values

This is driving me crazy...
$(document).on("click",".load",function(b){
b.preventDefault();
$.get("/url/get.php",{
id: 123
},
function(a){
$("#result").html(a);
})
});
This loads the page as expected but when I do print_r($_GET) it shows it's empty...
Any ideas?
Backend:
if (isset($user) == false) {
session_start();
$path_to_root = "../";
require($path_to_root."require/loads.php");
$PDO = new PDO(DB_CONN, DB_USERNAME, DB_PASSWORD);
$user = new User($PDO);
}
$i = 0;
print_r($_GET);
Please, try this way, using done() function:
$(document).on("click",".load",function(b){
b.preventDefault();
$.get("/url/get.php",{
id: 123
}).done(
function(a){
$("#result").html(a);
})
});
As said in jquery docs that´s the way to send payload data with GET.
Anyway, you can also use ajax:
$.ajax({
url: "/url/get.php",
type: "get", //send it through get method
data:{id:123},
success: function(response) {
$("#result").html(a);
},
error: function(xhr) {
$("#result").html("ERROR");
}
});
Anyway, if you are still viewing those errors, the problem souhld be in your backend as #AmmarCSE commented.
Hope it helps
EDIT some text about the difference between jquery methods success() and done() :
jQuery ajax success callback function definition
please try this
$(document).on("click",".load",function(b){
b.preventDefault();
$.ajax({
method:'get',
url : '/url/get.php',
data : '{id:123}',
dataType: 'json', //json,html any you will return from backend
success:function(a){
$("#result").html(a);
}
})
});
Try using
$data = file_get_contents("php://input");
$r = json_decode($data);
instead of $_GET in you php file, then print $r

AJAX take data from POST with PHP

i have a little problem with my script.
I want to give data to a php file with AJAX (POST).
I dont get any errors, but the php file doesn't show a change after AJAX "runs" it.
Here is my jquery / js code:
(#changeRank is a select box, I want to pass the value of the selected )
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success') },
error: function (err)
{ alert(err.responseText)}
});
});
});
PHP:
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
header('Location:/user/'.$user);
die();
When i run the script, javascript comes up with an alert "success" which means to me, that there aren't any problems.
I know, the post request for my data is missing, but this is only a test, so im planning to add this later...
I hope, you can help me,
Greets :)
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success: ' + JSON.stringify(msg)) },
error: function (err)
{ alert(err.responseText)}
});
});
});
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
echo json_encode($user);
This sample code will let echo the username back to the page. The alert should show this.
well your js is fine, but because you're not actually echoing out anything to your php script, you wont see any changes except your success alert. maybe var_dump your post variable to check if your data was passed from your js file correctly...
Just return 0 or 1 from your php like this
Your PHP :
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
{
$_SESSION["user"] = $user;
echo '1'; // success case
}
else
{
echo '0'; // failure case
}
Then in your script
success: function (msg)
if(msg==1)
{
window.location = "home.php"; // or your success action
}
else
{
alert('error);
}
So that you can get what you expect
If you want to see a result, in the current page, using data from your PHP then you need to do two things:
Actually send some from the PHP. Your current PHP redirects to another URL which might send data. You could use that or remove the Location header and echo some content out instead.
Write some JavaScript that does something with that data. The data will be put into the first argument of the success function (which you have named msg). If you want that data to appear in the page, then you have to put it somewhere in the page (e.g. with $('body').text(msg).

Categories

Resources