Passing a variable to PHP with jQuery and $.ajax - php

I have a jQuery php script which accesses a database and echoes back html to fill a div on my page. It uses the following code.
function myCall() {
var request = $.ajax({
url: "ajax.php",
type: "GET",
dataType: "html"
});
request.done(function (msg) {
$("#divholder").html(msg);
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
}
What I need to do is also send a variable through to the script so it knows what to look for in the database. I have been searching but I can't seem to find quite the right answer. Any help greatly appreciated.
Regards.

With a get request just append it to the url.
$.ajax({
url : 'ajax.php?someVar=20',
type : 'GET',
dataType : 'html'
)}
You can also add it to the data property and jQuery will url encode your data and append it to the url string.
$.ajax({
url : 'ajax.php',
type : 'GET',
dataType : 'html',
data : {
someVar : 20
}
)}

You can send the parameter like this :
function myCall() {
var request = $.ajax({
url: "ajax.php?param1=" + 'parameter',
type: "GET",
dataType: "html"
});
request.done(function(msg) {
$("#divholder").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
And get the parameter with $_GET
Or you can send the parameter with POST (look at data : Ajax jQuery)

Related

Data is not defined Jquery, PHP

I cant define data in ajax jquery function, where can be problem? I try everything, choose other server, other browser, remove cache, add data manually and always it is undefined...
Server: Laragon
App.js , add-new.php
(function($){
var form = $('#add-form');
form.on('submit',function(){
event.preventDefault();
$.ajax({
url: form.attr('action'),
type: 'POST',
data: form.serialize()
})
.done(function(data){
console.log("Data: " + data);
});
});
}(jQuery))
<?php
die("test");
//include
require('./config.php');
$id = $database->insert('items',[
'text' => $_POST['message']
]);
if($id){
die('success');
}
?>
Response screen:
response screen
I think you have missed success parameter in ajax function.
$.ajax({
url: form.attr('action'),
type: 'POST',
data: form.serialize(),
success: function(data) {
console.log("Data => ", data);
}
});
Hope it may work for you.

Data send in json is change while send it

$.ajax({
type : 'POST',
url : '<?=site_url("aplikasi_tambah_merchant/input_merchant/get_mdr_master");?>',
data : 'kode='+arr_value[0],
beforeSend:function(){
$('#ajax-loader').show();
},
error: function(){
$('#ajax-loader').hide();
alert('Error\nGagal request data');
},
success: function(data){
var res = JSON.parse(data);
datamdr = Number(res.mdr_debit);
$('#ajax-loader').hide();
}
});
$.ajax({
type : 'POST',
url : '<?=site_url("pameran/update_mdr_pameran");?>',
data : 'datamdr='+datamdr+'&app_id='+app_id+'&on_off=2',
beforeSend:function(){
$('#ajax-loader').show();
},
error: function(){
$('#ajax-loader').hide();
alert('Error\nGagal request data');
},
success: function(data){
alert("tes "+datamdr);
alert("balik "+data);
$('#ajax-loader').hide();
}
});
this is the ajax code to send my data.
the first ajax is to get the value of datamdr = Number(res.mdr_debit);then i send datamdr value again to the controller, but in controller here
public function update_mdr_pameran() {
$this->config->set_item('compress_output', FALSE);
$datamdr = trim($this->input->post('datamdr'));
$app_id = trim($this->input->post('app_id'));
$on_off = trim($this->input->post('on_off'));
$out = $this->aplikasi_model->update_mdr_app_id_onoff($datamdr, $app_id, $on_off);
echo json_encode($datamdr);
}
those datamdr value is undefined, while the other 2 variable is still readable as string? how is it possible? i've tried parse the first json to string and int but still no luck to send the data again
Ajax works asynchronously by default so what is happening, is that both your requests execute at the same time and at that moment, the value you set on completion of the first ajax call, is still undefined.
You should wrap your second ajax call in a function and call that from the success handler in your first ajax call.
Or you combine both requests in one as they seem to be going to the same server any way.
A third option would be to make the ajax calls synchronous but that would block the execution of your script so I would not recommend that.
What #jeroen suggesting is this:
$.ajax({
type : 'POST',
url : '<?=site_url("aplikasi_tambah_merchant/input_merchant/get_mdr_master");?>',
data : 'kode='+arr_value[0],
beforeSend:function(){
$('#ajax-loader').show();
},
error: function(){
$('#ajax-loader').hide();
alert('Error\nGagal request data');
},
success: function(data){
var res = JSON.parse(data);
datamdr = Number(res.mdr_debit);
$('#ajax-loader').hide();
update_mdr_pameran();
}
});
function update_mdr_pameran(){
$.ajax({
type : 'POST',
url : '<?=site_url("pameran/update_mdr_pameran");?>',
data : 'datamdr='+datamdr+'&app_id='+app_id+'&on_off=2',
beforeSend:function(){
$('#ajax-loader').show();
},
error: function(){
$('#ajax-loader').hide();
alert('Error\nGagal request data');
},
success: function(data){
alert("tes "+datamdr);
alert("balik "+data);
$('#ajax-loader').hide();
}
});
}

Ajax post not appending data to URL

I am trying to get my search bar working, however I am having issues with an ajax post.
For whatever reason, none of the data is being appended to the URL. I have tried various things with no success. I am attempting to send the data to the same page (index.php).
Here is my jquery:
$(function(){
$(document).on({
click: function () {
var tables = document.getElementsByTagName("TABLE");
for (var i = tables.length-1; i >= 0; i-= 1) {
if (tables[i]) tables[i].parentNode.removeChild(tables[i]);
}
var text = $('#searchBar').val();
var postData = JSON.stringify({ searchTerm: text });
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: postData,
success: function() {
alert("Test");
}
});
}
}, "#searchButton");
});
And here is the php which I have with index.php:
<?php
require('course.php');
if(isset($_POST['searchTerm'])) {
echo $_POST['searchTerm'];
}
?>
No matter what I try, I am unable to get anything to post. I have checked the network tab in chrome, and I'm not seeing anything that indicates it's working correctly.
Any ideas?
EDIT:
I've changed my code to this, and it seems I'm getting closer:
$(document).on({
click: function () {
$("TABLE").remove()
var text = $('#searchBar').val();
$.ajax({
type: 'GET',
url: 'index.php',
dataType: 'text',
data: { searchTerm: text },
success: function() {
alert("Test");
}
});
}
}, "#searchButton");
And:
<?php
require('course.php');
if(isset($_GET['searchTerm'])) {
echo $_GET['searchTerm'];
}
?>
Now I am getting ?searchTerm=theTextIEnter as expected, however it's still not being echoed in index.php.
Do not use JSON.stringify() to convert object to string. data passed to $.ajax must be an object and not JSON.
For whatever reason, none of the data is being appended to the URL.
You are making a POST request. POST data is sent in the request body, not in the query string component of the URL.
If you change it to a GET request (and inspect it in the correct place, i.e. the Network tab of your browser's developer tools and not the address bar for the browser) then you would see the data in the query string.
This will work for you use data: { postData } on place of data:postData and you will receive your data in $_POST['postData']
$(function(){
$(document).on({
click: function () {
var tables = document.getElementsByTagName("TABLE");
for (var i = tables.length-1; i >= 0; i-= 1) {
if (tables[i]) tables[i].parentNode.removeChild(tables[i]);
}
var text = $('#searchBar').val();
var postData = JSON.stringify({ 'searchTerm' : text });
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: { postData },
success: function(data) {
alert(data.searchTerm);
}
});
}
}, "#searchButton");
});
In index.php
<?php
if(isset($_POST['postData'])) {
echo $_POST['postData'];
die;
}
?>
If you want to send data via the URL you have to use a GET request. To do this, change the type of the request to GET and give the object directly to the data parameter in your jQuery, and use $_GET instead of $_POST in your PHP.
Finally note that you're not returning JSON - you're returning text. If you want to return JSON, use json_encode and get the value in the parameter of the success handler function.
Try this:
$(document).on({
click: function () {
$('table').remove();
$.ajax({
type: 'GET',
url: 'index.php',
dataType: 'json',
data: { searchTerm: $('#searchBar').val() },
success: function(response) {
console.log(response.searchTerm);
}
});
}
}, "#searchButton");
<?php
require('course.php');
if(isset($_GET['searchTerm'])) {
echo json_encode(array('searchTerm' => $_GET['searchTerm']));
}
?>
Remove dataType: 'json', from your AJAX. That is all.
Your response type is not JSON, yet by setting dataType: 'json' you're implying that it is. So when no JSON is detected in the response, nothing gets sent back to the method handler. By removing dataType it allows the API to make an educated decision on what the response type is going to be, based on the data you're returning in the response. Otherwise, you can set dataType to 'text' or 'html' and it will work.
From the manual:
dataType: The type of data that you're expecting back from the server.
This is NOT the type of data you're sending/posting, it's what you're expecting back. And in your index.php file you're not sending back any JSON. This is why the success() method is not satisfying. Always set the dataType to the type of data you're expecting back in the response.
With POST Request:
Please comment below line in your code:
//var postData = JSON.stringify({ searchTerm: text });
And use below ajax code to get the post-data:
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: { searchTerm: text },
success: function() {
alert("Test");
}
});
With GET Request:
You can convert your data to query string parameters and pass them along to the server that way.
$.ajax({
type: 'GET',
url: 'index.php?searchTerm='+text,
dataType: 'json',
success: function(response) {
alert(response);
}
});
In response, You can get the data with alert, so you may get idea about the same.

PHP to jQuery - catching the json

Here's what I want to do. User submits form (a single text input) and send to PHP. PHP returns this;
{"status":"true","custid":"00001","custname":"John"}
I know that it is in JSON format, but I don't know how to catch and use the value so I can us the returned values.
$(function(){
$('#icnumber-form').submit(function(){
var icno = $('#icnumber').val();
var purl = 'php/create_process.php'
$.ajax({
type : 'POST',
url : purl,
cache : false,
data : icno,
dataType: 'json',
success : function(response){
var json = $.parseJSON(response);
alert(json.message);
},
beforeSend:function(){
$('.cust-exist-view').show();
}
});
return false;
})
});
Since you set the dataType to json, the response comes back as an already parsed object, so you don't try to parse it yourself.
success : function(response){
alert(response.status);
},
You don't need to use var json = $.parseJSON(response); because jQuery automatically parse the JSON string to object . Just use it as a javascript object to access the json properties. I create a simple demo from your code. View it in jsfiddle
JS Code:
$(function () {
$('#icnumber-form').submit(function () {
//var icno = $('#icnumber').val();
var purl = '/echo/json/'
$.ajax({
type: 'POST',
url: purl,
cache: false,
data: {
json: '{"status":"true","custid":"00001","custname":"John"}',
delay: 1
},
dataType: 'json',
success: function (response) {
alert( "status:" + response.status
+ "\ncustname:"+response.custname
+ "\ncustid:"+ response.custid);
},
beforeSend: function () {
// $('.cust-exist-view').show();
}
});
return false;
})
});
SO you just need to view this part to see how to use json return :
success: function (response) {
alert( "status:" + response.status //access status
+ "\ncustname:"+response.custname //access custname
+ "\ncustid:"+ response.custid); // access custid
},

jQuery Ajax post to php not catching variable

What am i doing wrong. PHP doesn't seem to catch title and wrapper from $.ajax. Does the code look correct. The success message i get indicate an error that title is not found.
jQuery main.html
$.ajax({
type: "POST",
url: "process.php",
data: 'title=test&wrapper=testing',
success: function(msg){
alert( "Data Saved: " + msg );
}
});
PHP process.php
<?php
$title = $_REQUEST['title'];
$wrapper = $_REQUEST['wrapper'];
...
?>
Take a look: jQuery.ajax()
The data parameter is better to be a Key/Value pairs object, it's cleaner and easier to debug :)
$.ajax({
type: "POST",
url: "process.php",
data: {
title: 'test',
wrapper: 'testing'
},
success: function(msg){
alert( "Data Saved: " + msg );
}
});
Thats a good solution.but if I try to send data through a form in a webservice.
$.ajax({
type: "POST",
url: "process.php",
data: {
title: $('#title').val,
name: $('#name').val
},
success: function(data){
alert(data );
}
});
Here title and name are forms element in client side.but i am not able to get post value in json based webservice file say process.php

Categories