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

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

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>

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.

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.

Calling AJAX is not working onclick of button

I am calling an API from AJAX,
When I am Calling AJAX like this,
$(function (){
$.ajax({
type:'GET',
url :"/tournament",
dataType: 'json',
success: function(data) {
console.log('success',data);
},
error:function(exception){
alert('Exception:'+exception);
}
});
});
This is working fine without any errors but when I am using this..
$('#btnadad').on('click',function (){
alert("ok");
$.ajax({
type:'GET',
dataType: 'json',
url :"/tournament",
success: function(data) {
console.log('success',data);
},
error:function(exception){
alert('Exception:'+exception);
}
});
});
This popups "error" alert,
can anybody help me whats the error?
HTML Body is Like this,
<form>
<h2>
<font color="#FFFFFF">
<br><br><input type="text" name="name" placeholder ="Tournament Name"><br>
<table>
<?PHP
//print_r($teams);
for ($i = 0; $i < $count; $i++) {
?>
<tr>
<td><input type="checkbox" name=<?php echo $taemId[$i] ?></td>
<td><?php echo $teamname[$i] ?></td>
</tr>
<?php
}
?>
</table>
<button id="btnadad">ADD</button>
</form>
<script src ="/js/myjs.js"></script>
here I am calling one API and Displaying the Checkboxes Dynamically.
I am checking The Console...when I am clicking button ,the alert box is popping up and in networks tab tournament path's status is cancelled .when I am clicking it on to see the response it shows fail to load response data.
I have Tried calling this function in same html file in tag but it is also not working.
<script>
function getOnClick()
{
alert("ok");
$.ajax({
type: 'GET',
url: "http://harshal:8888/tournament",
success: function(data) {
alert("no error in alert");
console.log('success', data);
},
error: function() {
alert("error in alert");
}
});
}
and calling it on button's onclick Event ut it also gives me the same result
Thanks For the Help Friends,your Efforts matters a lot to me,I am feeling glad to tell you that I just found the answer for this the below code makes it happened ..
$('#btnadad').on('click',function (e){
alert("ok");
$.ajax({
type:'GET',
url :"/tournament",
dataType: 'json',
success: function(data) {
console.log('success',data);
},
error:function(exception){alert('Exeption:'+exception);}
});
e.preventDefault();
});
$ajax error function takes 3 parameters. Jquery ajax error
A function to be called if the request fails. The function receives
three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a
string describing the type of error that occurred and an optional
exception object, if one occurred.
try changing like this
$('#btnadad').on('click',function (){
alert("ok");
$.ajax({
type:'GET',
dataType: 'json',
url :"/tournament",
success: function(data) {
console.log('success',data);
},
error:function(jqXHR,textStatus,errorThrown ){
alert('Exception:'+errorThrown );
}
});
});
I got the same issue. If you use onclick, do not use a form. In local environment, it is working, but when you go to production, the ajax request is cancelling. The solution is removing the form tag and adding a div tag.

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