Archive for category JavaScript

PHP CURL and AJAX

From http://stackoverflow.com/questions/19212293/mimicking-an-ajax-call-with-curl-php

I’m scraping a site using curl (via PHP) and some information I want is a list of products which is by default only showing the first few ones. The rest is passed to the user when they click a button to get the full list of products, which triggers an ajax call to return that list.

Here is in a nutshell the JS they use:

headers['__RequestVerificationToken'] = token;
$.ajax({
type: "post",
url: "/ajax/getProductList",
dataType: 'html',
data: JSON.stringify({ historyPageIndex: 1, displayPeriod: 0, productsType: All }),
contentType: 'application/json; charset=utf-8',
success: function (result) {
    $(target).html("");
    $(target).html(result);
},
beforeSend: function (XMLHttpRequest) {
    if (headers['__RequestVerificationToken']) {
        XMLHttpRequest.setRequestHeader("__RequestVerificationToken", headers['__RequestVerificationToken']);
    }
}
});

To set the request verification token as a header, more closely mimic an AJAX request, and set the content-type to JSON, use CURLOPT_HEADER.
curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Requested-With: XMLHttpRequest", "Content-Type: application/json; charset=utf-8", "__RequestVerificationToken: $token"));
PHP code
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieLocation);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieLocation);
curl_setopt($ch, CURLOPT_URL, 'https://www.domain.com/Applications/ViewProducts');
curl_setopt($ch, CURLOPT_REFERER, 'https://www.domain.com/');
$webpage = curl_exec($ch);
$productsType = trim(find_by_pattren($webpage, '<input id="productsType" name="productsType" type="hidden" value="(.*?)"'));
$token = trim(find_by_pattren($webpage, '<input name="__RequestVerificationToken" type="hidden" value="(.*?)"'));

$postVariables = json_encode(array('productsType' => $productsType,
'historyPageIndex' => 1,
'displayPeriod' => 0));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Requested-With: XMLHttpRequest", "Content-Type: application/json; charset=utf-8", "__RequestVerificationToken: $token"));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postVariables);
curl_setopt($ch, CURLOPT_URL, 'https://www.domain.com/ajax/getProductList');
curl_setopt($ch, CURLOPT_REFERER, 'https://www.domain.com/Applications/ViewProducts');
$webpage = curl_exec($ch);


                            
                        
Share

Tags: , ,

Multiple submit buttons in one form

To solve an issue in a web application, I searched for “multiple submit button in one form”. End up I found multiple ways. They both have advantages and disadvantages.

First approach, use the script to identify which submit button is pressed.

The example is from the internet. I just put them here for convenience. The following text are from  http://www.chami.com/tips/internet/042599i.html.

Wondering how to create an HTML form with more than a single submit button and check which of those buttons was pressed?

First, let's create a form with a single submit button called "Submit 1" (assuming that the script we're calling to handle the form submission or the ACTION attribute is "mulsub.asp").

<FORM action="mulsub.asp" method="post">
First name: <INPUT type="TEXT" name="FNAME"><BR>
<INPUT type="submit" name="bsubmit" value="Submit 1">
</FORM>
Listing #1 : HTML code. Download onesub.htm (0.26 KB).

Now let's add two more submit buttons to the form and call them "Submit 2" and "Submit 3."

<FORM action="mulsub.asp" method="post">
First name: <INPUT type="TEXT" name="FNAME"><BR>
<INPUT type="submit" name="bsubmit" value="Submit 1">

<INPUT type="submit" name="bsubmit" value="Submit 2">
<INPUT type="submit" name="bsubmit" value="Submit 3">
</FORM>
Listing #2 : HTML code. Download mulsub.htm (0.27 KB).

Note how we kept the name of all three submit buttons the same -- "bsubmit." The only difference is the "value" attribute with unique values -- "Submit 2" and "Submit 3." When we create the script, these unique values will help us to figure out which of the submit buttons was pressed.

Following is a sample Active Server Pages script to check for the submit button. We're simply checking the value of the button(s) named "bsubmit" and performing the appropriate action within the script.

<HTML><BODY>
<%
  btnID = "?"

  if Request.Form("bsubmit") = "Submit 1" then
    btnID = "1"
  elseif Request.Form("bsubmit") = "Submit 2" then
    btnID = "2"
  elseif Request.Form("bsubmit") = "Submit 3" then
    btnID = "3"
  end if
%>
Submit button ID: <%=btnID%>
</BODY></HTML>
Listing #3 : ASP/VBScript code. Download mulsub0.asp (0.28 KB).

Finally let's combine the HTML form tags and the script commands into a single ASP script.

<HTML>
<BODY>

<%
  btnID = "?"

  if Request.Form("bsubmit") = "Submit 1" then
    btnID = "1"
  elseif Request.Form("bsubmit") = "Submit 2" then
    btnID = "2"
  elseif Request.Form("bsubmit") = "Submit 3" then
    btnID = "3"
  end if
%>
Submit button ID: <%=btnID%><BR>

<FORM action="mulsub.asp" method="post">
First name: <INPUT type="TEXT" name="FNAME"><BR>
<INPUT type="submit" name="bsubmit" value="Submit 1">
<INPUT type="submit" name="bsubmit" value="Submit 2">
<INPUT type="submit" name="bsubmit" value="Submit 3">
</FORM>

</BODY>
</HTML>

Second approach, use javascript to control the submission process.

The following text is from http://blog.coderlab.us/2005/10/04/multiple-submit-buttons-in-a-form/.

At some point, people ask themselves “How can I have two submit buttons with different actions in one form?” Well, the approach I’ve used to accomplish this task is to ‘emulate’ the submit buttons with regular button controls and changing the form action based on what button was clicked.

In the following example I have a text field and 3 different buttons that will send the string to be searched to Google, MSN or Yahoo depending on what button the user clicks.

The Code

So, the JavaScript looks like this:

<script type="text/javascript">
<!--
    function IsBlankField(field){
	var j = 0;
	var chr;

	for(j; j < field.length; j++){
	    chr = field.charAt(j);

	    if(chr != "" && chr != " " && chr != "\n" && chr != "\t"){
		return false;
	    }
	}

	return true;
    }

    function SendTo(id){
        //shortening form elements
        var myForm      = document.getElementById('myForm');
        var txtSearch   = document.getElementById('wrdSearch');
	var srchURL;    // this variable will hold the URL of the search engine to be used
        var srchVar;    // this variable will hold the value of the text field 'name' which will hold the string to be searched 

        if(IsBlankField(txtSearch.value)){
            //if the form doesn't validate, send this alert
            alert("there's nothing to search for!");
        } else{
            if(id == "google"){
		srchURL = "http://www.google.com/search";
		srchVar = "q";
            } else if(id == "msn"){
		srchURL = "http://search.msn.com/results.aspx";
		srchVar = "q";
            } else{
		srchURL = "http://search.yahoo.com/search";
		srchVar = "p";
            }

            //adding the attribute name and values to the form and text field elements
	    myForm.setAttribute("action", srchURL);
	    txtSearch.setAttribute("name", srchVar);
	    myForm.setAttribute("target", "_blank"); //this, of course, will open a new browser window
	    myForm.setAttribute("method", "get");

            myForm.submit();           

        }
    }
//-->
</script>

And the HTML part looks like this:

<form name="myForm" id="myForm">
    Search: <input type="text" id="wrdSearch"/>
    <input type="button" name="google" id="google" value="Google" onClick="SendTo(this.id)"/>
    <input type="button" name="msn" id="msn" value="MSN" onClick="SendTo(this.id)"/>
    <input type="button" name="yahoo" id="yahoo" value="Yahoo" onClick="SendTo(this.id)"/>
</form>

Explanation

In the JavaScript, the IsBlankField(field) function takes as its argument the text field value and will check if it is empty or has space, new line or tab characters. If it does, the function will return true and the form will not validate.

if(IsBlankField(txtSearch.value)){
    //if the form doesn't validate, send this alert
     alert("there's nothing to search for!");
}

The SendTo(id) function takes one argument (the button id) so that we know what button triggered the event. Then we will add the attributes, with the correct values, to the form and text field elements using the DOM setAttribute() method. As you can see in the code sample, this method takes two parameters: the attribute name and the attribute value.

function SendTo(id){
    ....
    ....
    ....

    myForm.setAttribute("action", srchURL);
    txtSearch.setAttribute("name", srchVar); //this will add the name attribute to the text field element
    myForm.setAttribute("target", "_blank");
    myForm.setAttribute("method", "get");

Then, we submit the form.

    myForm.submit();
    ....
    ....
}

In the HTML, notice that the form does not have its name, action and method attributes (nor the text field has its name attribute). As I explained before, they are being added with the DOM setAttribute() method.

<form name="myForm" id="myForm">
    Search: <input type="text" id="wrdSearch"/>
    ....
    ....
</form>

 

Share

Tags: ,

JavaScript handling UTF8 characters

When I developed a PHP web application with AJAX. I encountered a problem that JavaScript cannot process utf-8 character correctly. Whenever user enter a UTF-8 string,
it was converted to ASCII in JavaScript and delivered to PHP script. The site is using UTF-8 characters and will be sure there are a lot of request using utf-8 characters. I googled “Javascript and utf-8” and find an article at http://ecmanaut.blogspot.com/2006/07/encoding-decoding-utf8-in-javascript.html. It provides two functions for the purpose. One function I will use is the decode_utf8. I simply copied these two functions and the second one did not work. I change the inner function from escape to unescape. After the change, I call the function decode_utf8(s).

Here are the two functions:
function encode_utf8( s )
{
return unescape( encodeURIComponent( s ) );
}

function decode_utf8( s )
{
return decodeURIComponent( unescape( s ) );
}

A JavaScript code snippet to call the function:

function search(php)
{
var keyword = window.document.forms["searchform"].elements["keyword"].value;
var url=php+"?cmd=search" +
"&keyword="+decode_utf8(keyword);
makeGETrequest2(url, link_callback);
}

Share

Tags: , , , , ,