JQuery Ajax Post input Class - javascript

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;
}
?>

Related

Send php response to ajax and display result in div

I have made a simple form through which i can search the keywords and find the related output from database dynamically. The code works perfect without AJAX . But now i have applied some AJAX code to get the response on same page within a div named coupon. I am unable to get the response. I don't know where am i doing wrong. Any suggestions please. Here is the complete code.
form
<form action="" id="search_form" method="POST">
<p><input name="query" autocomplete="off" id="list_search" type="search" required class="list_search" /></p>
<p align="center"><input type="submit" id="click" name="click" class="but" value=" search" /></p>
</form>
<div class="coupons"></div>
AJAX
$("document").ready(function(){
// $(".but").click(function(event){ // here
$("#search_form").submit(function (event) {
{
event.preventDefault();
var myData={ query: $( 'input[name="query"]' ).val() };
$.ajax({
url: 'result.php',
data: myData,
type: 'post',
dataType: "html",
success: function(result){
//console.log(result);
$('.coupons').html(result);
},
error: function() {
alert('Not OKay');
}
});
});
});
result.php
$keyword = mysqli_real_escape_string($con,$_REQUEST['query']); // always escape
$keys = explode(" ", $keyword);
$sql="SELECT c.* , sc.* , sm.* ,ca.* from store_category sc INNER JOIN store_manufacture sm ON sm.sm_id=sc.store_id INNER JOIN categories ca ON ca.cat_id=sc.cat_id INNER JOIN coupons c on c.c_sc_id=sc.sc_id WHERE c.c_name LIKE '%$keyword%' OR sm.sm_brand_name LIKE '%$keyword%' OR ca.cat_name LIKE '%$keyword%' OR c.c_description LIKE '%$keyword%'";
foreach ($keys as $k) {
$sql.="OR c.c_name LIKE '%$k%' OR sm.sm_brand_name LIKE '%$k%' OR ca.cat_name LIKE '%$k%' OR c.c_description LIKE '%$k%'";
}
$result = mysqli_query($con, $sql);
$count=mysqli_num_rows($result);
if($count!=0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$res=$row['c_name'].$row['c_description'];
echo json_encode($res);
}
}
else
{
echo "no result";
}
Do not use a click event and a button does not have a submit event - use the form's submit event instead
$("#search_form").on("submit",function(e) {
e.preventDefault();
$.post("result.php?query="+encodeURIComponent($("#list_search").val()),function(data) {
$('.coupons').html(data); // you likely need to render the JSON instead here or send HTML from server
});
});
You should try with:
var myData={ query: $( 'input[name="query"]' ).val() };
So you can get back a query field on the server.
The Problem is your ajax request does have your value as key in $_REQUEST. There might be some way to handle this but it is not very intuitive.
And right you should register the submit handler on your form not your button.
$("#search_form").submit(function(event){ ... }

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>

Unable to pass javascript variable to PHP through ajax?

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);
}
});

Receive multiple value from php file via ajax call

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.

Getting undefined index when using ajax.

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'] : '';

Categories

Resources