Passing jquery variable into php script in a modal with ajax - javascript

i'm having problem getting the value of a variable into the modal which is supposed to be openning. i have tried using post but nothing changed. Both codes are in index.php.
This is the jquery script passing the value
$(document).ready(function () {
$(".issue").click(function () {
var x = $(this).attr("id");
$.ajax({
url: "index.php",
type: "GET",
data: {data1: x,},
success: function () {
$("#modal2").modal('show');
}
});
});
});
And i tried echoing the id of class .issue but it doesn't works
<div class="modal fade" role = "dialog" id = "modal2" aria-labelledby = "myModalLabel" aria-hidden = "true">
<div class="dialog">
<div class="modal-content">
<div class="modal-body"><?php echo $_GET["data1"]; ?></div>
</div>
</div>
</div>

You're missing the variable in the success method. It should be success:function(ajaxData){}
So in all:
var x = $(this).attr("id");
$.ajax({
url: "index.php",
type: "GET",
data: {data1: x,},
success: function (ajaxData) { // ajaxData is the return data from php
// add the data to the modal
$("#modal2 .modal-body").html(ajaxData);
$("#modal2").modal('show');
}
});
Are you sending the data server side to save it, or grab information from the database? If all you're trying to do is move the data to the modal, ajax isn't necessary.
Part of me suspects you're not properly calling and passing the data to php, if you really do need ajax. The php you send the ajax data to should be a separate file, that receives it, processes it, and echos it back to the ajax success function. Then the ajax function puts the data in the modal and displays the modal.
Hope one of those thoughts points you in the right direction.

Related

Ajax call to insert to database not working

I'm trying to do an Ajax call on button click to insert to a database through a PHP file. I want to use AJAX to achieve this, but it does not show the alert dialog on success nor does it insert the data to the database. Here is the code I have:
AjaxTest.html:
<button type="button" onclick="create()">Click me</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
function create () {
$.ajax({
url: "AjaxTestRegistration.php",
type: "POST",
data: {
'bid': 10,
'kid': 20
},
success: function (msg) {
alert("!");
}
});
}
</script>
AjaxTestRegistration.php:
<?php
include "connection.php";
include "Coupon.php";
$bid = $_GET['bid'];
$kid = $_GET['kid'];
Coupon::insertCoupon($bid, $kid);
?>
If I try to enter AjaxTestRegistration.php manually in the browser like this: ajaxtestregistration.php?kid=10&bid=5, the row gets inserted into the database.
wWhat could be the problem with this code? How to rectify that?
Your PHP handles GET requests.
$bid = $_GET['bid'];
But your ajax function tries to POST
type: "POST",
The easiest here is to get your data by $_POST in php.
I think you should try $__REQUEST method of php and also use $_POST method if you use post from ajax
$bid = $__REQUEST['bid'];
$kid = $__REQUEST['kid'];

Passing Javascript variable to PHP and then reloading page without refresh

How do you reload a page without re-fresh after sending a javascript variable to PHP via Ajax.
Below is an image of a webpage I'm creating which analyses asset performance.
What I'm trying to do is the following.
When a user selects a test block with in the graph, the selcection box is updated with all subtests within that specific test block. However, I do not want to refresh the page. I have managed to send the the selected tested block to the PHP code via ajax, but can not get ajax to reload the page without a refresh.
Currently, when a test block is selected, the label is return to PHP and is stored in the $_SESSION['label'] variable. This is then used in the panel header #subtest-chart-select. However the label will not update without a page refresh which is what I want to avoid.
Ajax:
$("#test_block_chart").click(
function(evt){
var activePoints = myNewChart.getElementsAtEvent(evt);
if (activePoints[0]) {
var chartData = activePoints[0]['_chart'].config.data;
var idx = activePoints[0]['_index'];
var label = chartData.labels[idx];
//alert(label);
$.ajax(
{
url:'test_performance.php',
type: 'POST',
datatype: 'json',
data: {'label':label}, // post to location.php
success: function(label) {
// success
},
error: function(label) {
alert("There may an error on uploading. Try again later");
}
});
}
});
});`
PHP:
session_start();
if(isset($_POST['label']))
{
$_SESSION['label'] = $_POST['label'];
}
PHP echo HTML
<?php
echo '<div class="row">
<div class="col-lg-12 subtest-select">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title" id="subtest-chart-select"><i class="fa fa-bar-chart-o fa-fw"></i>' . $_SESSION['label'] . ' Subtest Select </h3>
</div>
<select class="form-control">
<option>1</option>
</select>
</div>
</div>
</div>'
?>
I'm still to write the PHP code to update the options of subtests within the selected test block.
Any help will be greatly appreciated as I've been trying to get this working for what seems like forever.
In $.ajax() set
dataType: 'text',
In your $.ajax() success function say:
success: function(data) {
$('.inside_whereever_you_want_to_show_this').html(data);
}
Edit:
To update only one value on page you can:
a) in PHP print out only this value (so that whole page would be only this value).
<?php echo $_SESSION['label']
and in HTML put a span around the bit you want to update (avoid constructing longer strings in javascript, all constant parts should be in HTML)
<h3 class="panel-title" id="subtest-chart-select"><i class="fa fa-bar-chart-o fa-fw"></i><span class="subtest-updateable">' . $_SESSION['label'] . '</span> Subtest Select </h3>
then you can update only your needed bit with whole response
success: function(data) {
$('.subtest-updateable').html(data);
}
b) better (in systematic approach means) would be use json response, where you can return more isolated variables as well:
Set dataType to json.
Success function would use $('.subtest-updateable').html(data.label)
In PHP print json_encode(array('label' => $_SESSION['label'], 'someelse' => $someother_variable ))
You still should put span (or some other html element) around updateable bits of your page (to avoid writing constants into your javascript)
In your success function you need to update the part of the DOM that you want to change. On the PHP side just return your blade partial or whatever HTML you want to display.
$(document).on('submit', 'form#form-grad', function (e) {
e.preventDefault();
var context = $(this);
var thisForm = context.closest('form');
$.ajax({
url: thisForm.attr('action'),
method: 'PUT',
data: thisForm.serialize(),
success: function (response) {
$('#updatearea').html(response.pt_html);
// Close grading form
}
});
return false;
});

How to send data from a div tag with ajax without the need for a form?

I have a div as follows:
<div id="test-container">
<div id="test-one">
<p id="data">Example to send</p>
</div>
</div>
I need to send what's inside the <p> "Example to send"
As I can send it without the need to use a form, only using ajax, jQuery and PHP
Thanks!
You can get the content of p using this:
var content = $("#data").html();
Then you can send it using ajax this way:
$.post("url_to_some_file.php", content, function(response){
//Here you can get the response from the server
});
you need an event to get trigger the ajax function first
$('#button').click(function(){
var data = $('.data').html()
$.ajax({
url: 'url_to_server',
data: data,
type: 'POST',
success: function(result){
alert(result)
}
})
})
var getdata = $("#data").html(); // get the text inside of the p tag
$.post("yourphpfile.php", {data: getdata}).done(function(r) {
alert("Data sent!"); // show alert box after the query sent
});
to get the data via PHP
<?php
$data = $_POST['data'];
?>

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.

Sending form data with ajax echo data with php not displaying

Im learning Ajax...normally I dont like posting about a subject I know very little of but I believe Im on the right path here (maybe not...?) so I will take a chance to find out.
Ive got 3 select boxes each box populates with values based on the the selection of the box before it:
Everything is working perfectly, when the user clicks submit I want to send the 3 textbox values to 3 php variables and echo it on the same page...
Now my data is not echoing (the data of the variables are not displaying) but when I look in my console on firefox I can see the value of the variables...
Here is the selection made on the select boxes
Here is what im seeing in my console
Yet it is does not echo on the page....?
jQuery(document).click(function(e){
var self = jQuery(e.target);
if(self.is("#resultForm input[type=submit], #form-id input[type=button], #form-id button")){
e.preventDefault();
var form = self.closest('form'), formdata = form.serialize();
//add the clicked button to the form data
if(self.attr('name')){
formdata += (formdata!=='')? '&':'';
formdata += self.attr('name') + '=' + ((self.is('button'))? self.html(): self.val());
}
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: formdata,
success: function(data) {
console.log(data);
}
});
}
});
PHP below form
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$sport = $_POST['sport'];
$round = $_POST['round'];
$tournament=$_POST['tournament'];
echo $sport;
echo $round;
echo $tournament;
}
I don't see anything in your code that would make the values display on the page. You would need to either do some DOM insertion in your AJAX success function, or do a full page refresh and echo the data out via PHP (but that would probably defeat the purpose of doing an AJAX call in the first place.)
If you want to go the AJAX route, I would suggest editing your PHP to the following:
echo json_encode(array(
'sport' => $sport,
'round' => $round,
'tournament' => $tournament
));
This will return a JSON object for your jQuery AJAX call to consume.
In your jQuery success function, do something with those values, like so:
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: formdata,
dataType: 'json',
success: function(data) {
$('<div></div>').text(data.sport).appendTo('body');
$('<div></div>').text(data.round).appendTo('body');
$('<div></div>').text(data.tournament).appendTo('body');
}
});
Note the additional dataType argument to $.ajax. To do it the right way, you'll also want to set your headers in your PHP response to "application/json"
You ajax is just displaying the output in console. Change the ajax success to display it in page.
Make changes after success as:
success:function(data){
$('someelementclassorid').text(data);
}

Categories

Resources