PHP script not running from Jquery/AJAX? - php

I am trying to pass the user's checked HTML radio button value to a PHP variable using Jquery/Javascript and Ajax.
The following is a simplified version of the HTML/Javascript:
$("input[name=bus_plan]").on('change', function(){
var $postID = "=" + $('input:radio[name=bus_plan]:checked').val();
$.ajax ({
type: "GET",
url: "product-group.php",
data: {"postID" : $postID },
success : function(data){
alert("done");
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("problem: " + errorThrown);
}
});
});
The ajax call shows a success (i.e. there is a "done" alert.)
This is the product-group.php:
<?php
echo "hello world<br>";
$postid = $_GET['postID'];
echo "The postID is ".$postid;
?>
Any help in understanding/fixing the fact that product-group.php does not appear to run would be most appreciated.
Thank you.

Try alert(data) instead of alert("done") to see if jQuery is receiving the correct response.

Your echo output is in "data" var, its like the "return" for ajaxcalls.
Tru alert(data) or append the data content on some div.

Try rewriting your ajax call like this-
$("input[name=bus_plan]").on('change', function(){
var postID = $('input:radio[name=bus_plan]:checked').val();
$.ajax ({
type: "GET",
url: "product-group.php?postID="+postID,
success : function(data){
alert("done");
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("problem: " + errorThrown);
}
});
});

Related

Not getting response in ajax

I am trying to get ajax response. But my code does not show anything in alert. Here is my ajax code. my form id is contact_form and my submit button id is submit_btn
$(document).ready(function(){
$('#contact_form').on('submit', function(e){
var form= $("#contact_form").val();
$.ajax({
type : 'POST',
url : 'email.php',
data : form.serialize(),
dataType : 'json',
success: function (response) {
alert(response);
},
error: function(jqXHR, textStatus, errorThrown) {
//console.log(textStatus, errorThrown);
}
});
e.preventDefault();
});
});
my email.php
<?php
echo "ok";
?>
I think that your problem is because you are trying to use the serialize method in a wrong way.
The .serialize() method will handle all the fields that are inside the selected target form. In the original code, You've used the .val() method to take the values of the form, but this will not work because that method is intended to be used with a single form element and can't handle the whole form.
Change your code in this way:
$(document).ready(function(){
$('#contact_form').on('submit', function(e){
e.preventDefault();
var form = $("#contact_form");
$.ajax({
type : 'POST',
url : 'email.php',
data : form.serialize(),
success: function (response) {
alert(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
});

How do I get the value of a JSON result into a label?

This is the result: [{"apn":"173-76-001"}]
From this code (php):
<?php
require_once('../config.php');
if(isset($_GET['parcel_id'])) {
$db = new ezSQL_mysql(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
$data = $db->get_results("select apn from parcels where parcel_id=" . $_GET['parcel_id']);
if($data != null) echo json_encode($data);
//if ($data != null) echo $data;
}
?>
jquery:
$('#searchTable tr').click(function(){
var parcel_id = $(this).attr('id');
alert(parcel_id);
$.ajax({
url: "classes/get-apn.php?id=" + parcel_id,
//timeout: 30000,
type: "GET",
error: function(SMLHttpRequest, textStatus, errorThrown){
alert("An error has occurred making the request: " + errorThrown);
},
success: function(data){
//do stuff here on success
alert(data);
$('#ParcelNumber').val(data);
}
});
});
How do I get the value of apn (173-76-001) into a label??
Im new at all this so thanks for your help in advance!!! :)
EDIT: So I tried the response below but it didn't work. I was told I need to parse using jQuery.parsJSON but it's not working either. I'm so confused. Here's my updated jQuery code:
$('#searchTable tr').click(function(){
var parcel_id = $(this).attr('id');
$('#ParcelId').html(parcel_id);
$.ajax({
url: "classes/get-apn.php?id=" + parcel_id,
//timeout: 30000,
type: "GET",
data: { parcel_id : parcel_id },
dataType: 'json',
error: function(SMLHttpRequest, textStatus, errorThrown){
alert("An error has occurred making the request: " + errorThrown);
},
success: function(data){
//do stuff here on success
var result = $.parseJSON(data);
alert(result.apn);
}
});
});
You perform the ajax request to the server. Server queries the DB and formats output as json. Ajax request hereby succeeded and the following line of code sets the label’s value:
$('#ParcelNumber').val(data);
Label ID here is ParcelNumber. To get the value you probably need to:
$('#ParcelNumber').val(data[0]["apn"]);
Whether ParcelNumber is not “valued” control (e.g. not an input but static div), use .html method:
$('#ParcelNumber').html(data[0]["apn"]);

Ajax: I can't get data from PHP by using json_encode

I am having issues retrieving data from PHP by using Ajax. I am stuck and have been spending lots of time trying to find out where the problem is.
Here is my php code:
<?php //ajax/default_chart_numbers.php
require_once '../core/db_connection.php';
$lotto = new Lotto();
$ultimo_concurso=$lotto->ultimo_concurso('foo');
$ultimos_numeros_m=$lotto->ultimos_numeros('bar');
$R1m=$ultimos_numeros_m[1];
$R2m=$ultimos_numeros_m[2];
$R3m=$ultimos_numeros_m[3];
$R4m=$ultimos_numeros_m[4];
$R5m=$ultimos_numeros_m[5];
$R6m=$ultimos_numeros_m[6];
$R7m=$ultimos_numeros_m[7];
//preparing json
$json=array('y'=>$ultimo_concurso,'n1'=>$R1m,'n2'=>$R2m,'n3'=>$R3m,'n4'=>$R4m,'n5'=>$R5m,'n6'=>$R6m);
print json_encode($json,true);
?>
The output of the PHP file is:
{"y":"2745","n1":"1","n2":"13","n3":"19","n4":"29","n5":"41","n6":"46"}
And here is the jQuery code:
<script>
$(document).ready(function(){
/*Retriving data from PHP file*/
$.ajax({
url: "ajax/default_chart_numbers.php",
cache: false,
dataType: "json",
timeout:3000,
success : function (response, textS, xhr) {
alert("everything ok :)");
},
error : function (xmlHttpRequest, textStatus, errorThrown) {
alert("Error " + errorThrown);
if(textStatus==='timeout')
alert("request timed out");
},
complete: function(data){
y=data.y;
alert('The id number is '+ y);
}
});
});
</script>
When executing, the value is undefined. I mean, the alert i get is The id number is undefined.
What am i missing?
There's no true in json_encode, there is in json_decode to get an array, but now you're creating a string
change
print json_encode($json,true);
to
echo json_encode($json);
and the complete handler doesn't get the data, it has two arguments, the XHR object and the statuscode, the success handler gets the data
$.ajax({
url: "ajax/default_chart_numbers.php",
cache: false,
dataType: "json",
timeout:3000,
success : function (data) {
y=data.y;
alert('The id number is '+ y);
},
error : function (xmlHttpRequest, textStatus, errorThrown) {
alert("Error " + errorThrown);
if(textStatus==='timeout')
alert("request timed out");
}
});
On PHP side, send the JSON with:
header('Content-Type: application/json');
echo json_encode($json);
Maybe log the incoming data to the console:
inside success: add an console.log(response)
inside complete: add an console.log(data.y)
This is missing:
https://api.jquery.com/jQuery.parseJSON/
try using:
result = $.parseJSON (data);
result.y has your value

How to get each value from json method

ajax
$('#stb_no').blur(function(){
var stb_no= $('#stb_no').val();
$.ajax({
url: "http://localhost/paymybill/ajax/stb_info",
global: false,
type: "POST",
data: {
'stb_no':stb_no, // you should give a key to the variable
},
success: function(data) {
$('#amount').val(data);
// $(".email_msg").addClass("red");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
Controller code
public function stb_info(){
$stb_no=$this->mso->alldata_stbno($this->input->post('stb_no'));
echo json_encode($stb_no);
}
i am getting out put
[{"sxb_no":"xxxxxx","mzo_name":"xx","cto_name":"xxxxx","area":"xxxxx","name_sxb_owr":"","mobile_no":"xxxxxx","email":"xxxxx#yahoo.com","amount":"xxx"}]
i need to know how to get each values ex:- if i want get email id what i should i do in jquery please help me i new to ajax
Most browsers support JSON.parse(), which is defined in ECMA-262 and is the recommended way. Its usage is simple (I will use your example JSON):
var json = '{"area":"xxxxx",...,"email":"xxxxx#yahoo.com","amount":"xxx"}';
var obj = JSON.parse(json);
Note that obj.email can't be used, because you are parsing an array.
Edit: Checking your comments you need to know that the data parameter is the JSON object, parse it first and then you can do:
$('#amount').val(obj[0].email);
Just add to $.ajax call parameter dataType:"json" and Jquery will parse it in success parameter automatically. Then use it data[0]['email'];
For example :
$('#stb_no').blur(function(){
var stb_no= $('#stb_no').val();
$.ajax({
url: "http://localhost/paymybill/ajax/stb_info",
global: false,
type: "POST",
data: {
'stb_no':stb_no, // you should give a key to the variable
},
success: function(data) {
$('#email').val(data[0]['email']);
//OR
var obj = JSON.parse(data);
$('#email').val(obj[0].email);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});

Making value from PHP show on page requesting AJAX data

I have a simple login form and it does return the "success" text in the function, but now I want to be able to add the text provided in the .php file. How can I do this?
html
<script>
$(function(){
$("#submitlogin").click(function() {
inputs = {
"logInUsername" : $('input[name=logInUsername]').val(),
"logInPassword" : $('input[name=logInPassword]').val()
};
// since this is a username and password combo you will probably want to use $.post
$.ajax ({
type: "POST",
url: "loggnow.php",
data: inputs,
success: function() {
$("#login").html("You are now logged in!");
},
error : function(jqXHR, textStatus, errorThrown){
alert("error " + textStatus + ": " + errorThrown);
}
});
});
});
$.ajax({
type: "POST",
url: "loggnow.php",
data: inputs,
dataType: "html",
success: function (data) {
$("#login").html(data);
},
error : function (jqXHR, textStatus, errorThrown) {
alert("error " + textStatus + ": " + errorThrown);
}
});
The docs on jquery web sites says that the sucess function will be passed the data. (See quoted). So you can just use the content passed back in the "data" variable, and put it in there.
success(data, textStatus, jqXHR)
A function to be called if the request succeeds. The function gets passed
three arguments: The data returned from the server, formatted according to
the dataType parameter; a string describing the status; and the jqXHR
(in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success
setting can accept an array of functions. Each function will be called in
turn.

Categories