Calling ajax on the same page - javascript

I am trying to call ajax on the same page without click event, I am getting the following error:
Notice: Undefined index: name in index.php on line
It works fine with the click event. I am trying to do it without any events. My goal is to pass JavaScript variable to PHP.
<script>
$(document).ready(function(){
alert('est123');
$.ajax({
type: 'POST',
url: 'index.php',
data: ({name:"test"}),
cache: false,
success: function(data){
$('#results').html(data);
}
})
return false;
});
</script>
</head>
<body>
click me!
<div id="results"></div>
<div><?php echo $_POST['name'] ?></div>
</body>
</html>

Check to see if it exists before outputting it
if (isset($_POST['name'])) { echo $_POST['name'] }
BUT I do not think this is what you want to happen since you will be sticking the HTML document returned into the page.

I think this might help you.
<script>
$(document).ready(function(){
dataArray={name:"test"};
$.ajax({
type: 'POST',
url: 'index.php',
data: dataArray,
cache: false,
success: function(data){
$('#results').html(data);
$('#lblName').html(dataArray.name);
}
})
return false;
});
</script>
</head>
<body>
click me!
<div id="results"></div>
<div id="lblName"></div>
</body>
</html>

Related

Ajax not able to post javascript variable to php

I want to post values of a JavaScript variable to a PHP page, and then use those values there.
I get back a new HTML page, which I did not want to happen. Also, it is showing the error message produced by:
echo"some error";
What am I missing? I don't understand why this happens?
Here is my html file try.html
<html>
<head>
<title>try</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<a id="button" href="try.php" target="_blank">send data</a>
<script>
var sum2= 2010;
$('#button').click(function() {
var val1=sum2;
$.ajax({
type: 'POST',
url: 'try.php',
data: { text: val1 },
dataType: 'script' // I am not sure about what I write here script,json,html?
});
});
</script>
</body>
</html>
And this is my PHP file try.php
<?php
if(isset($_POST['text']))
{
$text = $_POST['text'];
echo $text;
}
else {
echo"some error";
}
?>
In try.php if you echo something which in turn will comeback to try.html.
If you just want to post the data to try.php and echo there the just use form and submit. You dont need ajax in that.
Ajax is to send the data/receive back without reloading the existing page. The response will be seen in the current page itself.
<html>
<head>
<title>try</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<a id="button" href="try.php">send data</a>
<script>
var sum2= 2010;
$('#button').click(function() {
var val1=sum2;
var json_params = {
text: val1
};
var json_data = JSON.stringify(json_params);
$.ajax({
type: 'POST',
url: 'try.php',
data: json_data,
dataType: "html",
success: function(response)
{
alert(response);
}
});
});
</script>
</body>
</html>
In the try.php page you can place this code
<?php
if (isset($_POST)){
$data = json_decode(file_get_contents('php://input'));
print_r($data);
}
else{
echo "not set";
}
?>
Firstly, remove script from data-type.
This is how you can pass the data to php file:
$('#button').click(function() {
var val1=sum2;
$.ajax({
type: 'POST',
url: 'try.php',
data: { text: val1 },
});
});
dataType - The type of data that you're expecting back from the
server. Here you don't want anything in return then it's fine. If you
are expecting anything like json or something, you can specify it.
If You want anything in response, you can handle in this manner
$('#button').click(function() {
var val1=sum2;
$.ajax({
type: 'POST',
url: 'try.php',
data: { text: val1 },
});
success: function (data) {
//Your success handler code
},
});
success - A callback function to be executed when Ajax request
succeeds.
Firstly remove href from link. By this it is directly redirecting to try.php
<a id="button" href="javascript:void(0);" target="_blank">send data</a>

How to run simple php code with jquery/ajax?

Because my actual example is way too big I made a very short example:
test1.php
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <!--jQuery-->
<body>
<p> What is the first letter of the alphabet?</p>
<button type="button" id="button">Tell me!</button>
<div id="div"></div>
<script>
$(document).ready(function(){
$('#button').click(function(){
$.ajax({
url: 'test2.php',
success: function() {
$('#div').html();
}
});
});
});
</script>
</body>
</html>
test2.php
<?php
echo "It's the letter A!";
?>
I want to this to print out "It's the letter A!" when I hit the button, which does not seem to work. Could somebody help end tell me why this doesn't work and how to fix it?
Thanks
1st : Should be enclosed by quotes $('#button')
2nd : Get the response in success function like this.
success: function(res) {
$('#div').html(res);
}
3rd : Set data type to text .
dataType:'text'
Update 1:
$(document).ready(function(){
$('#button').click(function(){
$.ajax({
url: 'test2.php',
dataType:'text',
success: function(res) {
$('#div').html(res);
}
});
});
});
Its because you haven't output the result you got from ajax.
<script>
$(document).ready(function(){
$("#button").click(function(){
$.ajax({
url: 'test2.php',
success: function(data) { //<---result from ajax
$('#div').html(data); //<----add result to div element
}
});
});
});
</script>
If your script is only a call of a page without GET/POST arguments, the simpliest way with jQuery is $.load() :
<script>
$(document).ready(function() {
$('#button').click(function() {
$.load("test2.php #div");
});
});
</script>
doc here : http://api.jquery.com/load/

Jquery Ajax is not working with Codeigniter

I am a ajax beginner, Here I am trying to show a text box value in same page using Ajax.
My Controller code:
<?php
class Merchant extends CI_Controller
{
public function ajaxtest()
{
$this->load->helper('url');
$this->load->view('ajaxtest');
$fullname = $this->input->post("fullname");
echo $fullname;
}
}
?>
Here is my view code:
<head>
<script src="<?php echo base_url();?>assets/js/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#getinfo").click(function()
{
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>merchant/ajaxtest",
data: {textbox: $("#fullname").val()},
dataType: "text",
cache:false,
success:
function(data){
$('#mytext').html(data);
}
});
return false;
});
});
</script>
</head>
<body>
<form method="post">
<input type="text" id="fullname"/>
<input type="button" value="getinfo" id="getinfo"/>
<span id="mytext"></span>
</form>
</body>
When I click on the button getinfo, I want to show the text inside the text box as span text. But now it shows nothing..
Updated:
After experts' opinion, I edited some text(see my edit note), Now When i click on the button, it shows again a textbox and a button.. !!
Did you set the base_url variable with a link on the Javascript?
Because your post url contains this variable and you need set this to make it work. So initialize the variable with the base_url link.
See the corrected example below . Set your domain instead of the yourbaseurl.com
<script type="text/javascript">
$(document).ready(function(){
var base_url='http://yourbaseurl.com/index.php/';
$("#getinfo").click(function()
{
$.ajax({
type: "POST",
url: base_url + "merchant/ajaxtest",
data: {textbox: $("#fullname").val()},
dataType: "text",
cache:false,
success:
function(data){
$('#mytext').html(data);
}
});
return false;
});
});
</script>
Your base_url variable seems to be undefined in your JavaScript.
One simple approach to get the base URL is to echo it out in a hidden input, and then grab the value of that input in your JS code:
HTML
<input type='hidden' id="baseUrl" value="<?php echo base_url(); ?>" />
JS
var base_url = $('#baseUrl').val();
$.ajax({
type: "POST",
url: base_url + "/merchant/ajaxtest",
data: {textbox: $("#fullname").val()},
dataType: "text",
// ...
you are passing in textbox as parameter from your ajax to controller and trying to get POST data with name fullname. That wont work, since you passed in the name of parameter as textbox, access that in your post, as :
class Merchant extends CI_Controller
{
public function ajaxtest()
{
$this->load->helper('url');
//you dont need to load view so comment it
//$this->load->view('ajaxtest');
$fullname = $this->input->post("textbox"); //not fullname
echo $fullname;
}
}
js
<script type="text/javascript">
$(document).ready(function(){
var base_url='http://yourbaseurl.com/index.php/';
$("#getinfo").click(function() {
var fullname = $("#fullname").val();
alert("Fullname:" + fullname); //do you get this alert
$.ajax({
type: "POST",
url: base_url + "merchant/ajaxtest",
data: {textbox: fullname},
cache:false,
success:function(data){
alert("Response:" + data); //do you get this alert
$('#mytext').html(data);
}
});
return false;
});
});
</script>
Try using this:
<base href="<?=base_url();?>">
<script src="assets/js/jquery-latest.min.js"></script>
And this in ajaxtest:
$this->load->helper('url');
And also Comment out this:
// $this->load->view('ajaxtest');
Might be a little late with this response - but someone might find this while searching for a solution.
I was having the same issues with Codeigniter and JQuery ajax/post response. I could not get this to work no matter what I tried.
In the end, it turned out to be php_error that was causing the problem. Once I removed it, everything worked fine with my post/response.

Ajax call (before/success) doesn't work inside php file

I have a form that when clicked the submit button makes a call via ajax. This ajax is inside a php file because I need to fill in some variables with data from the database. But I can not use the calls before / success. They just do not work, I've done tests trying to return some data, using alert, console.log and nothing happens. Interestingly, if the ajax is isolated within a file js they work. Some can help me please?
File:
<?php
$var = 'abc';
?>
<script type="text/javascript">
$(document).ready(function() {
$('#buy-button').click(function (e){
var abc = '<?php echo $var; ?>';
$.ajax({
type: 'POST',
data: $('#buy-form').serialize(),
url: './ajax/buy_form.php',
dataType: 'json',
before: function(data){
console.log('ok');
},
success: function(data){
},
});
});
});
</script>
HTML:
<form id="buy-form">
<div class="regular large gray">
<div class="content buy-form">
/* some code here */
<div class="item div-button">
<button id="buy-button" class="button anim" type="submit">Comprar</button>
</div>
</div>
</div>
</form>
----
EDIT
----
Problem solved! The error was in the before ajax. The correct term is beforeSend and not before. Thank you all for help.
You said it was a submit button and you do not cancel the default action so it will submit the form back. You need to stop that from happening.
$('#buy-button').click(function (e){
e.preventDefault();
/* rest of code */
Now to figure out why it is not calling success
$.ajax({
type: 'POST',
data: $('#buy-form').serialize(),
url: './ajax/buy_form.php',
dataType: 'json',
before: function(data){
console.log('ok');
},
success: function(data){
},
error : function() { console.log(arguments); } /* debug why */
});
});
My guess is what you are returning from the server is not valid JSON and it is throwing a parse error.
Try this
<script type="text/javascript">
$(document).ready(function() {
$('#buy-button').click(function (e){
e.preventDefault();
var abc = '<?php echo $var; ?>';
$.ajax({
type: 'POST',
data: $('#buy-form').serialize(),
url: './ajax/buy_form.php',
dataType: 'json',
beforeSend: function(data){
console.log('ok');
},
success:function(data){
}
});
});
});
And make sure that your php file return response

Passing POST variables from jQuery to PHP, want to update div

I am trying to pass the form value "New Value" from jQuery to a PHP script, and then update the "to_change" div from "Old value" to "New value". It seemed like the AJAX call succeeded, but the POST variables are not being sent to the PHP script, and when I use getJSON, I do not succeed. How could I resolve this issue?
Javascript/HTML code:
<html>
<head>
<script src = 'jquery-1.10.2.js'></script>
<script>
$(document).ready(function() {
$("#form_tmin").submit(function(event) {
var values = $(this).serialize();
$.ajax({
type: "POST",
url: "parameters_form2.php",
data: values,
dataType: "json",
success: function(data){
$.getJSON("parameters_form2.php", function(tmin) {
document.getElementById("to_change").innerHTML = tmin[1];
});
}
});
return false;
});
});
</script>
</head>
<body>
<div id="to_change">Old value</div>
<form id="form_tmin" name="form_tmin">
<input type="hidden" id="tmin_value" name="tmin_value" value="New value">
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
PHP code:
<?php
header('Content-Type: application/json');
if ($_POST["tmin_value"]) {
$tmin[1] = $_REQUEST["tmin_value"];
}
else {
$tmin[1] = "FAILURE";
}
echo json_encode($tmin);
?>
You already have json response in data just set this data in where ever you want to display. you don not need $.getJSON again.
try like this:
$(document).ready(function() {
$("#form_tmin").submit(function(event) {
var values = $(this).serialize();
$.ajax({
type: "POST",
url: "parameters_form2.php",
data: values,
dataType: "json",
success: function(data){
document.getElementById("to_change").innerHTML = data[1];
}
});
return false;
});
});
You already have the response of query, no need to use $.getJson again
Instead just use:
success: function(data){
$("to_change").html(data[1]);
}

Categories

Resources