jQuery not generating correct queryString - php

I have been working on a website that uses a combination of PHP, jQuery, MySQL and XHTML in order to register students for a piano recital. This has no official purpose other than a learning exercise for me in getting all of these to work together. However, I have had a lot of problems getting the PHP to talk with the database and I'm not sure what my problem is. But before that can be tackled there is a really annoying issue that I've run across. For some reason my jQuery is not building a complete post URL for the PHP.
I am using jQuery version: 1.4.2 from Google. The query string is being built by using:
var ajaxOpts = {
type: "post",
url: "../php/addRecital.php",
data: "&performance=" + $("#performanceType :selected").text() +
"&groupName=" + $("#groupName").val() +
"&student1fName=" + $("#firstName").val() +
"&student1lname=" + $("#lastName").val() +
"&student1id=" + $("#studentID").val() +
"&student2fname=" + $("#Second_Student_firstName").val() +
"&student2lname=" + $("#Second_Student_lastName").val() +
"&student2id=" + $("#Second_Student_studentID").val() +
"&skillSelect=" + $("#skillSelect :selected").text() +
"&instrument1=" + $("#instument1 :selected").text() +
"&otherInstrument1=" + $("#otherInstrument1").val() +
"&instrument2=" + $("#Instument2 :selected").text() +
"&otherInstrument2=" + $("#otherInstrument2").val() +
"&location=" + $("#locationSelect :selected").text() +
"&roomNumber=" + $("#roomNumber").val() +
"&time=" + $("#timeSlotSelect :selected").text()
,
success: function(data) { ...
There is more than the above function, but I didn't think that it would pertain to here. I then call the code using:
$.ajax(ajaxOpts);
However, instead of creating the entire query string I get:
http://sterrcs123.mezoka.com/schoolProject/assign/assign13.html?groupName=&firstName=Samuel&lastName=Terrazas&studentID=23-343-3434&Second_Student_firstName=&Second_Student_lastName=&Second_Student_studentID=&otherInstrument=&Second_Student_Instrument=&roomNumber=2
Which as you can tell is missing a number of keys and their values. I would appreciate any help I can get because this is really driving me insane. Thanks.

It appears that your form is simply submitting itself without using your AJAX operation. Did you attach to the form's submit event and THEN run your ajax call? You will also want to return false from the submit event handler to prevent the default behavior you are seeing above.
Example:
$('#formid').submit(function(){
//your ajax code here.
return false;
});

If you're talking to an ASP.Net web service then you would need data to be a JSON string of your arguments. Otherwise, you can pass your data in by using an object literal (truncated for brevity):
var ajaxOpts = {
type: "post",
url: "../php/addRecital.php",
data: {
performance: $("#performanceType :selected").text(),
groupName: $("#groupName").val(),
student1fName: $("#firstName").val(),
student1lname: $("#lastName").val()
},
success: function(data)
}
As per the missing values, make sure you're capturing the button click / form submit.
$('form').submit(function (e) {
$.ajax(ajaxOpts);
return false;
});

Related

Laravel Eloquent in jQuery Script

EDIT
I just realized I didn't post the entire code.
I am using an Ajax live search to retrieves cards when a user types in a part of their last name. When the results appear, a user will click on the row and it will retrieve that cards information.
From there, I want to use the card information to generate additional html.
$.ajax({
type: "get",
url : '{{ route('compare.search') }}',
data: {'search':$(this).val()},
success: function(data) {
$("#suggestion-box-1").slideDown();
$("#suggestion-box-1 tbody").html(data);
$(data).each(function(index){
$("#suggestion-box-1 tbody").append('<tr><td><a href="#" class="player-name" data-card=' + data[index].id + '>' + data[index].first + ' ' + data[index].last + '</a></td><td><span class="card-type"></span>' + data[index].card_type.replace('-', ' ') + '</td><td align="center"><span class="card-overall">' + data[index].overall + '</span></td></tr>');
});
// This is the part that I can't figure out
$('#suggestion-box-1 .player-name').click(function() {
var cid = $(this).data('card');
var card = {!! App\Card::where("id", $cid)->get() !!};
console.log(card);
});
}
});
} else if (len == 0) $('#suggestion-box-1').slideUp();
});
Any sort of help would be greatly appreciated!
That's gonna be impossible without an API since blade won't talk back to the server for that function.
You'll need to create an API endpoint that takes that javascript cid variable and responds with the card information you need.
The flow is blade generates the page THEN the cid variable gets populated in the frontend so cid doesn't exist at the moment the ::where function is called.

Cannot pass bootstrap table cell data to php?

I'm developing a web based inventory system. In my project i have a user management page and it has a table to view all the users.
+----------------------------------------+
+ username + user type + + +
+----------+-----------+--------+--------+
+ sample + sample + edit + delete +
+----------+-----------+--------+--------+
+ sample + sample + edit + delete +
+----------+-----------+--------+--------+
+ sample + sample + edit + delete +
+----------+-----------+--------+--------+
It has two buttons to edit user type and to delete user from the database. i need to get username from this table to php script, to execute delete query. I tried this,
$(document).on('click','.remove' ,function(){
var $item = $(this).closest("tr").find('td:eq(0)').html();
console.log($item);
<?php $username = <script>$item</script>?>
});
but i can't pass this 'username' variable to php. How to do this? Thank you :-)
To achieve this you need to perform an ajax request like this:
$(document).on('click','.remove' ,function(){
var $item = $(this).closest("tr").find('td:eq(0)').html();
$.post("url/file.php", { // your php file
username: $item
}, function(data, status){
// you will get response from your php page (what you echo or print)
});
});
PHP side:
$username = $_POST['username'];
//Do whatever you want ...
echo "success";
You can do it by Ajax, this is suggested for your code:
$.ajax({
url: "data.php",//file wich has query select to db table
data: {id:theid},//describe your data here
dataType: 'json',// type of data that will you get (JSON/HTML).
type: 'POST',//sending type (POST/GET)
success: function(data) {
//do change the select option
}
});
Goodluck!

PHP & Ajax: Passing time_zone as a parameter in AJAX

I am trying to pass the time zone parameter in a Ajax request
Like
alert(meeting_time);
alert(meeting_timezone);
$.ajax({
type: "GET",
url: "http://webfaction/UI/user/joinmeeting.php",
data: "user_names="+ user_names + "&image=" +file+"&duration="+ duration +"&user_name="+ user_name + "&meeting_id=" + meeting_id + "&moderator_password=" + moderator_password +"&attendee_password=" + attendee_password +
"&meeting_time=" + meeting_time + "&meeting_timezone=" + meeting_timezone + "&meeting_sms_no=" + meeting_sms_no + "&meeting_logout_url=" + meeting_logout_url +"&meeting_maxp=" + meeting_maxp +"&meeting_name=" + meeting_name ,
success: function(json){
alert(json);
$('#show_ajax').hide();
if(!json.error) location.reload(true);
},
Now my problem is before ajax request
alert(meeting_timezone); is printing `GMT +8.00`
but on the joinmeeting.php page
$meeting_timezone = $_GET['meeting_timezone'];
print $meeting_timezone;
the above print statement is printing the value GMT 8.00
(+ sign is not printing here)
Please tell me how to fix this problem ?
That's a known situation while using POST and GET methods, your + signs will be converted to space. The right way to pass data through POST or GET is using encodeURIComponent in JavaScript.
For example in your case, do this before sending:
meeting_timezone = encodeURIComponent(meeting_timezone);
It will help if you encode your URL in JavaScript by
encodeURIComponent(uri)
Like this:
data: encodeURIComponent(("user_names="+ user_names + "&image=" +file+"&duration="+ duration +"&user_name="+ user_name + "&meeting_id=" + meeting_id + "&moderator_password=" + moderator_password +"&attendee_password=" + attendee_password +
"&meeting_time=" + meeting_time + "&meeting_timezone=" + meeting_timezone + "&meeting_sms_no=" + meeting_sms_no + "&meeting_logout_url=" + meeting_logout_url +"&meeting_maxp=" + meeting_maxp +"&meeting_name=" + meeting_name )
Also take a look at this question:
How to encode a URL in Javascript?
might be useful
Instead of specifying the data: parameter as a string, use an object:
data: { user_names: user_names,
image: file,
...
meeting_timezone: meeting_timezone,
...
}
jQuery will then take care of converting it to a query string properly.

Ajax not sending data at all

im working on a script that sends a few data stored using GET to a PHP script(process it then put it into database).
here's the ajax script , im using jQuery ajax
(i have included the latest jQuery script)
function send(){
$.ajax({
type: "GET",
url: "http://examplewebsite.com/vars/parse.php",
data: "id=" + id + "&purl=" + purl + "&send" + "true",
cache: false,
success: function(){
alert("Sent");
}
});
}
id and purl are JavaScript variables .
send() function is set in :
Send
PHP code:
<?php
//Connect to database
include ("config.php");
//Get the values
$id = $_GET['id'];
$purl = $_GET['purl'];
$send = $_GET['send'];
if ($send == 'true') {
$insertdata = "INSERT INTO data (id,purl,send) VALUES ('$id','$purl',+1)";
mysql_query($insertdata) or die(mysql_error());
} else {
//do nothing
}
?>
when i type http://examplewebsite.com/vars/parse.php?id=123&purl=example&send=true
it works, the php injects the data into the database as i wanted but when i use send() and wanted to use ajax to send the data, failed.
Is there any mistakes that im making?
You're missing the = after send,
function send(){
$.ajax({
type: "GET",
url: "http://examplewebsite.com/vars/parse.php",
data: "id=" + id + "&purl=" + purl + "&send=" + "true",
cache: false,
success: function(){
alert("Sent");
}
});
}
should fix it, also. post more information about your javascript. We just have to assume id and purl are filled out. Did you try debugging them (if this doesn't work).
Also, debug the URL that is requested, you can use firefox or chrome dev-tools for this. What url is being send to the PHP page and is it correct
missing "=" in the data string.
data: "id=" + id + "&purl=" + purl + "&send" + "true",
should be
data: "id=" + id + "&purl=" + purl + "&send=" + "true",
It depends where you are running your script, because ajax calls are not meant to work on other domains. If you need to run the js on http://example1.com and the call to go to http://example2.com you need another approach.
An idea is to use json
Try
data: { id: id, purl: purl, send: true }
See if that makes any difference
First, i suggest (if you use Chrome or Safari) to use the Web Inspector (Right Click anywhere - inspect element) and then press ESC to show to console, this will assist you in validating your JS code. That would show you you have a '=' missing.
Second, i would try something a bit more simple just to make sure you get to the file.
JS:
// Don't forget encoding the data before sending, this is just a simple example
$.get("parse.php?sent=true",
function(data){
alert("I think i got a nibble...");
alert(data);
}
);
On the php file :
$sent = (isset($_GET['sent']) && !empty($_GET['sent']))?$sent:false;
if($sent) echo 'whatever data you want back';
Just make sure that you actually get the alert, and if so , move on from there to build the PHP file as needed for your data.
Hope this assists,
Shai.

JQuery Ajax error

I am posting some form values through ajax to a PHP script. The PHP echoes 1 if it's successful and 2 if not.
The PHP seems to be working ok but I am being redirected to the url in the javascript and shown the number 1 on a blank page instead of it being echoed back to the ajax request.
This is my javascript, can anyone see where I am going wrong?
$(".save").click(function() {
var area = $("input#area").val();
var january = $("input#january").val();
var target = $("input#target").val();
var ach = $("input#achieved").val();
var comments = $("input#comments").val();
var token = "<?php echo $token; ?>";
var dataString = 'area='+ area + '&january=' + january + '&target=' + target + '&achieved=' + ach + '&comments=' + comments + '&ci_token=' + token;
$.ajax({
type: "POST",
url: "review/update-review/<?php echo $yr; ?>",
data: dataString,
success: function(msg) {
if(msg == 1)
{
alert("Your review has been updated.");
}
else
{
alert("There was a problem updating your review. Please try again.");
}
}
});
return false; });
I think the problem may be down to the format of your data parameters. for
type : "POST"
then for
data : "{param1: 'param1', param2: 'param2'}"
do you have a tool like fiddler to view the communications between your browser and server. if not i would recommend downloading fiddler (it's free). it will give you a lot of insight as to what is actually happening behind the scenes and can give invaluable information about what might have gone wrong with an ajax style post.
The code looks pretty much fine to me, including the syntax. Still some possibilities arise, which are:-
The URL for executing the PHP code, which you are using in the example ("review/update-review/<?php echo $yr; ?>"), may be incorrectly given with reference to your current page.
The variables which you are using it here to capture the values of the INPUT elements, may be producing some extra special characters (like "&") which may lead to erroneous processing, resulting in the JavaScript problem.
Hope it helps.
For starters if(msg == 1) will not be == 1 because what your fetching is a string so it would b if(msg == '1').
Where you have
var dataString = 'area='+ area + '&january=' + january + '&target=' + target + '&achieved=' + ach + '&comments=' + comments + '&ci_token=' + token;
Change that to an object like so:
var dataObject = {
area : area,
january : january,
target : target,
achieved : ach,
comments : comments,
ci_token : token
}
and then change it in the ajax request to dataObject
Debug
Firefox: firbug.
if your using chrome hit Ctrl+Shift+J to open the javascript console and debug. look out for all the heaDers and data your sending and you can use console.log(varaible) to track the values of a variable.

Categories