Passing arrays js variable to php - javascript

Currently I have stored variables in a Javascript array. The goal here is to turn them into PHP variables so that I can use these variables and insert them into my database.
The problem with this code is that the AJAX part doesn't work. Please get me in the right direction as I am extremely new to AJAX. I did try to read about them but still do not understand much. Doing it without refreshing the page is not necessary. Methods other than AJAX are welcomed.
Here is my current code:
<button onclick="Bookings()">Book</button>
<script>
function Bookings() {
var t2Cells = document.getElementsByClassName("t2");
for (var i = 0; i < t2Cells.length; i++) {
var t2CellsIndex [i] = t2Cells[i].cellIndex
var t2CellsRow [i] = t2Cells[i].parentNode.rowIndex
//alert('Coordinates are: '+t2Cells [i].cellIndex+'x'+t2Cells [i].parentNode.rowIndex);
var tbl = document.getElementById("tblMain");
//alert (tbl.rows[0].cells[t2CellsIndex].innerHTML);
var studioSelected = tbl.rows[0].cells[t2CellsIndex].innerHTML
var Timeselected = tbl.rows[t2CellsRow].cells[0].innerHTML
$.ajax({
type: "POST",
url: 'bookingconfirm.php',
data: "studioSelected=" + studioSelect,
success: function(data) {
alert("success!");
}
});
}
}
</script>
<?php
//bookingconfirmed.php
if (isset($_POST['studioSelect'])) {
$uid = $_POST['studioSelect'];
//steps to insert into database.

First, you should move ajax call outside of foreach
var usefulData = [];
var t2Cells = document.getElementsByClassName("t2");
for (var i = 0; i < t2Cells.length; i++) {
var t2CellsIndex [i] = t2Cells[i].cellIndex
var t2CellsRow [i] = t2Cells[i].parentNode.rowIndex
//alert('Coordinates are: '+t2Cells [i].cellIndex+'x'+t2Cells [i].parentNode.rowIndex);
var tbl = document.getElementById("tblMain");
//alert (tbl.rows[0].cells[t2CellsIndex].innerHTML);
var studioSelected = tbl.rows[0].cells[t2CellsIndex].innerHTML
// add data to array
usefulData.push(studioSelected);
var Timeselected = tbl.rows[t2CellsRow].cells[0].innerHTML
}
$.ajax({
type: "POST",
url: 'bookingconfirm.php',
data: {'usefuldata': usefulData},
success: function(data) {
alert("success!");
}
});
Then in your php file:
if (isset($_POST['usefuldata'])) {
var_dump($_POST['usefuldata']);
}

Related

Replace javascript variable without id or class

I have this javascript and once the AJAX process is executed I want to replace this variable to some other variable.
window.onload = function() {
oldvariable = [];
var chart = new Chart("Container2", {
data: [{
type: "column",
dataPoints: oldvariable
}]
});
}
When I process the AJAX request and fetch JSON data which is stored in oldvariable, it is not written so I have few options. I tried ads they are working in HTML but not under script tag.
If I can define oldvariable='<div class="second"></div>'; and replace this with processed JSON data then it is working and giving correct output in HTML but in javascript < tag is not allowed as variable so we cant define oldvariable like that.
$( "div.second" ).replaceWith( ''+newvariable +'' );
So is there anyway I can replace javascript variable as HTML tags are not allowed in variable and without tag javascript can't replace.
I have one more probable solution.regex. Search for oldvariable in entire HTML code and replace with newvariable but that process will be very slow so what is the best way to do this.
My vairables are globally defined and AJAX request is in external file and above codes are embeded in HTML.
========edit
how we can replace oldvariable with newvariable in above javascript
====== ajax code- variable name is different
$(document).ready(function() {
(function() {
$('#upload-form2').ajaxForm({
dataType: 'json',
success: function(data) {
var oldvariable = '',
downlo;
for (var i = 0; i < data.length; i++) {
downlo = data[i];
oldvariable += '' + downlo.ndchart + '';
}
$('#chek').html(oldvariable );
}
})
})();
});
you need to update chart datapoints and re-render the chart after ajax success like this
ajax :
...
success:function(response)
{
chart.options.data[0].dataPoints=response;
//response is (array) of dataSeries
chart.render();
}
.......
update 1 : As per your code data should be updated like this
.....
success:function(data) {
var new_data = [];
for (var i = 0; i < data.length; i++)
{
new_data.push({y:data[i].ndchart });
}
chart.options.data[0].dataPoints=new_data;
chart.render();
}
.....
update 2:
$(document).ready(function() {
(function() {
$('#upload-form2').ajaxForm({
dataType: 'json',
success: function(data) {
var new_data = [];
for (var i = 0; i < data.length; i++)
{
new_data.push({y:data[i].ndchart });
}
chart.options.data[0].dataPoints=new_data;
chart.render();
}
})
})();
});

Dropdown list with AJAX request and response back in JSON format not working

I want all state name of id 1 from static PHP array using ajax request and convert response in json.why it is not running, or it is a wrong way to do so??
country is coming from database and got set.
$(document).ready(function()
{
$("#country_drop").change(function()
{
var cuid = $(this).val();
alert(cuid);
$.ajax(
{
url: 'get_state.php',
type: 'post',
data: {id2:cuid},
dataType: 'json',
success:function(data)
{
var len = data.length;
$("#state_drop").empty();
$('#state_drop').html('<option value="">Select state first</option>');
for( var i = 0; i<len; i++)
{
// var id = data[i]['id'];
//var name = data[i]['name'];
// $("#state_drop").append('<option value="'+id+'">'+name+'</option>');
$('#state_drop').append('<option value="'+data[i].id+'">'+ data[i].name+'</option>');
}
}
});
});
});

How to get data from button attributes?

There are several buttons (they creates dynamically)
<button class="common" id="1.1" status="sale" oncontextmenu="rightButton('1.1'); return false" onclick="addOptions('1.1')" number="1">1</button>
I need to get attributes (class, id, status, number) and insert them into object array. Then input to database.
function saveScheme()
{
var table = document.getElementById('schemeTable');
var elements = table.getElementsByTagName('button');
var arrayIdButtons = {};
for(var i = 0; i<elements.length; i++)
{
arrayIdButtons[i] = {};
for(var j = 0; j<4; j++)
{
arrayIdButtons[i]["coord"] = elements.item([i]).id;
arrayIdButtons[i]["status"] = elements.item([i]).status;
arrayIdButtons[i]["type"] = elements.item([i]).class;
arrayIdButtons[i]["number"] = elements.item([i]).number;
}
}
console.log(arrayIdButtons);
var data='data=' + JSON.stringify(arrayIdButtons,"", 2);
$.ajax({
type: 'POST',
url: "handler.php",
data: data,
cache: false,
data: data,
success: function(data) {
alert(data)
}
});
}
result of this code(console.log(arrayIdButtons);):
Since you're already using jQuery, you can access the attributes of an element using .attr(). For example:
$('.common').attr('number');
Or, without jQuery,
elements[i].getAttribute('number');
Use HTML5 API data
<button class="common" id="1.1" data-status="sale" oncontextmenu="rightButton('1.1'); .....</button>
So,
elements.item([i]).data('status'); //if jquery enabled
You can try this html. then,
<button class="common" data-id="1.1" data-status="sale" data-number="1">1</button>
If DOM is not loaded, then you can get this by
$(document).ready(function(){
$(".common").on("click",function(){
var data_id = $(this).attr('data-id');
var data_status = $(this).attr('data-status');
var data_number = $(this).attr('data-number');
console.log(data_id);
console.log(data_id);
console.log(data_id);
});
});
And if DOM is already loaded you can get them by
$(document).on("click",".common",function(){
var data_id = $(this).attr('data-id');
var data_status = $(this).attr('data-status');
var data_number = $(this).attr('data-number');
console.log(data_id);
console.log(data_id);
console.log(data_id);
});
Then you can push this is an array. Note - this will give you the attributes of only the button was clicked

Retrieving data from myapifilms.com api

I am following a tutorial on YouTube showing how to get data from the myapifilms.com api and I am having trouble rendering the data to HTML. Currently my ajax call is working and the data is showing in the console. The problem I am having is getting the data to show on the page itself. I searched through the question already asked but had no luck. Here's my js code so far:
$(document).ready(function(){
$("#searchMovie").click(searchMovie);
var movieTitle = $("#movieTitle");
var table = $("#results");
var tbody = $("#results tbody"); //table.find("tbody");
function searchMovie() {
var title = movieTitle.val();
$.ajax({
url: "http://www.myapifilms.com/imdb/idIMDB?title="+ title +"&token= + token goes here +&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=1&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0&quotes=0&fullSize=0&companyCredits=0",
dataType: "jsonp",
success: renderMovies
})
function renderMovies(movies) {
console.log(movies);
tbody.empty();
for(var m in movies) {
var movie = movies[m];
var title = movie.title;
var plot = movie.simplePlot;
var posterUrl = movie.urlPoster;
var imdbUrl = movie.urlIMDB;
var tr = $("<tr>");
var titleTd = $("<td>").append(title);
var plotTd = $("<td>").append(plot);
tr.append(titleTd);
tr.append(plotTd);
tbody.append(tr);
}
}
}
});
I feel like I am so close but can't quite figure what I am missing. Again I was following a tutorial so if there's a better way to accomplish this goal I'm definitely open to suggestions.
Update:
I changed my code to this and I'm getting undefined in the browser. I changed the for loop to this
success: function (movies) {
console.log(movies);
tbody.empty();
for (var m in movies) {
$(".movies").append("<h3>"+ movies[m].title +"</h3>");
$(".movies").append("<h3>"+ movies[m].plot +"</h3>");
}
}
I figured out a solution, instead of using myapifilms, I used the tmdb api instead. Changing my code to this worked:
var url = 'http://api.themoviedb.org/3/',
mode = 'search/movie?query=',
input,
movieName,
key = 'myapikey';
//Function to make get request when button is clicked to search
$('button').click(function() {
var input = $('#movie').val(),
movieName = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + input + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
console.dir(json.results);
for (var i = 0; i < json.results.length; i++){
var result = json.results[i];
$(".moviesContainer").append('<div class="movies col-md-12">'+
'<img class="poster" src="http://image.tmdb.org/t/p/w500'+ result.poster_path +'" />'
+'<h3>'+ result.title +'</h3>'
+'<p><b>Overview: </b>'+ result.overview +'</p>'
+'<p><b>Release Date: </b>'+ result.release_date +'</p>'
+'</div>');
}
},
error: function(e) {
console.log(e.message);
}
});
});

Fetch mulitple values using Jquery post getting undefined value

Below is my jquery ajax method
<script type="text/javascript">
$(document).ready(function () {
$('#c_select').change(function(){
var one = 10;
var two = 20;
var three = 30;
var four = 40;
$.ajax({
type:'post',
url:'getvalues.php',
dataType: JSON,
success:function(resp){
alert(resp.first);
}
error:function(resp){
alert(resp.first);
}
});
});
});
</script>
Below given file is where i get the values (PHP File)
<?php
$output = array('first'=>'Steven',
'last'=>'Spielberg',
'address'=>'1234 Unlisted Drive');
echo json_encode($output,JSON_FORCE_OBJECT);
?>
success part is not getting executed i am getting undefined error
Try following code, it should work
$(document).ready(function() {
$('#c_select').change(function() {
var one = 10;
var two = 20;
var three = 30;
var four = 40;
$.ajax({
type: 'post',
url: 'getvalues.php',
dataType: 'json',
success: function(resp) {
alert(resp.first);
},
error: function(resp) {
}
});
});
});

Categories

Resources