I am trying to echo data from php to jquery and the problem is that somehow jquery is not passing the data to php. The var_dump of the variable $url echo's string'' or NULL.
Expected output is to echo what the user had typed on the input field on screen where the id="domain-hits" is.
HTML
<div id="domain-hits"></div>
<input onblur="checkPR()" type="text" class="input_text_metas_submit" name="url" value="http://" id="urlpr" />
Jquery / AJAX
$(function () {
jq2('#urlpr').on('blur', function (e) {
$.ajax({
type: 'post',
url: 'onlydomain.php',
data: $('#urlpr').serialize(),
success: function (data) {
$("#domain-hits").html(data);
}
});
e.preventDefault();
});
});
PHP - onlydomain.php
<?php
$url = isset($_GET['url']) ? $_GET['url'] : '';
var_dump($url); // it echo's string ''.
?>
I am a noob in ajax please help me on this, it's much appreciated. Thanks.
You're sending the form data via POST by trying to retrieve it via GET. Change:
$url = isset($_GET['url']) ? $_GET['url'] : '';
to:
$url = isset($_POST['url']) ? $_POST['url'] : '';
Related
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>
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);
}
});
I am trying to use ajax for retrieving data from my server. I use cakephp and jquery.
The ajax code is as follows:
<script>
$(document).ready(function(){
$(".viewMode").click(function(){
$.ajax({
type: "POST",
url:"viewModeSwitching",
data: {
mobileViewCookie:12,
},
success:function(result){
// window.location.href = result;
}
}
);
});
});
</script>
...
<?php
echo "<br>";
echo $this->Form->button(__('Desktop View'), array('type' => 'button','class' =>"viewMode",));
echo "<br>";
?>
This works well, in firebug I see that the POST is sent with value mobileViewCookie=12.
The point is that my cakephp controllerfunction 'viewModeSwitching' cannot retrieve that data.
I checked $this->data, $this->params, $_POST, etc but no sign of the data that had been send in the POST message.
Any suggestions?
/Antoine
Below is my ajax call code. I want to send one data in .php file via ajax call and want to get two values from .php file. This two values I want to set in different 'input' tags whose id are 'course_name' and 'course_credit'.
Here my ajax call return correct value(real value from DB table) of 'course_name' input tag.
But 'MY PROBLEM IS' the value of input tag whose id is 'course_credit' shows 'success'. How can I get the correct value(real value from DB table) of id 'course_credit' ?
I have a 'select' tag which id is 'c_select'
HTML:
<input type="text" name="course_name" id="course_name" value=""/>
<input type="text" name="course_credit" id="course_credit" value=""/>
AJAX :
$('#c_select').change(function(){
$.ajax({
type:'post',
url:'get_course_info_db.php',
data: 'c_id='+ $(this).val(),
success: function(reply_data1,reply_data2){
$('#course_name').val(reply_data1);
$('#course_credit').val(reply_data2);
}
});
});
get_course_info_db.php
<?php
include('db_connection.php');
$c_id = $_POST['c_id'];
$result = mysql_query("SELECT * FROM course WHERE c_id = '$c_id'");
$all_course_data = mysql_fetch_array($result);
$c_name = $all_course_data['c_name'];
$c_credit = $all_course_data['c_credit'];
echo $c_name,$c_credit;
exit();
?>
AJAX code:-
$('#c_select').change(function(){
$.ajax({
type:'post',
url:'get_course_info_db.php',
data: 'c_id='+ $(this).val(),
success: function(value){
var data = value.split(",");
$('#course_name').val(data[0]);
$('#course_credit').val(data[1]);
}
});
});
PHP code:-
<?php
include('db_connection.php');
$c_id = $_POST['c_id'];
$result = mysql_query("SELECT * FROM course WHERE c_id = '$c_id'");
$all_course_data = mysql_fetch_array($result);
$c_name = $all_course_data['c_name'];
$c_credit = $all_course_data['c_credit'];
echo $c_name.",".$c_credit;
exit();
?>
The success callback is Function( PlainObject data, String textStatus, jqXHR jqXHR ); http://api.jquery.com/jQuery.ajax/
php:
$data = array(
'name' => $c_name,
'credit' => $c_credit,
);
echo json_encode($data);
javascript:
success: function(data) {
var result = $.parseJSON(data);
$('#course_name').val(result.name);
$('#course_credit').val(result.credit);
}
success: function(reply_data1,reply_data2){
$('#course_name').val(reply_data1);
$('#course_credit').val(reply_data2);
}
second arguement is the status of http request, you have to encode the answer, i suggest you JSON
in your php
$c_credit = $all_course_data['c_credit'];
echo json_encode(array('name' => $c_name,'credit' => $c_credit));
exit();
and in your javascript
success: function(response,status){
var datas = JSON.parse(response);
$('#course_name').val(datas.name);
$('#course_credit').val(data.credit);
}
this is not tested, but this is the way to do it
I'd suggest using JSON to encode the data you fetch from the database.
Try changing your ajax call as follows:
$('#c_select').change(function(){
$.ajax({
type:'post',
url:'get_course_info_db.php',
data: 'c_id='+ $(this).val(),
dataType: 'json', // jQuery will expect JSON and decode it for you
success: function(reply_data){
$('#course_name').val(reply_data['c_name']);
$('#course_credit').val(reply_data['c_credit']);
}
});
});
And your PHP as follows:
include('db_connection.php');
// Escape your input to prevent SQL injection!
$c_id = mysql_real_escape_string($_POST['c_id']);
$result = mysql_query("SELECT * FROM course WHERE c_id = '$c_id'");
$all_course_data = mysql_fetch_array($result);
echo json_encode($all_course_data);
exit();
I haven't tested this but I imagine it'd work for you.
Im trying to send Ajax post to PHP.
This code works Ok:
$(document).on('keyup change',function(){
$.post("suma.php",{name: "oscar"},
function(data){
$('#Resultado').html(data);
}
);
});
PHP:
<?php
if( $_REQUEST["name"] )
{
$name = $_REQUEST['name'];
echo "Welcome ". $name;
}
?>
But the problem is, How can I send the value of two input class like this and calculate the sum in PHP?
<tr>
<td><input value="0" class="sum1"/></td>
<td><input value="0" class="sum2"/></td>
</tr>
Thank You in advance.
This is an example for you:
<div>
Send text
<input id="source1" name="source1" >
<input id="source2" name="source2" >
</div>
You need to include success handler in your ajax:
$("#text-id").on( 'click', function () {
$.ajax({
type: 'post',
url: 'text.php',
data: {
source1: "some text",
source2: "some text 2"
},
success: function( data ) {
console.log( data );
}
});
});
Firstly you will need to give distinguished names/IDs to the two input fields, then in JS you can find the value of those two like $("#input_id").val(), then post them in ajax data attribute like posted by Jeffery.
Secondly, you will be able to fetch all the posted data in PHP via $_POST variable, then you can do whatever you want with the data return a response.
You can send it here;
$.post("suma.php", {
src1 ; $('.sum1').val(),
src2 : $('.sum2').val()
}
And your php:
<?php
if( $_REQUEST["src1"] && $_REQUEST["src2"] ){
$sum = $_REQUEST["src1"] + $_REQUEST["src2"];
echo $sum;
}
?>