Unable to pass javascript variable to PHP through ajax? - javascript

I have searched through a couple of QA here at stackoverflow, none of solutions seemed to help. I am trying to pass input to my PHP file but for some reason the inputdoesn't get passed from javascript to and it keeps on returning undefined on the console.
my javascript:
$.ajax({
type:"GET",
url:"go.php",
data:{input:input},
success:function(data){
console.log(data); //data outputs https://mp3skull.wtf/search_db.php?q=&fckh=1d41a1579f21a921d1008d90dc6246a7
}
});
my php:
<?php
$input = $_GET['input']; //$input here is empty
$keywords= explode(" ",$input);
$link = "https://mp3skull.wtf/search_db.php?q=" . $keywords[0];
for($i = 1; $i < count($keywords); $i++){
$link .= "+" . $keywords[$i];
}
$link .= "&fckh=1d41a1579f21a921d1008d90dc6246a7";
echo $link; //$keywords is not appended to $link
?>

the code works you probably console.log from outside the ajax call.

hi first you need to declare it as a variable. Second does your variable really have a value? I'll give u sample you can run your code do it something like this
var input = $("#input").val();
$.ajax({
type:"GET",
url:"go.php",
data:{input:input},
success:function(data){
console.log(data); //data outputs https://mp3skull.wtf/search_db.php?q=&fckh=1d41a1579f21a921d1008d90dc6246a7
}
});
hope this helps

If you have the following Html:
<input type="text" class="field" />
<input type="button" class="button">
You should use the following script:
$(document).ready(function() {
$('.button').click(function(){
$.ajax({
type:"GET",
url:"go.php",
data:{'input':$('input.field').val()},
success:function(data){
console.log(data);
}
});
});
});

I think it's because when you send data in "data: { input: input } " are defining the variable input with the same name. It should be like that
var inputValue = $("#idInput").val();
$.ajax({
type:"GET",
url:"go.php",
data:{input:inputValue},
success:function(data){
console.log(data);
}
});

Related

how to make submit button both send form thru' PHP -> MySQL and execute javascript?

I'm having an issue. When I hit submit, my form values are sent to the database. However, I would like the form to both send the value to the database and execute my script, as said in the title.
When I hit submit button, the form is sent to the database and the script remains ignored. However, if I input empty values into the input areas, the javascript is executed, and does what I want (which is to show a hidden < div >), but it's useless since the < div > is empty, as there is no output from the server.
What I want is:
submit button -> submit form -> javascript is executed > div shows up > inside div database SELECT FROM values (which are the ones added through the submitting of the form) appear.
Is this possible? I mean, to mix both PHP and JavaScript like this?
Thanks in advance.
By two ways, You can fix it easily.
By ajax--Submit your form and get response
$('form').submit(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: url, //action
data: form.serialize(), //your data that is summited
success: function (html) {
// show the div by script show response form html
}
});
});
First submit your from at action. at this page you can execute your script code .. At action file,
<?php
if(isset($_POST['name']))
{
// save data form and get response as you want.
?>
<script type='text/javascript'>
//div show script code here
</script>
<?php
}
?>
hers is the sample as I Comment above.
In javascript function you can do like this
$.post( '<?php echo get_site_url(); ?>/ajax-script/', {pickup:pickup,dropoff:dropoff,km:km}, function (data) {
$('#fare').html(data.fare);
//alert(data.fare);
fares = data.fare;
cityy = data.city;
actual_distances = data.actual_distance;
}, "json");
in this ajax call I am sending some parameters to the ajaxscript page, and on ajaxscript page, I called a web service and gets the response like this
$jsonData = file_get_contents("https://some_URL&pickup_area=$pickup_area&drop_area=$drop_area&distance=$km");
echo $jsonData;
this echo $jsonData send back the data to previous page.
and on previous page, You can see I Use data. to get the resposne.
Hope this helps !!
You need ajax! Something like this.
HTML
<form method='POST' action='foobar.php' id='myform'>
<input type='text' name='fname'>
<input type='text' name='lname'>
<input type='submit' name='btnSubmit'>
</form>
<div id='append'>
</div>
jQuery
var $myform = $('#myform'),
$thisDiv = $('#append');
$myform.on('submit', function(e){
e.preventDefault(); // prevent form from submitting
var $DATA = new FormData(this);
$.ajax({
type: 'POST',
url: this.attr('action'),
data: $DATA,
cache: false,
success: function(data){
$thisDiv.empty();
$thisDiv.append(data);
}
});
});
And in your foobar.php
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$query = "SELECT * FROM people WHERE fname='$fname' AND lname = '$lname' ";
$exec = $con->query($query);
...
while($row = mysqli_fetch_array($query){
echo $row['fname'] . " " . $row['lname'];
}
?>
That's it! Hope it helps
You can use jQuery ajax to accomplish it.
$('form').submit(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: url, //url where the form is to be submitted
data: data, //your data that is summited
success: function () {
// show the div
}
});
});
Yes, you can mix both PHP and JavaScript. I am giving you a rough solution here.
<?php
if(try to catch submit button's post value here, to see form is submitted)
{
?>
<script>
//do javascript tasks here
</script>
<?php
//do php tasks here
}
?>
Yes, This is probably the biggest use of ajax. I would use jquery $.post
$("#myForm").submit(function(e){
e.preventDefault();
var val_1 = $("#val_1").val();
var val_2 = $("#val_2").val();
var val_3 = $("#val_3").val();
var val_4 = $("#val_4").val();
$.post("mydbInsertCode.php", {val_1:val_1, val_2:val_2, val_3: val_3, val_4:val_4}, function(response){
// Form values are now available in php $_POST array in mydbInsertCode.php - put echo 'success'; after your php sql insert function in mydbInsertCode.php';
if(response=='success'){
myCheckdbFunction(val_1,val_2,val_3,val_4);
}
});
});
function myCheckdbFunction(val_1,val_2,val_3,val_4){
$.post("mydbCheckUpdated.php", {val_1:val_1, val_2:val_2, val_3: val_3, val_4:val_4}, function(response){
// put echo $val; from db SELECT in mydbSelectCode.php at end of file ';
if(response==true){
$('#myDiv').append(response);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>

ajax function on change dropdown Value

Hie Everyone!
In PHP page1 my code is here..
<html>
.
...
<select id="customer">...</select>
..
....
<div id="show"></div>
//and Java script function (ajax call)
<script>
$('#customer').change(function(){
var Id = $(this).val();
$.ajax({
type: "GET",
url: "page2.php",
data: "ID="+id,
success: function( data ) {
document.getElementById("show").innerHTML = data;
}
});
});
</script>
</html>
In php page2 as code..
<?php
$ID=$_GET['ID'];
...
//db connection code
..
$sql="select * from Table1 where id='$ID'";
//result code..
//while loop..
//echo something..
// all working without error..
?>
So, when I was trying to do this.It does not showing the success data or may be Ajax function not work.I had check with alert(data);
but does not Alert anything.
please help.
You will give echo infront of the $get_id variable. But you will make sure only one echo in the page2.php page.
<?php
echo $get_id=$_GET['pass_id'];
...
//db connection code
..
$sql="select * from Table1 where id='$get_id'";
//result code..
//while loop..
//echo something..
// all working without error..
?>
Then in page1.php check your ajax response. using alert function.
<script>
$('#customer').change(function(){
var id = $(this).val();
$.ajax({
type: "GET",
url: "page2.php",
data: "pass_id="+id,
success: function( data ) {
alert(data);
document.getElementById("show").innerHTML = data;
}
});
});
</script>

Ajax post to PHP not working

Hi i got a problem im doing a ajax post to a php file but in the php file its empty
JS
google.maps.event.addListener(marker, 'click', function(marker, i) {
return function() {
var rid = locations[i][4]; //get id to varible
console.log(rid);
$.ajax({
url: uri+'/helper.php',
type: 'post',
data: {'referens': rid},
success: function(data){
console.log(rid);
window.location = uri+'/helper.php';
},error: function(data){
alert('error');
}
});
}
}(marker, i));
and my helper.php
<?php
$referens = $_POST['referens'];
echo $referens;
echo 1;
?>
the output in helper.php is only 1 and not my referens post
what if i want to use it like this in same file with location.reload();
success: function(data){
console.log(data);
location.reload();
},error: function(data){
alert('error');
}
});
}
}(marker, i));
</script>
<?php include_once('helper.php');
var_dump($referens); ?>
and helper.php
<?php
$referens = $_REQUEST['referens'];
echo $referens;
echo 1;
?>
As per your comments on other answers and on your post, I would like to mention this:
console.log(rid);
window.location = uri+'/helper.php';
In your success callback rid is 91 as it should be as per your comments and that is absolutely correct because at the php file you are trying to access a POST var.
But when this line executes window.location = uri+'/helper.php'; then location changes and it makes a GET request, so it fails.
To get this var at PHP end you should try with $_REQUEST('referens') and you have to send it with url like this:
window.location = uri+'/helper.php?referens=' + rid;
and at your php end:
<?php
$referens = $_REQUEST['referens']; // <---change here.
echo $referens;
echo 1;
?>
From the docs [$_REQUEST()]:
An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE.
Your code looks fine.
You are printing the wrong variable.
Change
success: function(data){
console.log(rid);
window.location = uri+'/helper.php';
}
To
success: function(data){
console.log(data); // Here you are getting return in data not as rid
window.location = uri+'/helper.php?rid='+rid; // See, pass rid here.
}
in helper.php
<?php
$referens = $_REQUEST['referens'];
echo $referens;
echo 1;
?>

javascript array in php using Ajax on submit not working

I have an array that i pass from javascript to php and in php page i am trying to put it in session to be used in the third page. The code is as below
JavaScript:
var table_row = [];
table_row[0] = [123,123,123];
table_row[1] = [124,124,124];
table_row[2] = [125,125,125];
var jsonString = JSON.stringify(table_row);
$.ajax({
type: "POST",
url: "test1.php",
dataType: "json",
data: {myJSArray: jsonString},
success: function(data) {
alert("It is Successfull");
}
});
test1.php
<?php
session_start();
$check1 = $_POST['myJSArray'];
$_SESSION['array']= $check1;
echo $check1;
?>
test2.php
<?php
session_start();
$test = $_SESSION['array'];
echo $test;
?>
on submit i call the function in javascript and the form takes me to test2.php. It is giving error on test2.php page Notice: Undefined index: array in C:\xampp\htdocs\test\test2.php on line 13
Any suggestions please do let me know.
You don't need to stringify yourself, jquery does it for you, if you stringify it, jQuery will believe you want a string instead
var table_row = [];
table_row[0] = [123,123,123];
table_row[1] = [124,124,124];
table_row[2] = [125,125,125];
$.ajax({
type: "POST",
url: "test1.php",
dataType: "json",
data: {myJSArray: table_row},
success: function(data) {
alert("It is Successfull");
}
});
However, on the php side, you still need to decode it as it is always a string when you get it from $_POST. use json_decode to do it.
$check1 = json_decode($_POST['myJSArray']);
look at your test2.php
<?php
session_start();
$test = $_SESSION['array'];
echo $test;
?>
if it's only the code in the file then the error you got C:\xampp\htdocs\test\test2.php on line 13 is mindless, because there is not line 13,
but if you have something about the code you show us, may there be something echoed before?
because session has to be started before any output,
otherwise I've tested whole script and works fine...
To check if session really started (otherwise $_SESSION will not work), try this:
if(session_id())
{
echo "Good, started";
}
else
{
echo "Magic! strangeness";
}
if problem not found in test2.php you can check test1.php echo $_SESSION['array'] after saving it, and in your javascript callback function alert data param itself,
I'm sure you can catch the problem by this way.
i got it to work, the code is below
Javascript file: in page index.php
Either you can call this function and pass parameter or use code directly
var table_row = []; //globally declared array
var table_row[0]=["123","123","123"];
var table_row[1]=["124","124","124"];
var table_row[2]=["125","125","125"];
function ajaxCode(){
var jsonArray = JSON.stringify(table_row)
$.ajax
({
url: "test1.php",
type: "POST",
dataType: 'json',
data: {source1 : jsonArray},
cache: false,
success: function (data)
{
alert("it is successfull")
}
});
}
Page: test1.php
session_start();
unset($_SESSION['array']);
$check1 = $_POST['source1'];
$_SESSION['array']= $check1;
echo json_encode(check1);
Page: test2.php //final page where i wanted value from session
if(session_id())
{
echo "Session started<br>";
$test = $_SESSION['array'];
echo "The session is".$test;
}
else
{
echo "Did not get session";
}
?>
In index page i have a form that is submitted and on submission it calls the ajax function.
Thank you for the help, really appreciate it.

Javascript send array to PHP using ajax

I am trying to send an array from javascript to PHP script using ajax. This is the code I have so far.
<?php
$i = 1;
while (++$i <= $_SESSION['totalcolumns']) {
$range = $_SESSION["min-column-$i"] . ',' . $_SESSION["max-column-$i"];?>
<br><?php echo "Keyword" ?>
<?php echo $i -1 ?>
<br><input type="text" data-slider="true" data-slider-range="<?php echo $range ?>" data-slider-step="1">
<?php } ?>
<button type="button" >Update</button>
<script>
$("[data-slider]")
.each(function () {
var range;
var input = $(this);
$("<span>").addClass("output")
.insertAfter(input);
range = input.data("slider-range").split(",");
$("<span>").addClass("range")
.html(range[0])
.insertBefore(input);
$("<span>").addClass("range")
.html(range[1])
.insertAfter(input);
})
.bind("slider:ready slider:changed", function (event, data) {
$(this).nextAll(".output:first")
.html(data.value.toFixed(2));
});
$(".output")
.each(function() {
var parms = [];
parms.push($(this).text());
});
</script>
<script>
function loadXMLDoc()
{
$.ajax({
type: "POST",
url: "update.php",
data: { value : $(parms).serializeArray() },
success: function(data)
{
console.log (data);
}
});
}
$("button").on('click',function(){ loadXMLDoc(); });
</script>
In my $.output function, I am using the parms [] array to store all the UI slider values which I am trying to pass on to the next PHP script page on a button click event as defined in loadXMLDoc() function. In my PHP page, I am accessing them as below.
<?php
$uid = $_POST['value'];
echo "Am I getting printed";
echo $uid;
// Do whatever you want with the $uid
?>
However, I am not able to view the data in my update.php script. Can someone please let me know what am doing wrong?
This is the link to my work so far.
serializeArray returns the json object ,maybe you could try json_decode in your php script,simply like:
$uid_arr = json_decode($uid,true);
print_r($uid_arr);
Just Use
data: $(parms).serializeArray()

Categories

Resources