passing data from js file to php using jquery ajax - javascript

ajaxcheck.js
var val = "hai";
$.ajax(
{
type: 'POST',
url: 'ajaxphp.php',
data: { "abc" : val },
success :function(data)
{
alert('success');
}
}
)
.done(function(data) {
alert("success :"+data.slice(0, 100));
}
)
.fail(function() {
alert("error");
}
);
ajax.html
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript" src="ajaxcheck.js"></script>
<title>ajax request testing</title>
</head>
<body>
</body>
</html>
ajaxphp.php
<?php
$v_var = $_POST["abc"];
print_r($_POST);
if(isset($_POST["abc"]))
{
echo $v_var;
}
else
{
echo "Data not received";
}
?>
When I run the ajax.html file ,I get success alert. But when I run ajaxphp.php file it shows notice like:
undefined index abc
Why is that the data is not received in $v_var ? where i am mistaking ?please help.

Actually the ajaxphp.php file is used to receive the data from the
post method and i will give response .
In First case by using ajax post method it will call to ajaxphp.php file.
In Second case your using direct file call without any post data(that's way it shows error)
Try this
var val = "hai"
$.post( "ajaxphp.php", {'abc':val}function( data ) {
alert( "Data Loaded: " + data );
});

jQuery expects an object as data, remove the double-quotes:
data: { abc : val }

Related

How to correctly parse Json from php json_encode

I want to parse json data created by PHP json_encode in my front end app, i can't do this:
var data= '<?php echo $jsonarr; ?>';
As it is a Cordova app.
Here is my php code:
<?php
$arr_login= array("lname"=>"$rowlname","email"=>"$rowemail","fname"=>"$rowfname","mobile"=>"$rowmobile");
echo json_encode($arr_login);
?>
My ajax code:
$.ajax({
type:"POST",
url: url,
data:data,
success: function(data){
var res = $.trim(data);
if (res == "Password is inccorrect" || res== "Email is inccorrect") {
$("#errmsg").html(data);
}
else{
var response= JSON.parse(data);
alert(response);
//window.open("dashboard.html?sess=logined&","_self");
}
}
});
Now if I alert data it gives me the valid JSON format as sent by PHP, but I need to convert it to javascript object so I can use it in DOM but JSON.parse gives this error in the console:
VM236:14 Uncaught SyntaxError: Unexpected token / in JSON at position 147
var response = JSON.parse(JSON.stringify(data));
Why do you alert all the json variable which is definetely an object?
I have simulated your process, as #Anik Anwar 's mention JSON.stringify is the solution
<?php
$rowlname = "row";
$rowemail = "email";
$rowfname = "rowfname";
$rowmobile = "rowmobile";
$arr_login= array("lname"=>"$rowlname","email"=>"$rowemail","fname"=>"$rowfname","mobile"=>"$rowmobile");
$jsonarr = json_encode($arr_login);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script>
var data = '<?php echo $jsonarr ?>';
</script>
<script>
$.ajax({
type: "POST",
url: '/',
data: data,
dataType: 'json',
contentType: 'application/json',
success: function (data) {
var res = $.trim(data);
var response = JSON.parse(JSON.stringify(data));
window.alert(response.lname);
}
});
</script>
</body>
</html>

AJAX data variable not posting to PHP script, yet $_POST is set

This is driving me crazy. I'm trying to post a variable to a PHP script using AJAX but while I can verify that $_POST is set, the varibale remains undefined.
I've used almost identical code elsewhere and it works fine - I just cant see what the problem is here.
Here is a very stripped down version of the code -
The JS
$(function(){
$('#load_more_comments').click(function(){
var newLimit = 40;
$.ajax({
url: "scripts/load_comments.php",
data: { limit: newLimit },
type: "post",
success: function(result){
// execute script
},
error: function(data, status, errorString)
{
alert('error');
}
});
return false;
});
});
The PHP
if (isset($_POST)) {
echo "POST is set";
if (isset($_POST['limit'])) {
$newLimit = $_POST['limit'];
echo $newLimit;
}
}
UPDATE
var_dump($_POST) returns array(0) { } so I know that AJAX is definitely is not posting any values
Using slightly modified version of the above I am unable to reproduce your error - it appears to work fine.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
if( isset( $_POST['limit'] ) ){
echo $_POST['limit'];
}
exit();
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<script src='//code.jquery.com/jquery-latest.js'></script>
<script>
$(function(){
$('#load_more_comments').click(function(){
var newLimit = 40;
$.ajax({
url: location.href, //"scripts/load_comments.php",
data: { limit: newLimit },
type: "post",
success: function(result){
alert( result )
},
error: function(data, status, errorString){
alert('error');
}
});
return false;
});
});
</script>
</head>
<body>
<!-- content -->
<div id='load_more_comments'>Load more...</div>
</body>
</html>
Try :
if (count($_POST)) {
Instead of
if (isset($_POST)) {

Getting information form json encode

main.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="jquery-3.1.1.min.js"></script>
<script src="jsfile.js"></script>
</head>
<body>
<button onclick="cart(0)"> hi </button>
<p id="disp"></p>
</body>
</html>
jsfile.js
function cart(id1)
{
var id=id1;
//alert("enterd "+id);
document.getElementById("disp").innerHTML ="hi";
if (window.jQuery) {
// jQuery is available.
// Print the jQuery version, e.g. "1.0.0":
//alert(window.jQuery.fn.jquery);
}
$.ajax({
url:"add.php ",
type:"POST",
data:{
item_id: id,
},
success:function(response) {
document.getElementById("disp").innerHTML =response.value1;
},
error:function(){
alert("error");
}
});
}
add.php
<?php
if(isset($_POST['item_id'])){
//if(count($_POST)>0)
echo json_encode(array("value1" => "hello", "value2" => "hi"));
}
?>
am collection the informaton from add.php to jsfile.js ... I am not able to get information from the json array.. I am trying to get information by respnse.value1. But it returns me undefined.. what might be the error??
You'll have to parse the JSON before using it. Change your success function to this -
success:function(response) {
var res = JSON.parse(response);
document.getElementById("disp").innerHTML = res.value1;
},

AJAX returns random hash instead of text

I am working on live notification script.
I have managed to rend request to external file, but the script returns random hash instead of plain text...
This is my function that should get data from test.php
<script>
$(document).ready(function () {
function load() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "/test.php",
dataType: "html", //expect html to be returned
success: function (response) {
$("#responsecontainer").append(response);
setTimeout(load, 5000)
}
});
}
load(); //if you don't want the click
// $("#display").click(load); //if you want to start the display on click
});
</script>
And it should append to the results.
This is the source of test.php
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Headerview</title>
</head>
<body>
<?php
$p = "<p>test</p>";
echo $p;
?>
</body>
</html>
And this is what I am getting...
inGN^PtJRo(hi*I1HVb&pB0wJs(B)9rID*6O�Eyh6cngWD+93Zr$zYU
The file path was the problem. I did not specify exact file path.
Thank you

Random string picker only execute once per page load

When you press the link text it is supposed to give you an random string from a file, which it does on first click. But second click nothing happens, I need to refresh page before execute it again..
Code:
function randomName() {
$names = file('layout/sub/names.txt', FILE_IGNORE_NEW_LINES);
$array = array_rand($names);
return $names[array_rand($names)];
}
<div class="randomName">
</div>
<button class="aardvark">Pick random name</button>
<script>
$(document).on('click','.aardvark', function(e){
$('.randomName').html('<?php echo randomName(); ?>');
});
</script>
The issue is the age old PHP is server side and and javascript(jQuery) is client side problem, you cant call/run PHP from javascript as its already happened.
You will need to use AJAX to re-request a new name. Here is a copy and paste example, your welcome ;p
<?php
//is ajax
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//is get name
if(isset($_POST['get_name'])){
$names = file('names.txt', FILE_IGNORE_NEW_LINES);
exit(json_encode(array('resp' => $names[array_rand($names)])));
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
//get_name function
$.fn.get_name = function(){
var elm = $(this);
var ajax = $.ajax({
url: "./",
type: "POST",
data: {'get_name':true},
dataType: "json"
});
ajax.done(function(data){
elm.html(data.resp);
});
ajax.fail(function(xhr, status, error){
elm.html("AJAX failed:" + xhr.responseText);
});
return this;
};
//do get_name on page load
$('#randomName').get_name();
//do get_name on button click
$('#aardvark').on('click', function(){
$('#randomName').get_name();
});
});
</script>
</head>
<body>
<div id="randomName"></div>
<button id="aardvark">Pick random name</button>
</body>
</html>

Categories