pass js variable to php using ajax on the same page - javascript

this is my html code:
<form id="form" action="javascript:void(0)">
<input type="submit" id="submit-reg" value="Register" class="submit button" onclick="showtemplate('anniversary')" style='font-family: georgia;font-size: 23px;font-weight: normal;color:white;margin-top:-3px;text-decoration: none;background-color: rgba(0, 0, 0, 0.53);'>
</form>
this is my javascript code:
function showtemplate(temp)
{
$.ajax({
type: "POST",
url: 'ajax.php',
data: "section="+temp ,
success: function(data)
{
alert(data);
}
});
}
this is my ajax.php file:
<?php
$ajax=$_POST['section'];
echo $ajax;
?>
The above html and javascript code is included in a file named slider.php. In my index file i have included this slider.php file and slider.php is inside slider folder. So basically index.php and slider.php are not inside the same folder.
Javascript code alerts the data properly. But in my php code (ajax.php file) the value of $_POST['section'] is empty. What is the problem with my code. I tried googling everything and tried a few codes but it still doesn't work. Please help me out

Try this instead:
$.ajax({
type: "POST",
url: 'ajax.php',
data: { 'section': temp},
success: function(data)
{
alert(data);
}
});
It is quite possible that your server does not understand the string you have constructed ( "section="+temp ). When using ajax I prefer sending objects since for an object to be valid it requires a certain format.
EDIT1:
Try this and let me know if it doesn't work either:
$.post('ajax.php', {'section': temp}, function(data}{
alert(data);
});

Add jquery plugin(jQuery library) ,then only ajax call works
for eg
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
check your input data , whether it contain '&,/' charators,then use encodeURIComponent()
for Ajax Call Eg:
var gym_name = encodeURIComponent($("#gym_name").val());
$.ajax({
type: "POST",
url: "abc.php",
data:string_array,
success: function(msg) {
console.log(msg);
}
});
In abc.php
<?php
$id = $_POST['gym_name'];
echo "The id is ".id;
?>

Give a try to the following (although I cannot work out why #Grimbode's answer is not working):
$("#submit-reg").on( "click", function() {
$.ajax({
type: "POST",
url: 'ajax.php',
data: {'section': 'anniversary'},
success: function(data)
{
alert(data);
}
});
});
Note: I don't know what your underlying code is doing. However, I would suggest not using HTML element properties to handle events for numerous reasons, but separate the JS/event handling appropriately (separate js file(s) (recommended) or inside <script> tags). Read more...

Related

jQuery ajax not passing post data to php page

I try to get post data from using alert() and its worked problem is that data is not passing to php page result is always {"success":false,"result":0}
What I want is send password to php page and hash it using password_hash() and return result
$('#spass').on('submit',function(){
var that=$(this),
contents=that.serialize();
alert(contents);
$.ajax({
url:'passwordhashing.php',
dataType:'json',
data:contents,
success:function(data){
alert(JSON.stringify(data));
console.log(data);
}
});
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="spass" >
<h4>Change Your Password</h4>
<input type='password'name="passc" >
<!--<input type='password' name="cpass" id="cpass"> -->
<input type="submit">
</form>
**this my php code**
<?php
header('Content-type: text/javascript');
$json=array(
'success'=>false,
'result'=>0
);
if(isset($_POST['passc']) && !empty($_POST['passc'])) {
$pass=password_hash($_POST['passc'],PASSWORD_DEFAULT);
$json['success']=true;
$json['result']=$pass;
}
echo json_encode($json);
?>
You can test that your data has not actually been passed to a PHP page.
In the PHP code, do the following: echo $ _POST ['YOUR_VARIABLE'].
Check the INSPECT_ELEMENT / NETWORK browser to make sure you actually send data to the correct link. Your link may be relative, so you may be sending data to the wrong link.
So, try to put the entire link in the ajax url
$ .ajax ({
url: 'HTTP: //WHOLE_LINK_IN_HERE.COM/passwordhashing.php',
});
SET method in Ajax: type: "POST"
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
**i used $.post() instead of using $.ajax() and it fix my problem**
$('#spass').on('submit',function(){
var that=$(this),
contents=that.serialize();
alert(contents);
$.post({
url:'passwordhashing.php',
dataType:'json',
data:contents,
success:function(data){
alert(JSON.stringify(data));
console.log(data);
}
});
return false;
});

Why is my jquery/ajax post not registering in my php code?

So I am trying to build a single page application using PHP and AJAX but I am having some issues with my navigation.
I have a file controller.php that controls the page to be displayed. The code that handles a post request is as follows
EDIT: Forgot to mention that echoing $_POST['page'] shows nothing
if(!isset($_POST['page'])){
include('Pages/landing_page.php');
echo "empty";
}
else{
echo $_POST['page'];
if($_POST['page'] == 'landing_page'){
include('Pages/landing_page.php');
}
if($_POST['page'] == 'forum'){
include('Pages/forum.php');
echo "forum hit";
}
}
The post request is generated with $.ajax function as follows
$(document).ready(function(){
$("#home_link").on('click', ()=>{
alert("Working");
$.ajax({
type: "POST",
url: "controller.php",
data: "page=landing_page"
});
});
$('#forum_link').on('click', ()=>{
$.ajax({
type: "POST",
url: "controller.php",
data: "page=forum",
success: function(){
alert("Callback Works");
}
});
});
});
I know the jquery click is working because I get the original "Working" alert as well as the callback alert if I click on the forum link.
I am using the Netbeans built in PHP development server but I have also tested it on a proper apache2 server that is well configured for PHP and AJAX.
Any help would be appreciated, thanks!
As I understand the question, this should work:
PHP: (all the same)
if(!isset($_POST['page'])){
include('Pages/landing_page.php');
echo "empty";
}
else{
echo $_POST['page'];
if($_POST['page'] == 'landing_page'){
include('Pages/landing_page.php');
}
if($_POST['page'] == 'forum'){
include('Pages/forum.php');
echo "forum hit";
}
}
JS:
$(document).ready(function(){
$("#home_link").on('click', ()=>{
alert("Working");
$.ajax({
type: "POST",
url: "controller.php",
data: "page=landing_page"
});
});
$('#forum_link').on('click', ()=>{
$.ajax({
type: "POST",
url: "controller.php",
data: "page=forum",
success: function(data){
$("#container").html(data);
alert("Callback Works");
}
});
});
});
You need to take the data returned from the function and put it somewhere, presumably into a container element.
If this isn't what you are trying to do, please comment.

AJAX to PHP without page refresh

I'm having some trouble getting my form to submit data to my PHP file.
Without the AJAX script that I have, the form takes the user through to 'xxx.php' and submits the data on the database, however when I include this script, it prevents the page from refreshing, displays the success message, and fades in 'myDiv' but then no data appears in the database.
Any pointers in the right direction would be very much appreciated. Pulling my hair out over this one.
HTML
<form action='xxx.php' id='myForm' method='post'>
<p>Your content</p>
<input type='text' name='content' id='content'/>
<input type='submit' id='subbutton' name='subbutton' value='Submit' />
</form>
<div id='message'></div>
JavaScript
<script>
$(document).ready(function(){
$("#subbutton").click(function(e){
e.preventDefault();
var content = $("#content").attr('value');
$.ajax({
type: "POST",
url: "xxx.php",
data: "content="+content,
success: function(html){
$(".myDiv").fadeTo(500, 1);
},
beforeSend:function(){
$("#message").html("<span style='color:green ! important'>Sending request.</br></br>");
}
});
});
});
</script>
A couple of small changes should get you up and running. First, get the value of the input with .val():
var content = $("#content").val();
You mention that you're checking to see if the submit button isset() but you never send its value to the PHP function. To do that you also need to get its value:
var submit = $('#subbutton').val();
Then, in your AJAX function specify the data correctly:
$.ajax({
type: "POST",
url: "xxx.php",
data: {content:content, subbutton: submit}
...
quotes are not needed on the data attribute names.
On the PHP side you then check for the submit button like this -
if('submit' == $_POST['subbutton']) {
// remainder of your code here
Content will be available in $_POST['content'].
Change the data atribute to
data:{
content:$("#content").val()
}
Also add the atribute error to the ajax with
error:function(e){
console.log(e);
}
And try returning a var dump to $_POST in your php file.
And the most important add to the ajax the dataType atribute according to what You send :
dataType: "text" //text if You try with the var dump o json , whatever.
Another solution would be like :
$.ajax({
type: "POST",
url: "xxxwebpage..ifyouknowhatimean",
data: $("#idForm").serialize(), // serializes the form's elements.
dataType:"text" or "json" // According to what you return in php
success: function(data)
{
console.log(data); // show response from the php script.
}
});
Set the data type like this in your Ajax request: data: { content: content }
I think it isnt a correct JSON format.

Using AJAX/Jquery to Replace div

I am trying to set the content of an empty div after an AJAX call with the data message. I also wired the function to my CHtml::submitButton, which should call the function when clicked, but nothing is happening. Any suggestions?
<div id="myResult">
</div>
JavaScript:
function successMessage(){
$.ajax({
type: "GET",
data: "<div> Replace div with this contentf</div>",
success: function(data){
$('myResult').html(data);
}
})
}
PHP:
echo CHtml::beginForm(array('myForm'), 'get', array('form'));
echo '<div class="row form">';
echo '<div class="row buttons">';
echo CHtml::submitButton('Download Content', array('htmlOptions' => 'successMessage()'));
echo '</div>';
echo '</div>';
Your problem relies in the following line:
$('myResult').html(data);
Here, you are trying to do a jquery selection to an element, which you are not using in your html (this is only possible via pollyfils). So you have to select the element by its ID:
$('#myResult').html(data);
And another thing i've seen, what is the url where you are doing the request?
<script>
function successMessage(){
$.ajax({
type: "GET",
url: "/please/add/an/url/",
data: "<div> Replace div with this contentf</div>",
success: function(data){
$('myResult').html(data);
}
})
}
</script>
first of all, when you are using onclick function like this :
<input type="submit" onclick="successMessage()">
you should use this instead:
<input type="submit" onclick="successMessage();result false;">
but when you are already using jquery, then better approach is:
$( document ).ready(function() {
successMessage(){
// your ajax goes here
}
$('#myResult').click(function(e){
e.preventDefault();
successMessage();
});
});
Then you need to repair your successMessage function. You see, the data you are setting there are not the data, that are coming out as an output. If you need ajax then you probably want to get the result from some php script on some other url. Then you should do it like this :
function successMessage(){
$.ajax({
type: "GET",
url : 'index2.php',
dataType: "json",
data: { mydata: '<div> Replace div with this content</div>'},
success: function(data){
$('#myResult').html(data);
}
})
}
Then you need a php file named index2.php which can look like this :
<?php
echo json_encode($_GET['variable']);
?>
And i dont know if this your line :
echo CHtml::submitButton('Download Content', array('htmlOptions' => 'successMessage()'));
also put the </form> tag after the form to close it.
This should work for you. I tried it and it works fine.
Try this:
$.ajax({
url: "test.html",
type: "GET",
data: "<div> Replace div with this contentf</div>",
success: function(data){
$('#myResult').html(data);
}
})
selector jQuery incorrect in response ajax. and define Url in ajax.

Form or jQuery Ajax?

When a form sends variable with GET Method, the URL changes, putting the variables that you are passing in this way
url?variable=....
How can I get the same result with jQuery Ajax? Is it possible? Thank you
set path in your php layout/view file where you include this code
<script>
var path="<?php echo $this->webroot;?>";
</script>
and add following jquery code to post the data through ajax.
$.ajax({
type: 'POST',
url: path+'homes/createEvent',
data: {eventname:eventname,manager:manager},
async: false,
success: function(resulthtml)
{
alert(resulthtml);
},
error: function(message)
{
alert('error');
}
});
and on homes_controller.php, u will get this ajax data in createEvent function,
<?php
function createEvent()
{
$eventName=$_POST['eventname'];
$manager=$_POST['manager'];
}
?>

Categories

Resources