$.post() not able to pass data - php

I want to pass some data as a variable using jQuery $.post() method to a PHP file and then display the result in a div after clicking a button. But the data isn't getting retrieved in PHP file.
<script>
$(document).ready(function () {
$("button").click(function () {
$.post("add.php", {
fname: 'Billy'
}, function () {
$('#topic').load('add.php');
});
});
});
</script>
</head>
<body>
<br>
<div class="container">
<?php
echo "Welcome ".get('Name')." !";
?>
<div style="float: right">
<?php
echo "<a href='logout.php'> Log Out </a>";
?>
</div>
<br>
<button>Add Topic</button><br>
<div id='topic'></div>
//the PHP file:
<?php
session_start();
echo "".$_POST['fname']."";
//if(isset($_POST['fname']))
//{
//$fname=$_POST['fname'];
//echo " ".$fname." topic added!";
//}
?>
Notice: Undefined index: fname in C:\xampp\htdocs\forum\add.php on line 3

I'm not too familiar with the load function, but it seems to me that you're doubling down on fetching from the same resource.
You could do something like:
$.ajax({
type: "POST",
url: 'add.php',
data: {fname:"Billy"},
success: function(response){
$( "#topic" ).html(response);
// or .text or whichever replacement method you need/works best
},
});
add.php
if ( isset($_POST['fname'] ){
echo "Topic " . $_POST['fname'] . " added!";
} else {
echo "Could not find 'fname'!";
}

$.ajax({
type: "POST",
url: 'add.php',
data: {fname:"your data goes here"},
success: function(response){
// handle success
},
error: function(response){
// handle error
},
});

Related

passing a variable to php file using ajax not working

I am trying to pass a variable when a class("women") is clicked using ajax to a php file but it is not working. Here is my code
jquery:
$('.women').click(function(){
var test="hello";
$.ajax({
type: "POST",
url: 'data.php',
data: {'variable':test},
success:function(data){
console.log(data);
},
});
$(".women").attr('href','data.php');
})
php code:
if (isset($_POST['variable']))
{
echo($_POST['variable']);
}
else
{
echo ("failure");
}
html:
<li class="nav-item mr-auto ml-auto" data-target="#collapsewomen">
<a class="nav-link active women productlink" href="#">Women</a>
</li>
In the console I can see "hello" which mean ajax is working, but once directed to php page I get "failure". What I am not able to pass test variable to php file
The purpose of ajax is to send data to a URL without refreshing the page. If you want redirect the page, there is no use of using ajax.
Doing an ajax call will not automatically save the data sent and the data can't be use if you redirect to that page.
Using GET
$('.women').click(function(){
var test="hello";
window.location.href = "data.php?variable=" + test;
})
On your php
if (isset($_GET['variable']))
{
echo($_GET['variable']);
}
else
{
echo ("failure");
}
Using POST, one option is to use hidden form like:
On your main page:
$('.women').click(function(){
var test = "hello";
$('[name="variable"]').val(test); //Update the value of hidden input
$("#toPost").submit(); //Submit the form
})
HTML:
<a class="nav-link active women productlink" href="#">Women</a>
<form id="toPost" action="data.php" method="POST">
<input type="hidden" name="variable" value="">
</form>
On your data.php:
<?php
if (isset($_POST['variable']))
{
echo($_POST['variable']);
}
else
{
echo ("failure");
}
?>
I think it should be data: {variable:test} not data: {'variable':test}
add this to your frontend file
<input type="button" class="women" value="Button" name="ash_b" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js" >
$('.women').click(function(){
var test="hello";
$.ajax({
type: "POST",
url: 'data.php',
data: {'variable':test},
success:function(data){
console.log(data);
},
});
$(".women").attr('href','data.php');
})
</script>
And in your data.php use following code
if (isset($_POST['variable']))
{
echo($_POST['variable']);
}
else
{
echo ("failure");
}
it works perfectly for me, try this if this doesnt work show your both files
Please try this code:
$('.women').click(function(){
var test="hello";
var datastr = 'test='+test;
$.ajax({
type: "POST",
url: 'data.php',
data: datastr,
success:function(data){
console.log(data);
},
});
$(".women").attr('href','data.php');
})

Passing variables from javascript via ajax to php

I am new to jquery and ajax. I have a script here where i need to pass variables to a php file. That php will be then encoded to div#chat-body. I am trying to pass the receiver variable to the load-messages.php via POST but I am getting the following error: "Undefined index: receiver in xxxx/scripts/load_messages.php on line 8". I think there is something wrong with my syntax or im doing this totally wrong.
script.js
$('input#send-message').on('click', function(){
alert("test");
var message = $('input#input-message').val();
var sender= $('input#sender').val();
var receiver= $('input#receiver').val();
if($.trim(message)!=''){
$.post('scripts/messaging.php', {message: message, sender: sender, receiver:receiver}, function(data){
//output after sending message
});
//load message to chat-body div
$.ajax({
url: 'scripts/load_messages.php',
type: "POST",
data: {receiver: receiver},
success: function(data){
$('#chat-body').html(data);
//$('#chat-body').scrollTop($('#chat-body')[0].scrollHeight);
}
});
}});
load-messages.php
<?php
session_start();
require('config.php');
require('chat_functions.php');
$messages = get_msg($_SESSION['user_id'], $_POST['receiver']);
foreach($messages as $message){
if($message['sender'] == $_SESSION['user_id']) {
?><div id = "you_message">
<?php echo '<strong> You: </strong><br />';
echo $message['message'].'<br /><br />';?>
</div><!--you_message-->
<?php
}
else{
?><div id="recipient_message">
<?php echo '<strong>'.get_name($_POST['receiver']).'</strong><br />';
echo $message['message'].'<br /><br />';?>
</div> <!--recipient_message -->
<?php
}
}
?>
It's just simple to pass the values to php file through AJAX call.
Change your AJAX call as shown in below
var message = $('#input-message').val();
var sender= $('#sender').val();
var receiver= $('#receiver').val();
$.ajax({
url: "scripts/load_messages.php",
method: "post",
//data: { "message":$('#input-message').val(),"sender":$('#sender').val(),"receiver":$('#receiver').val()},you can pass the values directly like this or else you can store it in variables and can pass
data: { "message":message,"sender":sender,"receiver":receiver},
success: function(data){
$('#chat-body').html(data);
},
error: function() {
alert('Not OKay');
}
});
and your load-messages.php could be like this`
$receiver = $_POST['receiver'];
echo $receiver;
You're passing an object, not a JSON string :
$.ajax({
type: 'POST',
url: 'scripts/messaging.php',
data: JSON.stringify ({receiver: receiver}),
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
you can try this then adapt it to your needs, as I just made it a little bit more 'basic' :
your form :
<form action="#" id="form" method="post">
<input type="text" id="sender" name="sender" />
<input type="text" id="receiver" name="receiver" />
<input type="text" id="input-message" name="input-message" />
<input type="submit" id="send-message" value="Post" />
</form>
<div id="chat-body" class="regular"></div>
the jQuery part :
$(document).ready(function(){
$("#send-message").click(function(e){
e.preventDefault(); /* to prevent form default action */
var message = $('#input-message').val();
var sender = $('#sender').val();
var receiver = $('#receiver').val();
$.ajax({
url: "load_messages.php",
method: "POST",
data: { message: message, sender: sender, receiver:receiver },
success: function(html){
alert(html); /* checking response */
$('#chat-body').html(html); /* add to div chat */
}
});
});
});
then, load_message.php
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$sender = $_POST['sender'];
$receiver = $_POST['receiver'];
$message = $_POST['message'];
echo"[ $sender / $receiver / $message ]"; /* here, you can only echo $message for instance,
then use response to append message to chat window */
?>

Phalcon jquery-ajax on button click

I am warking in phalcon framework, and i am trying to call controller's method to get simple string using jquery-ajax. When i placed my ajax call inside $(document).ready(function() ajax call worked, but when i placed same code inside $('#dugme').click(function() ajax call reported error. I am confused. Here is my view code:
<script type="text/javascript">
$(document).ready(function(){
//alert($("#nesto").val());
//atr = $(".klasa").attr("id");
//alert("Id je: " + atr)
$.ajax({
url: '<?php echo $this->url->get("xml/posalji");?>',
type: 'POST',
dataType: 'json',
success: function(data){
alert(data);
},
error: function(){
alert("Neuspjesan JSON zahtjev!");
}
});
$('#dugme').click(function(){
$.ajax({
url: '<?php echo $this->url->get("xml/posalji");?>',
type: 'POST',
dataType: 'json',
success: function(data){
alert(data);
},
error: function(){
alert("Neuspjesan JSON zahtjev!");
}
});
}) ;
});
</script>
<h2>Basic example</h2>
<?php echo Tag::form("xml/pretraga"); ?>
<p>
<label for="name">Title</label>
<?php $opt = array('title', 'id'=>'nesto', 'size'=>'10');
$buttopt = array('Show', 'id'=>'dugme','class'=>'klasa');
?>
<?php echo Tag::textField($opt) ?>
</p>
<p>
<?php echo Tag::SubmitButton($buttopt) ?>
</p>
</form>
and here is my action code:
public function posaljiAction(){
$this->view->disable();
$data = "My name is Nedimo";
echo json_encode($data);
}
Please, can anyone tell me what is wrong in my code.

AJAX call success but data not retrieved at server

I have an ajax call that passes data to another php file, createTest2.php, as below.
But the createTest2.php file throws error
"Notice: Undefined index: aaa in C:\xampp\htdocs\TestProj\Test\createTest2.php on line 2
I have no clue how to fix it.
caller.php
$(document).ready(function(){
$("#button_submit").click(function()
{
$.ajax({
type:"POST",
url:"createTest2.php",
data:{aaa : "UNIT_TEST"},
success:function()
{
alert("success");
}
});
});
});
createTest2.php
$test_name = $_POST['aaa'];
if you are using
$test_name = $_POST['aaa'];
you have to call ajax like this
$(document).ready(function(){
$("#button_submit").click(function()
{
$.ajax({
type:"POST",
url:"createTest2.php",
data:"aaa=UNIT_TEST",
success:function()
{
alert("success");
}
});
});
});
the main thing is that " data:"aaa=UNIT_TEST", "
Try this:
//sample.php
<?php
if(isset($_POST) && isset($_POST['aaa'])){
echo json_encode("hello world! Your data was: " . $_POST['aaa']);
}
?>
//your client side page
<html>
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function send(){
$.ajax({
type:"POST",
url: 'sample.php',
data:{aaa:"UNIT_TEST"},
dataType: 'json'
}).done(function(data){
alert(data);
});
}
</script>
</head>
<body>
Send
</body>
</html>
Try this in your, for example, index.html:
<script>
$(document).ready(function(){
$("#button_submit").click(function()
{
$.ajax({
global: false,
type:"post",
dataType: "html",
cache: false,
url: "createTest2.php",
data: {aaa:'test'},
success:function(html) { alert(html); },
error: function(e) {alert(e);}
});
});
});
</script>
And in your createTest2.php just put this to see if ajax calls are received:
<?php
echo $_POST['aaa'];
?>

json jquery post request

<script type="text/javascript">
$(document).ready(function() {
$("a").click(function() {
var content = $('#content').html();
var data = {"content":content};
$.ajax({
type: "POST",
dataType: "json",
url: "ajax.php",
data: {content:content},
success function (data) {
alert('Hello!');
}
});
});
});
</script>
<div id="content"><?php echo $content; ?></div>
ajax.php
echo json_encode($_POST['content']); ?>
Nothing happens... WhatI really want to achieve is to get that alert box and get the return data, but I am lost since I don't get any errors or nothing.
You miss " : " after success
<script type="text/javascript">
$(document).ready(function() {
$("a").click(function() {
var content = $('#content').html();
var data = {"content":content};
$.ajax({
type: "POST",
dataType: "json",
url: "ajax.php",
data: {content:content},
success: function (data) {
alert('Hello!');
}
});
});
});
</script>
<div id="content"><?php echo $content; ?></div>
As #sofl said, if you change it to success:function (data) { it will work!
Just remember that the $("a") from $("a").click(function() { called when click in a link tag like <a href"">.
If you are using an input ou button with a class="a" you should change the code to $(".a").click(function() {
(just add a . before a)
PS: If you're using a link, you should set the href="" to href="#" to work.

Categories