I'm trying to pass a string from PHP onto a javascript file using the $.getJSON function but it keeps alerting 'getJSON request failed'. So far, I've tried using the $.ajax with and without async: true and the regular $.get jQuery functions but I get the same problem. I've also tried including the
$( document ).ready() function.
The enterComment function is executed upon sending a form in the php file 'pannkakor.php'. Just to be clear, the enterComment function does execute when clicking the button but the $.getJSON function fails.
Also worth noting is that I am using the knockout.js framework.
What am I doing wrong?
PHP CODE SNIPPET:
<?php
$username = "test";
$array = array('username' => $username);
echo json_encode($array);
?>
Javascript code:
this.enterComment = function (comment) {
$.getJSON("localhost:8888/Sem4/recept/pannkakor.php", function (jsonData) {
alert("TESTING THAT IT WORKS");
})
.done(function () {
alert('getJSON request succeeded!');
})
.fail(function () {
alert('getJSON request failed');
});
};
HTML/PHP FOR THE FORM SUBMITTED:
<form data-bind="submit: enterComment.bind($data,$data.comment )">
<input type="text" data-bind="value: $data.comment"/>
<button type="submit">Submit Comment</button>
</form>
Related
I am trying to send js variables from my js file to another php file when the user hits "FINISH" on the main php page. Here is my code so far:
map.php
<form action="./finalmap.php">
<input class="finish-button" type="submit" value="FINISH" onclick="sendData();" />
</form>
map.js
function sendData() {
$.ajax({
method: "POST",
url: "../finalmap.php",
data: {
selectedLoc: selectionArray,
startLoc: start,
endLoc: end,
dist: distance,
locTypes: allLocations
},
beforeSend : function(http) { },
success : function(response,status,http) {
alert(response);
},
error : function(http,status,error) {
$('.response').html("<span class='error'>Something went wrong</span>");
$(".response").slideDown();
}
});
}
finalmap.php
<?php
$data = $_POST['data'];
echo $data;
?>
Post is successful and I'm able to see the contents(my code) in my finalmap.php from the alert command. When I try to console.log $data in finalmap.php, it is empty/null.
My goal is to send the data to finalmap.php and redirect to it.
To solve this problem, you must reduce what you're testing to one thing at a time. Your code has errors and is incomplete. So let's start with the errors first: If you're using AJAX, you don't want HTML to submit the form in the regular way. If you get a page refresh, your AJAX didn't work.
<button type="button" id="submit-button">FINISH</button>
Note, no <form> is needed; you're submitting through AJAX.
Next, you need to be sure that your ajax function is being executed (since you're using $.ajax, I presume you have JQuery loaded):
<button type="button" id="submit-button">FINISH</button>
<script>
// all listener functions need to wait until DOM is loaded
$(document).ready(function() {
// this is the same idea as your onclick="sendData();
// but this separates the javascript from the html
$('#submit-button').on('click', function() {
console.log('hello world');
});
});
</script>
You use your web console to see the console.log message.
Now, try out the ajax command with a simple post:
<button type="button" id="submit-button">FINISH</button>
<script>
// all listener functions need to wait until DOM is loaded
$(document).ready(function() {
$('#submit-button').on('click', function() {
$.ajax({
method: "POST",
// "./finalmap.php" or "../finalmap.php"?
url: "../finalmap.php",
data: {foo: 'bar'},
success: function(response){
console.log('response is: ');
console.log(response);
}
});
});
});
</script>
finalmap.php
<?php echo 'This is finalmap.php';
If you see This is finalmap.php in the web console after pressing the button, then you can try sending data.
finalmap.php
<?php
echo 'You sent the following data: ';
print_r($_POST);
See where we're going with this? The way to eat an elephant is one bite at a time.
./finalmap.php is not a thing.
Instead the code must look like this:
<form action="/finalmap.php">
<input class="finish-button" type="submit" value="FINISH" onclick="sendData();" />
</form>
Try using this instead.
EDIT: OOPS SORRY, I JUST CPED AND PASTED.
How can I post jQuery data and receive on the same file without passing through the URL as a variable (eg. test.php?data=xxx).
For example here's the response.data that I can see in the console log.
function (response) {
console.log(response.data);
},
I want to post that data and receive on the same file. I have tried following:
function (response) {
//console.log(response.data);
$.post(window.location.href, {json_data: response.data});
},
but when in the body of same file I print
print_r($_POST);
it does not display anything.
Make sure that response.data is Type: PlainObject or String. See more here on PlainObjects
UPDATE
Here is a video that describes what this code sample does.
Code Sample
<?php
if (empty($_POST)) :
?>
Nothing was posted, please click there \/<br><br>
<?php
else :
echo 'You posted: '.print_r($_POST['json_data'], 1).'<br><br>';
endif;
?>
click here (simple string)<br>
click here (plain object)
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
function fake_simple_response (response) {
console.log(response);
$.post(window.location.href, {json_data: response});
}
</script>
If you want to use POST, one way is to create a form and submit it with jQuery.
<form id="form-id" method="post" action="">
<input type="hidden" value="hello world" />
</form>
<script>
$('#form-id').submit();
</script>
I'm trying to post data on my HTML code to CI with Ajax. But I got no response?
Here is my JS Code
$(document).ready(function(){
$("#simpan").click(function(){
nama_pelanggan = $("#nama_pelanggan").val();
telp = $("#telp").val();
jQuery.ajax({
type: "POST",
url: "http://192.168.100.100/booking_dev/booking/addBookingViaWeb/",
dataType: 'json',
data : {
"nama_pelanggan":nama_pelanggan,
"telp":telp,
},
success: function(res) {
if (res){
alert(msg);
}
}
});
});
});
And here is my form
<form>
Nama Pelanggan <br>
<input type="text" name="nama_pelanggan" id="nama_pelanggan"><br>
Telepon<br>
<input type="text" name="telp" id="telp"><br>
<input type="button" name="simpan" id="submit" value="Simpan">
</form>
and here is my contoller function code
public function addBookingViaWeb(){
$data = array(
'nama_pelanggan' => $this->input->post('nama_pelanggan'),
'telp'=>$this->input->post('telp')
);
echo json_encode($data);
}
Here is my post param
But I got no response
any idea?
add method in from if you use post then
<form method="post" action ="" >
Try using JQuery form serialize() to declare which data you want to post. It automatically put your form input into ajax data. Example :
first set ID to your form tag
<form id="form">
then
$.ajax({
type:'POST',
url : 'http://192.168.100.100/booking_dev/booking/addBookingViaWeb/',
data:$('#form').serialize(),
dataType:'JSON',
success:function(data){
console.log(data);
}
});
First problem I see is in your ajax submission code. Change
$("#simpan").click(function(){
to
$("#submit").click(function(event){
Notice that I added the event parameter. You now need to prevent the default submission behavior. On the first line of your click method add
event.preventDefault();
Now I'm assuming that your url endpoint http://192.168.100.100/booking_dev/booking/addBookingViaWeb/ can handle POST requests. Usually this is done with something like PHP or Ruby on Rails. If I was doing this in PHP I would write something like the following:
<?php
$arg1 = $_POST["nama_pelanggan"];
$arg2 = $_POST["telp"];
// do something with the arguments
$response = array("a" => $a, "b" => $b);
echo json_encode($response);
?>
I personally don't know anything about handling POST requests with js (as a backend) but what I've given you should get the data over there correctly.
I got solution for my problem from my friend xD
just add header("Access-Control-Allow-Origin: *"); on controller function
Thank you for helping answer my problem.
I am trying to pass a variable from js to a backoffice page.
So far I've tried using a form and submitting it from javascript (but that refreshes the page, which I don't want)
I ditched the form and when for an iframe (so the page doesn't reload everytime the data is submitted). The function is run every few seconds (so the form should be submitting):
<iframe style="visibility:hidden;display:none" action="location.php" method="post" name="location" id="location">
<script>
/*Some other stuff*/
var posSend = document.getElementById("location");
posSend.value = pos;
posSend.form.submit();
</script>
However my php page does not display the value posted (im not quite sure how to actually get the $_POST variable):
<?php
$postion = $_POST['location'];
echo $_POST['posSend'];
echo "this is the";
echo $position;
?>
I also tried $.post as suggested here Using $.post to send JS variables but that didn't work either.
How do I get the $_POST variable value? I cannot use $_SESSION - as the backoffice is a different session. What is the best method to do this?
EDIT I'd rather avoid ajax and jquery
And i think you no need to use form or iframe for this purpose . You just want to know the user onf without refreshing then use the following method with ajax.
index.html the code in this will
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script>
navigator.geolocation.getCurrentPosition(function(position)
{
pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
$.ajax(
{
url:'location.php',
type: 'POST',
datatype: 'json',
data: {'pos':pos}, // post to location.php
success: function(data) {
aler(data);
// success
},
error: function(data) {
alert("There may an error on uploading. Try again later");
},
});
});
</script>
location.php
echo "position :=".$_POST['pos'];
Instead of using iframe to submit your form with out reloading you submit form using ajax call.
$.ajax({
type: "POST",
url: url,
data: $("#formId").serialize(), // This will hold the form data
success: success, // Action to perform on success
dataType: "JSON" or "HTML" or "TEXT" // return type of function
});
There are various alternative to submit the form without reloading the page check here
Thanks
You can use plugin ajaxForm. On action and method you can form options
$(function() {
$('#form_f').ajaxForm({
beforeSubmit: ShowRequest, //show request
success:SubmitSuccesful, //success
error: AjaxError //error
});
});
Lakhan is right, you should try to use ajax instead of an iframe as they cause a lot of issues. If you absolutely need to use an iframe add a target attribute to your form (target the iframe not the main page) and only the iframe will reload.
<form action="action" method="post" target="target_frame">
<!-- input elements here -->
</form>
<iframe name="target_frame" src="" id="target_frame" width="XX" height="YY">
</iframe>
Here's a fully worked example that makes use of a <form>, the FormData object and AJAX to do the submission. It will update the page every 5 seconds. Do note that in PHP, the use of single quotes ( ' ) and double quotes ( " ) is not always interchangeable. If you use single quotes, the contents are printed literally. If you use double-quotes, the content is interpretted if the string contains a variable name. Since I wanted to print the variable name along with the preceding dollar sign ($) I've used single quotes in the php file.
First, the PHP
location.php
<?php
$location = $_POST['location'];
$posSend = $_POST['posSend'];
echo '$location: ' . $location . '<br>';
echo '$posSend: ' . $posSend;
?>
Next, the HTML
index.html
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(id,parent){return (parent == undefined ? document : parent).getElementById(id);}
function myAjaxPostForm(url, formElem, successCallback, errorCallback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
successCallback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
errorCallback(this);
}
ajax.open("POST", url, true);
var formData = new FormData(formElem);
ajax.send( formData );
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
var submitIntervalHandle = setInterval( doAjaxFormSubmit, 5000 ); // call the function to submit the form every 5 seconds
}
function doAjaxFormSubmit()
{
myAjaxPostForm('location.php', byId('myForm'), onSubmitSuccess, onSubmitError);
function onSubmitSuccess(ajax)
{
byId('ajaxResultTarget').innerHTML = ajax.responseText;
}
function onSubmitError(ajax)
{
byId('ajaxResultTarget').innerHTML = "Sorry, there was an error submitting your request";
}
}
</script>
<style>
</style>
</head>
<body>
<form id='myForm'>
<input name='location'/><br>
<input name='posSend'/><br>
</form>
<hr>
<div id='ajaxResultTarget'>
</div>
</body>
</html>
I'm creating an online exam application in PHP and am having trouble with the AJAX calls.
I want the questions to be fetched (and used to populate a div) using an AJAX call when one of the buttons on the right are clicked. These buttons are not static; they are generated on the server (using PHP).
I'm looking for an AJAX call to be something like this:
functionname=myfunction(some_id){
ajax code
success:
html to question output div
}
and the button should call a function like this:
<button class="abc" onclick="myfunction(<?php echo $question->q_id ?>)">
Please suggest an AJAX call that would make this work
HTML
<button class="abc" questionId="<?php echo $question->q_id ?>">
Script
$('.abc').click(function () {
var qID = $(this).attr('questionId');
$.ajax({
type: "POST",
url: "questions.php", //Your required php page
data: "id=" + qID, //pass your required data here
success: function (response) { //You obtain the response that you echo from your controller
$('#Listbox').html(response); //The response is being printed inside the Listbox div that should have in your html page. Here you will have the content of $questions variable available
},
error: function () {
alert("Failed to get the members");
}
});
})
The type variable tells the browser the type of call you want to make to your PHP document. You can choose GET or POST here just as if you were working with a form.
data is the information that will get passed onto your form.
success is what jQuery will do if the call to the PHP file is successful.
More on ajax here
PHP
$id = gethostbyname($_POST['id']);
//$questions= query to get the data from the database based on id
return $questions;
You are doing it the wrong way. jQuery has in-built operators for stuff like this.
Firstly, when you generate the buttons, I'd suggest you create them like this:
<button id="abc" data-question-id="<?php echo $question->q_id; ?>">
Now create a listener/bind on the button:
jQuery(document).on('click', 'button#abc', function(e){
e.preventDefault();
var q_id = jQuery(this).data('question-id'); // the id
// run the ajax here.
});
I would suggest you have something like this to generate the buttons:
<button class="question" data-qid="<?php echo $question->q_id ?>">
And your event listener would be something like the following:
$( "button.question" ).click(function(e) {
var button = $(e.target);
var questionID = button.data('qid');
var url = "http://somewhere.com";
$.ajax({ method: "GET", url: url, success: function(data) {
$("div#question-container").html(data);
});
});