issue sending and retrieving value using ajax - php

This is a cleaner code of my preview problem, the idea is to send and retrieve a value using ajax, but the value is not being sent nor ajax seems to work. I updated this code because this way it could be easily tested on any machine. First time using ajax. Here is the code:
Javascript
<script>
jQuery(document).ready(function() {
jQuery('#centro').click( function() {
$.ajax({
url: 'request.php',
type:'POST',
data: $("#form").serialize(),
dataType: 'json',
success: function(output_string){
alert(output_string);
$('#cuentas').html(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
}
});
</script>
HTML:
<?php
$result = 'works';
?>
<form id="form">
<div id="centro">
Click here
<br>
<input type="hidden" name="centro" value="<?php echo $result; ?>">
</form>
<div id="cuentas">
</div>
PHP file, request.php
<?php
$centro = $_POST['centro'];
$output_string = ''.$centro;
echo json_encode($output_string);
?>

Looks like you never tell AJAX that the POST name is 'centro', try to change this:
data: $("#form_"+i).serialize(),
for this
data: { 'centro' : $("#form_"+i).serialize()},

I've run into the same problem with my ajax calls that I call via the POST method. My data was actually getting passed in the message body. I had to access it through the following method:
php://input
This is a read only wrapper stream that allows you to read raw data from the message body.
For more information on this wrapper visit this link.
Tray adding the following to your PHP file:
$centro = file_get_contents("php://input");
// Depending on how you pass the data you may also need to json_decode($centro)
echo json_encode($centro);
// See if you get back what you pass in
This read the message body (with my posted data) and I was able to access the value there.
Hope this helps.

try to using this code in your ajax post :
jQuery('#centro_'+i).click( function() {
$.ajax({
data: $("#centro_"+i).closest("form").serialize(),
dataType:"html",
success:function (data, textStatus) {
$('#cuentas').html(data);
alert(data);},
type:"post",
url:"load_cuentas.php"
});
});

Try this:
HTML
<?php
$i=0;
$f=0;
$consulta = $db->consulta("SELECT * FROM centro");
if($db->num_rows($consulta)>0){
while ($resultados1 = $db->fetch_array($consulta)){ ?>
<form id="form_<?php echo $f++; ?>"> //begin form with its id
<div class="centro" id="centro_<?php echo $i++; ?>">
<?php echo $resultados1['nombre_centro']; ?>
<br>
<input type="hidden" name="centro" value="<?php echo $resultados1['id_centro']; ?>">
<!--this is the data that is going to be sent. I set up a hidden input to do it.-->
</div>
</form>
<div id="cuentas" class="cuentas">
<!--where data is going to be displayed-->
</div>
<br>
<?php
}
}
?>
Javascript:
<script>
jQuery(document).ready(function() {
jQuery('.centro').on('click',function() {
var formElem=jQuery(this).closest('form');
jQuery.ajax({
url: 'load_cuentas.php',
cache: true ,
type:'POST',
dataType: 'json',
data: $(formElem).serialize(),
success: function(output_string){
jQuery(formElem).next('div.cuentas').html(output_string);
alert(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
});
</script>
Server page:
<?php
include ('mysql.php');
$db = new mysql();
$centro = $_POST['centro']; //this is not getting any data. the whole ajax thing
$consulta = $db->consulta("SELECT * FROM cuenta WHERE id_center = '$centro'");
$output_string=array();
if($db->num_rows($consulta)>0){
while ($resultados1 = $db->fetch_array($consulta)){
$output_string []= 'test text';
}
}
mysql_close();
echo json_encode($output_string);
?>

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');
})

How to pass data from a PHP file back to the original without page refresh?

I am trying to have the output from a PHP file display in the original page containing the form, without having to refresh the page.
I am currently using AJAX to do so but I am not able to pass the value of the submitted PHP file back to the index.php page - this needs to be done without having the page refreshed.
Overall
User enters some data and submits the form
That data is passed to a PHP file through AJAX
Some pieces of data, which were manipulated through the PHP file, are then echoed out onto the original index.html file without the page refreshing
Below you will find the code that I am currently using to try and achieve this.
index.php
<form>
<input type="text" name="hi">
<input type="submit">
</form>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
});
});
});
</script>
post.php
<?php
echo "Hello";
$name = $_POST['hi'];
echo $name . "This is a test";
?>
I would appreciate any help, thanks!
How about this simple solution. Just copy and paste this code into a file called index.php and whatever text you enter in the input field will be outputted by PHP. Hope it helps!.
<?php
$data = array();
if(isset($_POST['userText']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH'])){
$data = 'The data you entered is: ' . $_POST['userText'];
echo json_encode($data);
die();
}
?>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form>
<input type="text" name="hi" id = "someID">
<input type="submit" id = "sendInfo">
</form>
<div id = "random"></div>
<script type = "text/javascript">
$("#sendInfo").click(function(){
var someText = document.getElementById("someID").value;
var userText = JSON.stringify(someText);
$.ajax({
url: "index.php",
method: "POST",
dataType: "json",
data: {userText: userText},
success: function (result) {
console.log(result);
$("#random").html(result);
}
});
return false;
});
</script>
</body>
</html>
Add 'success' to your object and pass in a parameter to the function. That will hold the results from the php file.
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
success: function(results) {
console.log(results);
}
});
What this does is, on a successful ajax call, stores all of the content sent from the post.php file into the results variable.' In this case it will be whatever $name is and 'This is a test.'

Display MySQL queries on the same page

I've been searching for a while but nothing I've found match what I need.
I've got a form with 2 variables (dropdownlist) to query a DB (PHP and SQL).
Names of my variables are : "province" and "candidat".
My result page is action.php with all the sql/php code for the results.
Everything is going very fine except that after clicking on the submit button, a new page is opening : action.php with the results of my request.
Now, I wish to display this results on the same page as my form (id = form). The id of the div to display results is"success" (<div id="success">). There is an action on my form : action="action.php", should I remove it ?
I know that I have to use AJAX method but nothing that I've found match my needs. The other point is that I wish to be able to make another query and display the new results in this area.
If you know the solution or a tutorial that fit my needs... MANY THANKS of your help !
Start here: http://api.jquery.com/jQuery.ajax/
And do something along the lines of this:
$.ajax({
url: "action.php",
cache: false
}).done(function( response ) {
alert( response );
$("#success").html(response); //put the response into a DIV with id="success"
});
I'd recommend being more specific with your HTML id's that you are using.
$(document).ready(function(){
var datastring = "your data that is pass for php file";
$.ajax({
url: "action.php",
data: datastring,
type: "post",
success: function(response) {
alert(response);
}
});
});
Here's the code :
PROVINCE
">
<?php
}
?>
</select>
CANDIDAT
<?php
$result = mysql_query($query);
while($data = mysql_fetch_array($result))
{
?>
<option value="<?php echo $data['id_candidat']; ?>">
<?php echo $data['pren1']; ?> <?php echo $data['nom_candidat']; ?></option>
<?php
$id = $data['id_candidat'];
if ($id === $id)
{break;}
}
?>
</select>
<br/>
<input type="submit" class="submit" name="submit" value="ok" />
</form>
Content of action.php :

Getting data from PHP page on form submit

I have index.php with a form. When it gets submitted I want the result from process.php to be displayed inside the result div on index.php. Pretty sure I need some kind of AJAX but I'm not sure...
index.php
<div id="result"></div>
<form action="" id="form" method="get">
<input type="text" id="q" name="q" maxlength="16">
</form>
process.php
<?php
$result = $_GET['q'];
if($result == "Pancakes") {
echo 'Result is Pancakes';
}
else {
echo 'Result is something else';
}
?>
You really don't "need" AJAX for this because you can submit it to itself and include the process file:
index.php
<div id="result">
<?php include('process.php'); ?>
</div>
<form action="index.php" id="form" method="get">
<input type="text" id="q" name="q" maxlength="16">
<input type="submit" name="submit" value="Submit">
</form>
process.php
<?php
// Check if form was submitted
if(isset($_GET['submit'])){
$result = $_GET['q'];
if($result == "Pancakes") {
echo 'Result is Pancakes';
}
else {
echo 'Result is something else';
}
}
?>
Implementing AJAX will make things more user-friendly but it definitely complicates your code. So good luck with whatever route you take!
This is a jquery Ajax example,
<script>
//wait for page load to initialize script
$(document).ready(function(){
//listen for form submission
$('form').on('submit', function(e){
//prevent form from submitting and leaving page
e.preventDefault();
// AJAX goodness!
$.ajax({
type: "GET", //type of submit
cache: false, //important or else you might get wrong data returned to you
url: "process.php", //destination
datatype: "html", //expected data format from process.php
data: $('form').serialize(), //target your form's data and serialize for a POST
success: function(data) { // data is the var which holds the output of your process.php
// locate the div with #result and fill it with returned data from process.php
$('#result').html(data);
}
});
});
});
</script>
this is jquery Ajax example,
$.ajax({
type: "POST",
url: "somescript.php",
datatype: "html",
data: dataString,
success: function(data) {
doSomething(data);
}
});
How about doing this in your index.php:
<div id="result"><?php include "process.php"?></div>
Two ways to do it.
Either use ajax to call your process.php (I'd recommend jQuery -- it's very easy to send ajax calls and do stuff based on the results.) and then use javascript to change the form.
Or have the php code that creates the form be the same php code that form submits to, and then output different things based on if there are get parameters. (Edit: MonkeyZeus gave you specifics on how to do this.)

How do I use ajax to submit post data using jquery?

I'm having trouble getting ajax to work with jquery and codeigniter. I've followed multiple tutorials but nothing seems to work. I'm trying to implement an upvote button that sends post data using ajax to be inserted into a db. Any help is much appreciated.
The code from my view:
<pre>
<?php foreach($query->result() as $row): ?>
<div>
<form action="" method="post">
<input type="hidden" name="story_id" value=<?php echo $row->id; ?>>
<input type="submit" name="story_id" class="button" id="submit_btn" value=<?php echo $row->id;?>>
</form>
</div>
<?php endforeach; ?>
</pre>
The jquery script I'm using:
<pre>
<script type="text/javascript">
$(document).ready(function(){
$(".button").click(function(){
var form_data = {
story_id: $(this).val()
};
$.ajax({
url: "<?php echo base_url('cyoa/upvote'); ?>",
type: 'POST',
data: form_data,
success: function()
{
$("#upvote").hide();
}
});
return false;
});
});
</script>
</pre>
Best way is to serialize your form data and send that to the server:
<script type="text/javascript">
$(document).ready(function(){
$(".button").click(function(){
var form_data = $("#myform").serialize();
$.ajax({
url: "<?php echo base_url('cyoa/upvote'); ?>",
type: 'POST',
data: form_data,
success: function()
{
$("#upvote").hide();
}
});
return false;
});
});
</script>
To access the form, give it a id:
<form id="myform" action="" method="post">
I strongly suggest to look at this plugin (and use it) :
JQuery Form Plugin
You can use form serialization to pass on data to php as below
First Give ID "storyform" to your form tag
$.ajax({
url: "<?php echo base_url('cyoa/upvote'); ?>",
type: 'POST',
data: $("#storyform").serialize(),
success: function()
{
$("#upvote").hide();
}
});
try using json objects,
view....
<pre>
<?php foreach($query->result() as $row): ?>
<div>
<form action=" controller_name/upvote" method="post">
<input type="hidden" name="story_id" id = "story_id" value=<?php echo $row->id; ?>>
<input type="submit" name="story_id" class="button" id="submit_btn" value=<?php echo $row->id;?>>
</form>
</div>
<?php endforeach; ?>
</pre>
Then your controller,
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Controller_name extends CI_Controller {
function __construct()
{
parent::__construct();
//loading libraries
$this->load->helper(array('form','url'));
$this->load->library('form_validation');
}
//##############################################################################
function upvote(){
//setting validation rules
$this->form_validation->set_rules('story_id', 'story Id', 'required|xss_clean');
if ($this->form_validation->run() == true){
//if validations ok, send the data to database
$this->load->model('your_model');
$params = ($this->input->post('story_id');
$query = 'INSERT INTO table_name (story_id) VALUES(?)';
$result = $this->your_model_name->method_name($query,$params);
echo '{"validation_result": "passed"}';
}
else{
$output = '{"story_id":"'.form_error('story_id').'"}';
echo $output;
}
}
}
?>
Then Your java script file
$(document).ready(function(){
$('#submit_btn').live('click',function(){
var form_data = {
$story_id: $('#story_id').val()
};
$.ajax({
type: "POST",
url: baseurl+"controller_name/upvote",
dataType: "json",
data : form_data,
success:
function(data){
if(data.validation_result == "passed"){
$("#upvote").hide();
}
else{
//form_validation errors
}
}
});
return false;
});
});

Categories