pass data($post) to php file using javascript without callback - javascript

I need to pass data from HTML page to PHP page But without data callback ....
i'm used two method but One of them did not succeed
1)
$.ajax({
type: "POST",
url: 'phpexample.php',
data: {voteid: x },
success: function(data)
{
alert("success! X:" + data);
}
});
2)
$.post("getClassStudent.php",
{
},
function(data){
$("#div_id.php").html(data);
}
);

as i can understand, you just want to send info to a php script and don't need the response, is that right?
try this
$.post("phpexample.php", {voteid:x});
or simply remove the "succes" function from the equation if you feel more confortable using $.ajax instead of $.post
$.ajax({
type: "POST",
url: 'phpexample.php',
data: {voteid: x }
});
your fisrt example is correct, the second is not well formed.
more info:
http://api.jquery.com/jquery.post/
EDIT: to help you some more :)
<button type="button" id="element-id">click</button>
<button type="button" class="class-name">Click</button>
$(document).ready(function(){
//if you are marking ans element by class use '.class-name'
$(".class-name").click(function(){
$.post("getClassStudent.php");
});
//if marking by id element use '#id-name'
$("#element-id").click(function(){
$.post("getClassStudent.php");
});
});
be carefful with the markings, for debuggin try to use "console.log()" or "alert()" so you can see where is the problem and where the code crushes.

var formData = {
'voteid' : 'x',
};
$.ajax({
type : 'POST',
url : 'phpexample.php',
data : formData, // our data object
dataType : 'json',
encode : true
}).done(function(data) {
console.log(data);
});

Related

Send variable from Javascript to PHP using AJAX post method

I am trying to pass a variable from javascript to php, but it doesn't seem to be working and I can't figure out why.
I am using a function that is supposed to do three things:
Create a variable (based on what the user clicked on in a pie chart)
Send that variable to PHP using AJAX
Open the PHP page that the variable was sent to
Task one works as confirmed by the console log.
Task two doesn't work. Although I get an alert saying "Success", on test.php the variable is not echoed.
Task three works.
Javascript (located in index.php):
function selectHandler(e) {
// Task 1 - create variable
var itemNum = data.getValue(chart.getSelection()[0].row, 0);
if (itemNum) {
console.log('Item num: ' + itemNum);
console.log('Type: ' + typeof(itemNum));
// Task 2 - send var to PHP
$.ajax({
type: 'POST',
url: 'test.php',
dataType: 'html',
data: {
'itemNum' : itemNum,
},
success: function(data) {
alert('success!');
}
});
// Task 3 - open test.php in current tab
window.location = 'test.php';
}
}
PHP (located in test.php)
$item = $_POST['itemNum'];
echo "<h2>You selected item number: " . $item . ".</h2>";
Thanks to anyone who can help!
From what i can tell you don't know what ajax is used for, if you ever redirect form a ajax call you don't need ajax
See the following function (no ajax):
function selectHandler(e) {
// Task 1 - create variable
var itemNum = data.getValue(chart.getSelection()[0].row, 0);
if (itemNum) {
console.log('Item num: ' + itemNum);
console.log('Type: ' + typeof(itemNum));
window.location = 'test.php?itemNum='+itemNum;
}
}
change:
$item = $_GET['itemNum'];
echo "<h2>You selected item number: " . $item . ".</h2>";
or better you do a simple post request from a form like normal pages do :)
Try this:
success: function(data) {
$("body").append(data);
alert('success!');
}
Basically, data is the response that you echoed from the PHP file. And using jQuery, you can append() that html response to your body element.
you should change this code
'itemNum' : itemNum,
to this
itemNum : itemNum,
Seems contentType is missing, see if this helps:
$.ajax({
type: 'POST',
url: 'test.php',
dataType: "json",
data: {
'itemNum' : itemNum,
},
contentType: "application/json",
success: function (response) {
alert(response);
},
error: function (error) {
alert(error);
}
});
you can easily pass data to php via hidden variables in html for example our html page contain a hidden variable having a unique id like this ..
<input type="hidden" id="hidden1" value="" name="hidden1" />
In our javascript file contains ajax request like this
$.ajax({
type: 'POST',
url: 'test.php',
data: {
'itemNum' : itemNum,
}
success: function (data) {
// On success we assign data to hidden variable with id "hidden1" like this
$('#hidden1').val(data);
},
error: function (error) {
alert(error);
}
});
Then we can access that value eighter on form submit or using javascript
accessing via Javascript (Jquery) is
var data=$('#hidden1').val();
accessing via form submit (POST METHOD) is like this
<?php
$data=$_POST['hidden1'];
// remaining code goes here
?>

Run if/else script with only part of a URL

I am trying to edit my Javascript to pull different data via an AJAX call based upon only part of a URL. Currently, my if/else script looks like this:
if (window.location.href=="london") {
$.ajax({
url: '../financial-reports/outwork-vs-expenses-data-london.php',
dataType: 'json'
}).done(function(data) {
data.forEach(function(item) {
dates.push(item.date);
expenses.push(item.expense);
outworks.push(item.outwork);
expensesOutworks.push(item.expensesOutwork);
budgetedOutworks.push(item.budgetedOutwork);
myExpensesChart.update();
});
});
} else {
$.ajax({
url: '../financial-reports/outwork-vs-expenses-data.php',
dataType: 'json'
}).done(function(data) {
data.forEach(function(item) {
dates.push(item.date);
expenses.push(item.expense);
outworks.push(item.outwork);
expensesOutworks.push(item.expensesOutwork);
budgetedOutworks.push(item.budgetedOutwork);
myExpensesChart.update();
});
});
}
This doesn't work as currently written since if window.location.href=="london") is only part of the URL, not the full URL. Is there a way to edit this script to run only based off of the last bit of the page URL? For example: /london, /nw, etc.? Is there a better way to accomplish this task?
Instead of
if (window.location.href=="london") {
Use below code
var URL = window.location.href;
if(URL.indexOf("london") !== -1)
The .indexOf function will find out a substring is exist or not in a string. And in your case you wants "london" is exist or not in URL.
I assume you are asking, when the url something like 'https://example.com/london' , so you just want to include or get the value of london. below code will help to provide always last bit of value of the url.
window.location.pathname.splitOnLast('/')[1]
it will give you '/london'. or you can just check the existence of theondon in the url.
Firstly it is not necessary to use if else like above
You can use like below
var dataurl = document.URL
$.ajax({
url: 'somepage.php',
type: 'post',
dataType: 'json',
success: function (data) {
console.log(data);
},
data: dataurl
});
in somepage.php file you can process the data however you want based on the dataurl
And also in javascript you can do like below
var urlTopost="other.php";
if(document.url.indexOf("london")!==-1)
{
urlTopost="london.php";
}
$.ajax({
url: urlTopost,
type: 'post',
dataType: 'json',
success: function (data) {
console.log(data);
},
data: dataurl
});

Ajax success and laravel

I'm currently working on a project using Laravel platform.
I'm trying to delete data from a model asynchronously using ajax. And when all is done my data should be removed from the table. My code runs perfectly, data are being removed from my database , yet "tr" elements arent really faded or removed. Here is my code :
ajax sucess not really working.
$(document).on('click', '.btn-remove-interview' , function() {
var id = $(this).attr('data-interview-id');
$.ajax({
url: './manage/interviews/destroy/'+id ,
type: 'post',
dataType: 'json',
data: id,
success: function (data) {
$(this).parents("tr").remove();
}
});
});
Use
$(this).closest('tr').remove();
Instead of
$(this).parents("tr").remove();
The problem is that the success function callback within your ajax request no long refers to the button when you use this. You need to get an explicit variable to the button if you want to use it.
$(document).on('click', '.btn-remove-interview' , function() {
// Get this button as a variable so we can use it later
var el = $(this);
var id = $(this).attr('data-interview-id');
$.ajax({
url: './manage/interviews/destroy/'+id ,
type: 'post',
dataType: 'json',
data: id,
success: function (data) {
$(el).parents("tr").remove();
}
});
});
Solution was by removing dataType json . My function doesnt return any data .

unable to show record using webservice

this code is working fine but not showing records. in alert if i am getting record from file its working fine.
$j().ready(function(){
var result =$j.ajax({
type: "GET",
url: "webService address",
dataType :'json',
contentType:'application/json; charset =utf-8',
success:function(data)
{
$j.each(data, function(index,element){
alert("Successful here: "+element);
});
}
});
alert("result"+result);
});
Welcome to the wonderful world of asynchronous ...
First of all, jQuery get doesn't return the data, that needs to be handled by the callback (which is working as from your post)
var result = null;
$j(document).ready(function(){
$j.ajax({
type: "GET",
url: "webService address",
dataType :'json',
contentType:'application/json; charset =utf-8',
success:function(data)
{
result = data;
$j.each(data, function(index,element){
alert("Successful here: "+element);
});
}
});
alert("result"+result);
});
This might not work as well since jQuery ajax is asynchronous and the alert may pop up while the GET is still reading data and not yet ready !!!!
Check Jquery ajax doc:
$.ajax({
type: "GET",
url: "webService address",
dataType :'json',
contentType:'application/json; charset =utf-8'
}).done(function(data) {
console.log(data);
});
The javascript is not waiting AJAX to finish, it moves on. That is why its called asynchronous . If you need synchronous call, use async: false.

Jquery - parse XML received from URL

I have this URL, that I supposedly should receive an XML from. So far I have this:
function GetLocationList(searchString)
{
$.ajax({
url: "http://konkurrence.rejseplanen.dk/bin/rest.exe/location?input=" + searchString,
type: "GET",
dataType: "html",
success: function(data) {
//Use received data here.
alert("test");
}
});
Tried to debug with firebug, but it doesn't go into the success method.
Though, in DreamWeaver it is able to post a simple alert, which is inside the success method.
I tried writing xml as dataType, but it doesn't work (in DreamWeaver) when I write alert(data).
But it shows an alert with the entire XML, when I write html as dataType.
How do I get the XML correctly, and how do I parse and for example get the "StopLocation" element?
Try to add an Error function as well.
See enter link description here
This will give you all the informations you need to debug your code with Firefox.
$.ajax({
url: "http://konkurrence.rejseplanen.dk/bin/rest.exe/location?input=" + searchString,
type: "GET",
dataType: "html",
success: function(data) {
//Use received data here.
alert("test");
},
error: function(jqXHR, textStatus, errorThrown ){
// debug here
}
});
you need to parse it first, and then you can search for the attributes. like this.
success: function(data) {
var xml = $.parseXML(data)
$(xml).find('StopLocation').each(function()
{
var name = $(this).attr('name');
alert(name);
}
);
this will give you the name of each StopLocation.
hope this helps, you can use the same method for all other attributes in the document also.

Categories

Resources